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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
577b64c18d493e33e4f0613c7e472ff95ab5d8e6 | 545 | cpp | C++ | src/main.cpp | FFreestyler/EnglishWords | b8666404fa5e72e7cf447d33d1a8cd5d9c2115cd | [
"MIT"
] | 7 | 2020-05-17T06:00:37.000Z | 2020-05-30T02:58:46.000Z | src/main.cpp | FFreestyler/EnglishWords | b8666404fa5e72e7cf447d33d1a8cd5d9c2115cd | [
"MIT"
] | 7 | 2020-05-15T08:02:34.000Z | 2020-05-27T15:49:57.000Z | src/main.cpp | FFreestyler/EnglishWords | b8666404fa5e72e7cf447d33d1a8cd5d9c2115cd | [
"MIT"
] | null | null | null | #include "Start.hpp"
#include "menu.hpp"
#include <SFML/Graphics.hpp>
#include <functional>
#include <vector>
using namespace sf;
int main()
{
const int height = 480; // Window height
const int width = 720; // Window width
RenderWindow window(
VideoMode(width, height),
"English Words",
sf::Style::Close); // Create window
window.setVerticalSyncEnabled(true); // Enabled Vertical Sync
while (window.isOpen()) // Open window
{
menu(window);
}
return 0;
}
| 20.961538 | 65 | 0.60367 | [
"vector"
] |
577c8f46084e8aa78e70f8486270677313aec9bc | 2,841 | cpp | C++ | 07/07_stencil/03/boxblur.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | 1,276 | 2021-12-11T05:21:48.000Z | 2022-03-31T15:30:45.000Z | 07/07_stencil/03/boxblur.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | 7 | 2021-12-30T15:41:34.000Z | 2022-03-02T07:13:51.000Z | 07/07_stencil/03/boxblur.cpp | HuSharp/parallel101 | 882a35c254538a64d3594d112caa6d1bb5315903 | [
"CC0-1.0"
] | 196 | 2021-12-12T08:15:36.000Z | 2022-03-31T07:15:23.000Z | #include "boxblur.h"
#include <x86intrin.h>
void xblur(Image &b, Image const &a, int nblur) {
if (!nblur) { b = a; return; }
int nx = a.shape(0);
int ny = a.shape(1);
int ncomp = a.shape(2);
b.reshape((size_t)nx, (size_t)ny, (size_t)ncomp);
__m128 factor = _mm_set1_ps(1.f / (2 * nblur + 1));
for (int comp = 0; comp < ncomp; comp++) {
#pragma omp parallel for collapse(2)
for (int y = 0; y < ny; y++) {
for (int xBase = 0; xBase < nx; xBase += 16) {
_mm_prefetch(&a(xBase + 16, y, comp), _MM_HINT_T0);
for (int x = xBase; x < xBase + 16; x += 4) {
__m128 res = _mm_setzero_ps();
for (int t = -nblur; t <= nblur; t++) {
res = _mm_add_ps(res, _mm_loadu_ps(&a(x + t, y, comp)));
}
_mm_stream_ps(&b(x, y, comp), _mm_mul_ps(res, factor));
}
}
}
}
}
void yblur(Image &b, Image const &a, int nblur) {
if (!nblur) { b = a; return; }
int nx = a.shape(0);
int ny = a.shape(1);
int ncomp = a.shape(2);
b.reshape((size_t)nx, (size_t)ny, (size_t)ncomp);
__m256 factor = _mm256_set1_ps(1.f / (2 * nblur + 1));
for (int comp = 0; comp < ncomp; comp++) {
#pragma omp parallel for collapse(2)
for (int x = 0; x < nx; x += 32) {
for (int y = 0; y < ny; y++) {
_mm_prefetch(&a(x, y + nblur + 40, comp), _MM_HINT_T0);
_mm_prefetch(&a(x + 16, y + nblur + 40, comp), _MM_HINT_T0);
__m256 res[4];
#ifdef _MSC_VER
#pragma unroll 4
#else
#pragma GCC unroll 4
#endif
for (int offset = 0; offset < 4; offset++) {
res[offset] = _mm256_load_ps(&a(x + offset * 8, y - nblur, comp));
}
for (int t = -nblur + 1; t <= nblur; t++) {
#ifdef _MSC_VER
#pragma unroll 4
#else
#pragma GCC unroll 4
#endif
for (int offset = 0; offset < 4; offset++) {
res[offset] = _mm256_add_ps(res[offset],
_mm256_load_ps(&a(x + offset * 8, y + t, comp)));
}
}
#ifdef _MSC_VER
#pragma unroll 4
#else
#pragma GCC unroll 4
#endif
for (int offset = 0; offset < 4; offset++) {
res[offset] = _mm256_mul_ps(res[offset], factor);
}
#ifdef _MSC_VER
#pragma unroll 4
#else
#pragma GCC unroll 4
#endif
for (int offset = 0; offset < 4; offset++) {
_mm256_stream_ps(&b(x + offset * 8, y, comp), res[offset]);
}
}
}
}
}
void boxblur(Image &a, int nxblur, int nyblur) {
if (!nxblur && !nyblur) return;
Image b(a.shape());
xblur(b, a, nxblur);
yblur(a, b, nyblur);
}
| 32.284091 | 86 | 0.483985 | [
"shape"
] |
578185c940484ca931257d757483613f6cb079ab | 7,990 | cc | C++ | apps/clicky/src/hvalues.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | apps/clicky/src/hvalues.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | apps/clicky/src/hvalues.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | #ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <click/config.h>
#include "hvalues.hh"
#include "cdriver.hh"
#include <gdk/gdkkeysyms.h>
#include <click/confparse.hh>
extern "C" {
#include "interface.h"
#include "support.h"
}
namespace clicky {
/*****
*
* handler_value, including autorefresh
*
*/
const String handler_value::no_hvalue_string = String::make_stable("???", 3);
namespace {
struct autorefresher {
handler_value *hv;
crouter *cr;
int period;
autorefresher(handler_value *hv_, crouter *cr_, int period_)
: hv(hv_), cr(cr_), period(period_) {
}
};
extern "C" {
static gboolean on_autorefresh(gpointer user_data)
{
autorefresher *wa = reinterpret_cast<autorefresher *>(user_data);
return wa->hv->on_autorefresh(wa->cr, wa->period);
}
static void destroy_autorefresh(gpointer user_data) {
autorefresher *wa = reinterpret_cast<autorefresher *>(user_data);
delete wa;
}
}}
void handler_value::refresh(crouter *cr, bool clear_outstanding)
{
if (empty() && handler_name().equals("handlers", 8))
_flags |= hflag_r;
if (clear_outstanding)
_flags &= ~hflag_outstanding;
else if (_flags & hflag_outstanding)
return; // nothing to do
if (_flags & (hflag_r | hflag_rparam)) {
int read_flags = (_flags & hflag_raw ? 0 : cdriver::dflag_nonraw);
_flags |= hflag_outstanding;
if (cdriver *d = cr->driver())
d->do_read(_hname, _hparam, read_flags);
} else if (empty())
_flags |= hflag_outstanding;
}
void handler_value::create_autorefresh(crouter *cr)
{
autorefresher *a = new autorefresher(this, cr, _autorefresh_period);
_autorefresh_source = g_timeout_add_full
(G_PRIORITY_DEFAULT, _autorefresh_period,
clicky::on_autorefresh, a, destroy_autorefresh);
}
gboolean handler_value::on_autorefresh(crouter *cr, int period)
{
if ((_flags & hflag_autorefresh) != 0
&& readable()
&& cr->driver()) {
refresh(cr);
if (period != _autorefresh_period) {
create_autorefresh(cr);
return FALSE;
} else
return TRUE;
} else {
_autorefresh_source = 0;
return FALSE;
}
}
void handler_value::set_flags(crouter *cr, int new_flags)
{
if (_autorefresh_source
&& ((new_flags & hflag_autorefresh) == 0
|| (new_flags & hflag_r) == 0)) {
g_source_remove(_autorefresh_source);
_autorefresh_source = 0;
} else if (_autorefresh_source == 0
&& (new_flags & hflag_autorefresh) != 0
&& (new_flags & hflag_r))
create_autorefresh(cr);
if ((new_flags & hflag_have_hvalue) == 0)
_hvalue = (new_flags & hflag_r ? no_hvalue_string : String());
_flags = new_flags & ~hflag_private_mask;
_driver_mask &= ~(_flags ^ _driver_flags);
}
/*****
*
* handler_values
*
*/
handler_values::handler_values(crouter *cr)
: _cr(cr)
{
}
handler_values::iterator handler_values::begin(const String &ename)
{
HashTable<handler_value>::iterator iter = _hv.find(ename + ".handlers");
if (iter && (iter->_driver_flags & hflag_dead) == 0)
return iterator(iter.operator->());
else
return iterator(0);
}
handler_value *handler_values::set(const String &hname, const String &hparam, const String &hvalue, bool &changed)
{
if (hname.length() > 9 && memcmp(hname.end() - 9, ".handlers", 9) == 0)
set_handlers(hname, hparam, hvalue);
handler_value *hv = _hv.find_insert(hname).get();
changed = (!hv->have_hvalue() || hparam != hv->_hparam
|| hvalue != hv->_hvalue);
hv->_hparam = hparam;
hv->_hvalue = hvalue;
hv->_flags = (hv->_flags & ~hflag_outstanding) | hflag_have_hvalue;
return hv;
}
void handler_values::set_handlers(const String &hname, const String &, const String &hvalue)
{
assert(hname.length() > 9 && memcmp(hname.end() - 9, ".handlers", 9) == 0);
handler_value *handlers = _hv.find_insert(hname).get();
if (handlers && handlers->hvalue() == hvalue)
return;
Vector<handler_value *> old_handlers;
for (handler_value *v = handlers; v; v = v->_next) {
v->_driver_flags |= hflag_dead;
old_handlers.push_back(v);
}
handlers->_next = 0;
// parse handler data into _hinfo
const char *s = hvalue.begin();
bool syntax_error = false;
while (s != hvalue.end()) {
const char *name_start = s;
while (s != hvalue.end() && !isspace((unsigned char) *s))
++s;
if (s == name_start || s == hvalue.end() || *s != '\t') {
syntax_error = true;
break;
}
String name = hvalue.substring(name_start, s);
while (s != hvalue.end() && isspace((unsigned char) *s))
++s;
int flags = 0;
for (; s != hvalue.end() && !isspace((unsigned char) *s); ++s)
switch (*s) {
case 'r':
flags |= hflag_r;
break;
case 'w':
flags |= hflag_w;
break;
case '+':
flags |= hflag_rparam;
break;
case '%':
flags |= hflag_raw;
break;
case '.':
flags |= hflag_calm;
break;
case '$':
flags |= hflag_expensive;
break;
case 'b':
flags |= hflag_button;
break;
case 'c':
flags |= hflag_checkbox;
break;
case 'U':
flags |= hflag_uncommon;
break;
case 'D':
flags |= hflag_deprecated;
break;
}
if (!(flags & hflag_r))
flags &= ~hflag_rparam;
if (flags & hflag_r)
flags &= ~hflag_button;
if (flags & hflag_rparam)
flags &= ~hflag_checkbox;
// default appearance
if (name == "class" || name == "name")
flags |= hflag_special;
else if (name == "config")
flags |= hflag_multiline | hflag_special | hflag_visible | hflag_refresh;
else if (name == "ports" || name == "icounts" || name == "ocounts")
flags |= hflag_collapse | hflag_visible;
else if (name == "handlers")
flags |= hflag_collapse;
else if (!(flags & (hflag_uncommon | hflag_deprecated)))
flags |= hflag_visible;
if (handler_value::default_refreshable(flags))
flags |= hflag_refresh;
String full_name = hname.substring(0, hname.length() - 8) + name;
handler_value *v = _hv.find_insert(full_name).get();
if (v != handlers) {
v->_next = handlers->_next;
handlers->_next = v;
}
bool was_empty = v->empty();
v->set_driver_flags(_cr, flags);
if (was_empty || v->notify_delt())
_cr->on_handler_create(v, was_empty);
if ((v->_flags & hflag_autorefresh)
&& v->readable()
&& !v->_autorefresh_source)
v->create_autorefresh(_cr);
if (was_empty && (v->_flags & hflag_outstanding)) {
v->_flags &= ~hflag_outstanding;
if (flags & hflag_refresh)
v->refresh(_cr);
}
while (s != hvalue.end() && *s != '\r' && *s != '\n')
++s;
if (s + 1 < hvalue.end() && *s == '\r' && s[1] == '\n')
s += 2;
else if (s != hvalue.end())
++s;
}
for (handler_value **hv = old_handlers.begin(); hv != old_handlers.end();
++hv)
if ((*hv)->_flags & hflag_dead)
_hv.erase((*hv)->_hname);
}
handler_value *handler_values::hard_find_placeholder(const String &hname,
int flags,
int autorefresh_period)
{
if (!_cr->driver())
return 0;
int dot = hname.find_right('.');
String base = (dot > 0 ? hname.substring(0, dot + 1) : String());
handler_value *hh = _hv.find_insert(base + "handlers").get();
if (hh->have_hvalue())
return 0;
hh->refresh(_cr);
handler_value *hv = _hv.find_insert(hname).get();
hv->set_flags(_cr, hv->flags() | flags);
if (autorefresh_period > 10
&& hv->autorefresh_period() > autorefresh_period)
hv->set_autorefresh_period(autorefresh_period);
return hv;
}
void handler_values::clear()
{
Vector<String> interesting_elements;
for (HashTable<handler_value>::iterator it = _hv.begin();
it != _hv.end(); ++it) {
if (it->notify_delt() || it->notify_whandlers())
interesting_elements.push_back(it->element_name());
it->clear();
}
if (_cr->driver())
for (String *it = interesting_elements.begin();
it != interesting_elements.end(); ++it) {
String name = *it + (*it ? ".handlers" : "handlers");
handler_value *hh = _hv.find_insert(name).get();
hh->refresh(_cr);
}
}
}
| 26.026059 | 114 | 0.634668 | [
"vector"
] |
c2364bd103ad3ed67f6ce58af0556f93717ffdf0 | 7,385 | cpp | C++ | code/MikoEngine/Renderer/Resource/Scene/SceneNode.cpp | warzes/MikoEngine | 1199f59a71ab3dfcbea5d02238639db55eded0d4 | [
"MIT"
] | 5 | 2020-08-04T17:57:01.000Z | 2021-02-07T12:19:02.000Z | code/MikoEngine/Renderer/Resource/Scene/SceneNode.cpp | warzes/MikoEngine | 1199f59a71ab3dfcbea5d02238639db55eded0d4 | [
"MIT"
] | null | null | null | code/MikoEngine/Renderer/Resource/Scene/SceneNode.cpp | warzes/MikoEngine | 1199f59a71ab3dfcbea5d02238639db55eded0d4 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Renderer/Resource/Scene/SceneNode.h"
#include "Renderer/Resource/Scene/SceneResource.h"
#include "Renderer/Resource/Scene/Item/ISceneItem.h"
#include "Renderer/Resource/Scene/Item/Mesh/MeshSceneItem.h"
#include "Renderer/Resource/Scene/Culling/SceneItemSet.h"
#include "Renderer/Resource/Mesh/MeshResourceManager.h"
#include "Renderer/Resource/Mesh/MeshResource.h"
#include "Renderer/IRenderer.h"
// Disable warnings in external headers, we can't fix them
SE_PRAGMA_WARNING_PUSH
SE_PRAGMA_WARNING_DISABLE_MSVC(4464) // warning C4464: relative include path contains '..'
#include <glm/gtx/component_wise.hpp>
SE_PRAGMA_WARNING_POP
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
void SceneNode::attachSceneNode(SceneNode& sceneNode)
{
// TODO(co) Need to guarantee that one scene node is only attached to one scene node at the same time
mAttachedSceneNodes.push_back(&sceneNode);
sceneNode.mParentSceneNode = this;
sceneNode.updateGlobalTransformRecursive();
mPreviousGlobalTransform = mGlobalTransform; // Teleport since we don't have a decent incremental previous global transform
}
void SceneNode::detachAllSceneNodes()
{
for (SceneNode* sceneNode : mAttachedSceneNodes)
{
sceneNode->mParentSceneNode = nullptr;
sceneNode->updateGlobalTransformRecursive();
mPreviousGlobalTransform = mGlobalTransform; // Teleport since we don't have a decent incremental previous global transform
}
mAttachedSceneNodes.clear();
}
void SceneNode::setVisible(bool visible)
{
setSceneItemsVisible(visible);
for (SceneNode* sceneNode : mAttachedSceneNodes)
{
sceneNode->setVisible(visible);
}
}
void SceneNode::attachSceneItem(ISceneItem& sceneItem)
{
// TODO(co) Need to guarantee that one scene item is only attached to one scene node at the same time
mAttachedSceneItems.push_back(&sceneItem);
updateSceneItemTransform(sceneItem);
sceneItem.onAttachedToSceneNode(*this);
}
void SceneNode::detachAllSceneItems()
{
for (ISceneItem* sceneItem : mAttachedSceneItems)
{
sceneItem->onDetachedFromSceneNode(*this);
}
mAttachedSceneItems.clear();
}
void SceneNode::setSceneItemsVisible(bool visible)
{
for (ISceneItem* sceneItem : mAttachedSceneItems)
{
sceneItem->setVisible(visible);
}
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
void SceneNode::updateGlobalTransformRecursive()
{
// Backup the previous global transform
mPreviousGlobalTransform = mGlobalTransform;
// Update this node
if (nullptr != mParentSceneNode)
{
mGlobalTransform = mParentSceneNode->mGlobalTransform;
mGlobalTransform += mTransform;
}
else
{
mGlobalTransform = mTransform;
}
// Update scene items
for (ISceneItem* sceneItem : mAttachedSceneItems)
{
updateSceneItemTransform(*sceneItem);
}
// Update attached scene nodes
for (SceneNode* sceneNode : mAttachedSceneNodes)
{
sceneNode->mGlobalTransform = mGlobalTransform;
sceneNode->mGlobalTransform += sceneNode->mTransform;
sceneNode->updateGlobalTransformRecursive();
}
}
void SceneNode::updateSceneItemTransform(ISceneItem& sceneItem)
{
// TODO(co) The following is just for culling kickoff and won't stay this way
SceneItemSet* sceneItemSet = sceneItem.mSceneItemSet;
if (nullptr != sceneItemSet)
{
const uint32_t sceneItemSetIndex = sceneItem.mSceneItemSetIndex;
{ // Set object space to world space matrix
glm::mat4 objectSpaceToWorldSpace;
mGlobalTransform.getAsMatrix(objectSpaceToWorldSpace);
sceneItemSet->worldXX[sceneItemSetIndex] = objectSpaceToWorldSpace[0][0];
sceneItemSet->worldXY[sceneItemSetIndex] = objectSpaceToWorldSpace[1][0];
sceneItemSet->worldXZ[sceneItemSetIndex] = objectSpaceToWorldSpace[2][0];
sceneItemSet->worldXW[sceneItemSetIndex] = objectSpaceToWorldSpace[3][0];
sceneItemSet->worldYX[sceneItemSetIndex] = objectSpaceToWorldSpace[0][1];
sceneItemSet->worldYY[sceneItemSetIndex] = objectSpaceToWorldSpace[1][1];
sceneItemSet->worldYZ[sceneItemSetIndex] = objectSpaceToWorldSpace[2][1];
sceneItemSet->worldYW[sceneItemSetIndex] = objectSpaceToWorldSpace[3][1];
sceneItemSet->worldZX[sceneItemSetIndex] = objectSpaceToWorldSpace[0][2];
sceneItemSet->worldZY[sceneItemSetIndex] = objectSpaceToWorldSpace[1][2];
sceneItemSet->worldZZ[sceneItemSetIndex] = objectSpaceToWorldSpace[2][2];
sceneItemSet->worldZW[sceneItemSetIndex] = objectSpaceToWorldSpace[3][2];
sceneItemSet->worldWX[sceneItemSetIndex] = objectSpaceToWorldSpace[0][3];
sceneItemSet->worldWY[sceneItemSetIndex] = objectSpaceToWorldSpace[1][3];
sceneItemSet->worldWZ[sceneItemSetIndex] = objectSpaceToWorldSpace[2][3];
sceneItemSet->worldWW[sceneItemSetIndex] = objectSpaceToWorldSpace[3][3];
}
if (sceneItem.getSceneItemTypeId() == MeshSceneItem::TYPE_ID)
{
const MeshResource* meshResource = sceneItem.getSceneResource().getRenderer().getMeshResourceManager().tryGetById(static_cast<MeshSceneItem&>(sceneItem).getMeshResourceId());
if (nullptr != meshResource)
{
{ // Set world space center position of bounding sphere
const glm::vec3& boundingSpherePosition = meshResource->getBoundingSpherePosition();
const glm::dvec3& position = mGlobalTransform.position;
const glm::vec3& scale = mGlobalTransform.scale;
sceneItemSet->spherePositionX[sceneItemSetIndex] = static_cast<float>(boundingSpherePosition.x * scale.x + position.x);
sceneItemSet->spherePositionY[sceneItemSetIndex] = static_cast<float>(boundingSpherePosition.y * scale.y + position.y);
sceneItemSet->spherePositionZ[sceneItemSetIndex] = static_cast<float>(boundingSpherePosition.z * scale.z + position.z);
}
// Set negative world space radius of bounding sphere
sceneItemSet->negativeRadius[sceneItemSetIndex] = -meshResource->getBoundingSphereRadius() * glm::compMax(mGlobalTransform.scale);
}
else
{
// Set world space center position of bounding sphere
sceneItemSet->spherePositionX[sceneItemSetIndex] = static_cast<float>(mGlobalTransform.position.x);
sceneItemSet->spherePositionY[sceneItemSetIndex] = static_cast<float>(mGlobalTransform.position.y);
sceneItemSet->spherePositionZ[sceneItemSetIndex] = static_cast<float>(mGlobalTransform.position.z);
}
}
else
{
// Set world space center position of bounding sphere
sceneItemSet->spherePositionX[sceneItemSetIndex] = static_cast<float>(mGlobalTransform.position.x);
sceneItemSet->spherePositionY[sceneItemSetIndex] = static_cast<float>(mGlobalTransform.position.y);
sceneItemSet->spherePositionZ[sceneItemSetIndex] = static_cast<float>(mGlobalTransform.position.z);
}
}
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
| 39.704301 | 178 | 0.69587 | [
"mesh",
"object",
"transform"
] |
c23c044d60e2469fb2689a27643ace6668a23f44 | 2,665 | cpp | C++ | middleware/common/source/buffer/transport.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/common/source/buffer/transport.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/common/source/buffer/transport.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | 1 | 2022-02-21T18:30:25.000Z | 2022-02-21T18:30:25.000Z | //!
//! Copyright (c) 2015, The casual project
//!
//! This software is licensed under the MIT license, https://opensource.org/licenses/MIT
//!
#include "common/buffer/transport.h"
#include "common/buffer/pool.h"
#include "common/algorithm.h"
namespace casual
{
namespace common
{
namespace buffer
{
namespace transport
{
bool operator < ( const Context::Callback& lhs, const Context::Callback& rhs)
{
return lhs.order < rhs.order;
}
Context& Context::instance()
{
static Context singleton;
return singleton;
}
Context::Context()
= default;
void Context::registration( size_type order, std::vector< Lifecycle> lifecycles, std::vector< std::string> types, dispatch_type callback)
{
m_callbacks.emplace_back( order, std::move( lifecycles), std::move( types), std::move( callback));
algorithm::stable_sort( m_callbacks);
}
void Context::dispatch(
platform::buffer::raw::type& buffer,
platform::buffer::raw::size::type& size,
const std::string& service,
Lifecycle lifecycle,
const std::string& type)
{
auto predicate = [&]( const Callback& c){
return (c.lifecycles.empty() || algorithm::find( c.lifecycles, lifecycle))
&& (c.types.empty() || algorithm::find( c.types, type));
};
auto found = algorithm::find_if( m_callbacks, predicate);
while( found)
{
found->dispatch( buffer, size, service, lifecycle, type);
found++;
found = algorithm::find_if( found, predicate);
}
}
void Context::dispatch(
platform::buffer::raw::type& buffer,
platform::buffer::raw::size::type& size,
const std::string& service,
Lifecycle lifecycle)
{
dispatch( buffer, size, service, lifecycle, buffer::pool::Holder::instance().type( buffer));
}
Context::Callback::Callback( size_type order, std::vector< Lifecycle> lifecycles, std::vector< std::string> types, dispatch_type callback)
: order( order), lifecycles( std::move( lifecycles)), types( std::move( types)), dispatch( std::move( callback)) {}
} // transport
} // buffer
} // common
} // casual
| 30.284091 | 150 | 0.521951 | [
"vector"
] |
c23d7e323fb55d1e0f79c49bb23956bb827c428f | 3,385 | hpp | C++ | src/roerei/util/performance.hpp | Wassasin/roerei | 78a6b91819cc37fd7ac25a209f18a3f97c5db2f5 | [
"BSD-3-Clause"
] | 1 | 2019-02-11T14:57:25.000Z | 2019-02-11T14:57:25.000Z | src/roerei/util/performance.hpp | Wassasin/roerei | 78a6b91819cc37fd7ac25a209f18a3f97c5db2f5 | [
"BSD-3-Clause"
] | null | null | null | src/roerei/util/performance.hpp | Wassasin/roerei | 78a6b91819cc37fd7ac25a209f18a3f97c5db2f5 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <roerei/util/timer.hpp>
#include <roerei/util/guard.hpp>
#include <boost/optional.hpp>
#include <map>
#include <vector>
#include <stack>
#include <memory>
#include <chrono>
#include <string>
#include <functional>
#include <iostream>
namespace roerei
{
namespace test
{
class performance
{
public:
typedef std::string key_t;
typedef std::chrono::microseconds time_t;
private:
struct node_t
{
std::vector<time_t> durations;
std::map<key_t, std::shared_ptr<node_t>> children;
};
std::shared_ptr<node_t> root;
std::stack<std::shared_ptr<node_t>> stack;
static thread_local boost::optional<performance> singleton;
public:
performance()
: root(std::make_shared<node_t>())
, stack()
{
stack.emplace(root);
}
static performance& init()
{
if(!singleton)
singleton.reset(performance());
return *singleton;
}
static void clear()
{
singleton.reset();
}
void operator()(key_t const& key, timer const& t)
{
auto node = stack.top()->children.emplace(std::make_pair(key, std::make_shared<node_t>())).first->second;
node->durations.emplace_back(t.diff_msec());
}
void enter(key_t const& key)
{
auto next_node = stack.top()->children.emplace(std::make_pair(key, std::make_shared<node_t>())).first->second;
stack.emplace(next_node);
}
void leave(key_t const& key, timer const& t)
{
stack.pop();
(*this)(key, t);
}
template<typename F>
auto operator()(key_t const& key, F f) -> typename std::result_of<F()>::type
{
timer t;
enter(std::move(key));
auto g(make_guard([&]() {
leave(key, t);
}));
return f();
}
static void note_time(key_t const& key, timer const& t)
{
if(!singleton)
throw std::runtime_error("Singleton performance measurements are not initialized");
(*singleton)(key, t);
}
template<typename F>
static auto measure(key_t const& key, F f) -> typename std::result_of<F()>::type
{
if(!singleton)
throw std::runtime_error("Singleton performance measurements are not initialized");
return (*singleton)(key, f);
}
void print_indentation(std::ostream& os, size_t indent)
{
os << std::string(indent, ' ');
}
time_t report(node_t const& node, key_t const& key, size_t indent = 0)
{
time_t total = time_t::zero();
for(time_t const& d : node.durations)
total += d;
print_indentation(std::cerr, indent);
if(indent == 0) // Special root case
std::cerr << key << std::endl;
else
std::cerr << key << ": " << total.count() << "µs" << std::endl;
time_t subtotal = time_t::zero();
for(auto const& child_tup : node.children)
subtotal += report(*child_tup.second, child_tup.first, indent+1);
time_t missing = total - subtotal;
if(node.children.size() > 0 && missing.count() > 0)
{
print_indentation(std::cerr, indent+1);
std::cerr << "missing: " << missing.count() << "µs" << std::endl;
}
return total;
}
void report()
{
report(*root, "root");
}
};
#define performance_scope(name) \
timer _performance_t; \
std::string _performance_name(name); \
test::performance::init().enter(_performance_name); \
auto _performance_guard(make_guard([&]() { test::performance::init().leave(_performance_name, _performance_t); }));
#define performance_func performance_scope(__func__)
#define register_performance decltype(roerei::test::performance::singleton) thread_local roerei::test::performance::singleton;
}
}
| 21.15625 | 126 | 0.677991 | [
"vector"
] |
c240e9efda7cb23b02612137134ef58c2bb48003 | 1,357 | cpp | C++ | src/MergeSortP.cpp | AdrianBZG/Framework_Divide-and-Conquer | 2dd3f19af7369b48f941fb562eaffd2f1cbf05ca | [
"Apache-2.0"
] | 6 | 2016-03-10T21:33:40.000Z | 2016-04-11T17:15:16.000Z | src/MergeSortP.cpp | AdrianBZG/Framework_Divide-and-Conquer | 2dd3f19af7369b48f941fb562eaffd2f1cbf05ca | [
"Apache-2.0"
] | null | null | null | src/MergeSortP.cpp | AdrianBZG/Framework_Divide-and-Conquer | 2dd3f19af7369b48f941fb562eaffd2f1cbf05ca | [
"Apache-2.0"
] | null | null | null | /*
Author: Adrián Rodríguez Bazaga
Contact: arodriba@ull.edu.es / alu0100826456@ull.edu.es
Date: 05/03/2016
*/
#include "headers/MergeSortP.hpp"
MergeSortP::MergeSortP(vector<int> array) : Problem::Problem() {
array_ = array;
}
MergeSortP::~MergeSortP() {
}
bool MergeSortP::isSimple() {
return (array_.size() < 3);
}
pair<Problem*,Problem*> MergeSortP::decompose() {
pair<Problem*,Problem*> subProblems;
vector<int> U(array_.cbegin(),array_.cbegin()+array_.size()/2);
vector<int> V(array_.cbegin()+array_.size()/2,array_.cend());
subProblems.first = new MergeSortP(U);
subProblems.second = new MergeSortP(V);
return subProblems;
}
int& MergeSortP::getCount () {
return count_;
}
void MergeSortP::simplySolve(Solution* s) {
if (array_.size() == 1){
vector<int> U;
U.push_back(array_[0]);
array_ = U;
count_++; //Statistics
} else if (array_.size() == 2) {
vector<int> U = array_;
//Swap it if it's not correctly ordered
if(U[0] > U[1]) {
int aux = U[0];
U[0] = U[1];
U[1] = aux;
}
count_++; //Statistics
//
array_ = U;
} else if (array_.size() > 2) {
//Sort the elements
vector<int> U = array_;
sort(U.begin(), U.end());
array_ = U;
count_++; //Statistics
//
}
((MergeSortS*)s)->setValue(array_);
}
void MergeSortP::resetCount() {
count_ = 0;
}
int MergeSortP::count_ = 0;
| 19.666667 | 64 | 0.633751 | [
"vector"
] |
c241935ab2c66125b3024551939ab655e3f3b2c3 | 1,911 | cpp | C++ | apps/openmw/mwclass/static.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwclass/static.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwclass/static.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null |
#include "static.hpp"
#include <components/esm/loadstat.hpp>
#include "../mwworld/ptr.hpp"
#include "../mwworld/physicssystem.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwrender/objects.hpp"
#include "../mwrender/renderinginterface.hpp"
namespace MWClass
{
std::string Static::getId (const MWWorld::Ptr& ptr) const
{
return ptr.get<ESM::Static>()->mBase->mId;
}
void Static::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
{
MWWorld::LiveCellRef<ESM::Static> *ref =
ptr.get<ESM::Static>();
const std::string model = getModel(ptr);
if (!model.empty()) {
renderingInterface.getObjects().insertModel(ptr, model, !ref->mBase->mPersistent);
}
}
void Static::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
{
const std::string model = getModel(ptr);
if(!model.empty())
physics.addObject(ptr);
}
std::string Static::getModel(const MWWorld::Ptr &ptr) const
{
MWWorld::LiveCellRef<ESM::Static> *ref =
ptr.get<ESM::Static>();
assert(ref->mBase != NULL);
const std::string &model = ref->mBase->mModel;
if (!model.empty()) {
return "meshes\\" + model;
}
return "";
}
std::string Static::getName (const MWWorld::Ptr& ptr) const
{
return "";
}
void Static::registerSelf()
{
boost::shared_ptr<Class> instance (new Static);
registerClass (typeid (ESM::Static).name(), instance);
}
MWWorld::Ptr
Static::copyToCellImpl(const MWWorld::Ptr &ptr, MWWorld::CellStore &cell) const
{
MWWorld::LiveCellRef<ESM::Static> *ref =
ptr.get<ESM::Static>();
return MWWorld::Ptr(&cell.get<ESM::Static>().insert(*ref), &cell);
}
}
| 26.541667 | 120 | 0.599686 | [
"model"
] |
c2448de9a58fad845f2701cb70039790c1b263a9 | 6,749 | cc | C++ | apps/http-proxy/src/forwarder_interface.cc | srene/hicn | 354f916b5ec7a2b7d63d29d9019fc3e7fa2d1b89 | [
"Apache-2.0"
] | 47 | 2019-02-18T13:54:34.000Z | 2022-03-03T04:46:50.000Z | apps/http-proxy/src/forwarder_interface.cc | srene/hicn | 354f916b5ec7a2b7d63d29d9019fc3e7fa2d1b89 | [
"Apache-2.0"
] | 1 | 2019-09-09T09:14:43.000Z | 2019-09-09T09:14:43.000Z | apps/http-proxy/src/forwarder_interface.cc | srene/hicn | 354f916b5ec7a2b7d63d29d9019fc3e7fa2d1b89 | [
"Apache-2.0"
] | 28 | 2019-02-22T17:40:03.000Z | 2021-08-18T02:39:40.000Z | /*
* Copyright (c) 2020 Cisco and/or its affiliates.
* 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 <arpa/inet.h>
#include <hicn/http-proxy/forwarder_interface.h>
#include <hicn/transport/utils/log.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <unordered_set>
namespace transport {
ForwarderInterface::~ForwarderInterface() {}
int ForwarderInterface::connectToForwarder() {
sock_ = hc_sock_create();
if (!sock_) return -1;
if (hc_sock_connect(sock_) < 0) {
hc_sock_free(sock_);
sock_ = nullptr;
return -1;
}
return 0;
}
void ForwarderInterface::close() {
if (!closed_) {
internal_ioservice_.post([this]() {
work_.reset();
if (sock_) {
hc_sock_free(sock_);
sock_ = nullptr;
}
});
if (thread_->joinable()) {
thread_->join();
}
}
}
void ForwarderInterface::removeConnectedUserNow(uint32_t route_id) {
internalRemoveConnectedUser(route_id);
}
void ForwarderInterface::scheduleRemoveConnectedUser(uint32_t route_id) {
internal_ioservice_.post(
[this, route_id]() { internalRemoveConnectedUser(route_id); });
}
int32_t ForwarderInterface::getMainListenerPort() {
if (!sock_) return -1;
hc_data_t *data;
if (hc_listener_list(sock_, &data) < 0) return -1;
int ret = -1;
foreach_listener(l, data) {
std::string interface = std::string(l->interface_name);
if (interface.compare("lo") != 0) {
ret = l->local_port;
break;
}
}
hc_data_free(data);
return ret;
}
void ForwarderInterface::internalRemoveConnectedUser(uint32_t route_id) {
auto it = route_status_.find(route_id);
if (it == route_status_.end()) return;
if (!sock_) return;
// remove route
hc_data_t *data;
if (hc_route_list(sock_, &data) < 0) return;
std::vector<hc_route_t *> routes_to_remove;
foreach_route(r, data) {
char remote_addr[INET6_ADDRSTRLEN];
int ret = ip_address_ntop(&r->remote_addr, remote_addr, r->len, r->family);
if (ret < 0) continue;
std::string route_addr(remote_addr);
if (route_addr.compare(it->second->route_addr) == 0 &&
r->len == it->second->route_len) {
// route found
routes_to_remove.push_back(r);
}
}
route_status_.erase(it);
if (routes_to_remove.size() == 0) {
// nothing to do here
hc_data_free(data);
return;
}
std::unordered_set<uint32_t> connids_to_remove;
for (unsigned i = 0; i < routes_to_remove.size(); i++) {
connids_to_remove.insert(routes_to_remove[i]->face_id);
if (hc_route_delete(sock_, routes_to_remove[i]) < 0) {
TRANSPORT_LOG_ERROR << "Error removing route from forwarder.";
}
}
// remove connection
if (hc_connection_list(sock_, &data) < 0) {
hc_data_free(data);
return;
}
// collects pointerst to the connections using the conn IDs
std::vector<hc_connection_t *> conns_to_remove;
foreach_connection(c, data) {
if (connids_to_remove.find(c->id) != connids_to_remove.end()) {
// conn found
conns_to_remove.push_back(c);
}
}
if (conns_to_remove.size() == 0) {
// nothing else to do here
hc_data_free(data);
return;
}
for (unsigned i = 0; i < conns_to_remove.size(); i++) {
if (hc_connection_delete(sock_, conns_to_remove[i]) < 0) {
TRANSPORT_LOG_ERROR << "Error removing connection from forwarder.";
}
}
hc_data_free(data);
}
void ForwarderInterface::internalCreateFaceAndRoute(RouteInfoPtr route_info,
uint8_t max_try,
asio::steady_timer *timer,
SetRouteCallback callback) {
int ret = tryToCreateFaceAndRoute(route_info.get());
if (ret < 0 && max_try > 0) {
max_try--;
timer->expires_from_now(std::chrono::milliseconds(500));
timer->async_wait([this, _route_info = std::move(route_info), max_try,
timer, callback](std::error_code ec) {
if (ec) return;
internalCreateFaceAndRoute(std::move(_route_info), max_try, timer,
std::move(callback));
});
return;
}
if (max_try == 0 && ret < 0) {
pending_add_route_counter_--;
external_ioservice_.post([callback]() { callback(false, ~0); });
} else {
pending_add_route_counter_--;
route_status_[route_id_] = std::move(route_info);
external_ioservice_.post(
[route_id = route_id_, callback]() { callback(route_id, true); });
route_id_++;
}
delete timer;
}
int ForwarderInterface::tryToCreateFaceAndRoute(route_info_t *route_info) {
if (!sock_) return -1;
hc_data_t *data;
if (hc_listener_list(sock_, &data) < 0) {
return -1;
}
bool found = false;
uint32_t face_id;
foreach_listener(l, data) {
std::string interface = std::string(l->interface_name);
if (interface.compare("lo") != 0) {
found = true;
ip_address_t remote_ip;
if (ip_address_pton(route_info->remote_addr.c_str(), &remote_ip) < 0) {
hc_data_free(data);
return -1;
}
hc_face_t face;
memset(&face, 0, sizeof(hc_face_t));
face.face.type = FACE_TYPE_UDP;
face.face.family = route_info->family;
face.face.local_addr = l->local_addr;
face.face.remote_addr = remote_ip;
face.face.local_port = l->local_port;
face.face.remote_port = route_info->remote_port;
if (netdevice_set_name(&face.face.netdevice, l->interface_name) < 0) {
hc_data_free(data);
return -1;
}
if (hc_face_create(sock_, &face) < 0) {
hc_data_free(data);
return -1;
}
face_id = face.id;
break;
}
}
if (!found) {
hc_data_free(data);
return -1;
}
ip_address_t route_ip;
hc_route_t route;
if (ip_address_pton(route_info->route_addr.c_str(), &route_ip) < 0) {
hc_data_free(data);
return -1;
}
route.face_id = face_id;
route.family = AF_INET6;
route.remote_addr = route_ip;
route.len = route_info->route_len;
route.cost = 1;
if (hc_route_create(sock_, &route) < 0) {
hc_data_free(data);
return -1;
}
hc_data_free(data);
return 0;
}
} // namespace transport
| 25.564394 | 80 | 0.639798 | [
"vector"
] |
c247b1317056852b569ec04ae28b50eb09ec73b6 | 566 | cc | C++ | tddd38-cpp/play/pmf/ply.cc | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | tddd38-cpp/play/pmf/ply.cc | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | tddd38-cpp/play/pmf/ply.cc | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
struct A {
static int cnt;
void print(ostream& os){
cnt++;
os << cnt << endl;;
}
static void print_(ostream& os){
cnt++;
os << cnt << endl;;
}
};
int A::cnt = 0;
int main() {
vector<A*> vecA {
new A{},
new A{},
new A{}
};
for (auto v : vecA)
v->print(cout);
cout << endl;
for (auto v : vecA)
v->print_(cout);
cout << endl;
for (auto v : vecA)
delete v;
return 0;
} | 13.47619 | 36 | 0.452297 | [
"vector"
] |
c24adc943e911e19a184dab344432d3184e3788b | 1,124 | cpp | C++ | C++/incremental-memory-leak.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/incremental-memory-leak.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/incremental-memory-leak.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(1)
// Space: O(1)
// Same problem from https://codingcompetitions.withgoogle.com/codejam/round/000000000019ffb9/00000000003384ea
class Solution {
public:
vector<int> memLeak(int memory1, int memory2) {
bool is_swapped = false;
if (memory1 < memory2) {
swap(memory1, memory2);
is_swapped = true;
}
int n = f(1, 1, memory1 - memory2);
memory1 -= s(1, 1, n);
if (memory1 == memory2) {
is_swapped = false;
}
int l = f(n + 1, 2, memory1);
int r = f(n + 2, 2, memory2);
memory1 -= s(n + 1, 2, l);
memory2 -= s(n + 2, 2, r);
if (is_swapped) {
swap(memory1, memory2);
}
return {n + l + r + 1, memory1, memory2};
}
private:
int s(int a, int d, int n) {
return (2LL * a + (n - 1) * d) * n / 2;
}
int f(int a, int d, int x) {
int r = (-(2LL * a - d) + sqrt((2LL * a - d) * (2LL * a - d) + 8LL * d * x)) / (2 * d);
if (s(a, d, r) > x) { // adjust float accuracy
--r;
}
return r;
}
};
| 27.414634 | 110 | 0.461744 | [
"vector"
] |
c24e4a027198b17529f348aec602a6c8b35577a4 | 3,672 | cpp | C++ | Hexeng2D/src/Renderer/Shader.cpp | Ily3s/Hexeng2D | 9e81618fc27b45a347abadc6f60f896ab28cbe6b | [
"MIT"
] | null | null | null | Hexeng2D/src/Renderer/Shader.cpp | Ily3s/Hexeng2D | 9e81618fc27b45a347abadc6f60f896ab28cbe6b | [
"MIT"
] | null | null | null | Hexeng2D/src/Renderer/Shader.cpp | Ily3s/Hexeng2D | 9e81618fc27b45a347abadc6f60f896ab28cbe6b | [
"MIT"
] | null | null | null | #include "Shader.hpp"
#include "../Macros.hpp"
#include "Camera.hpp"
#include "Renderer.hpp"
#include "Uniform.hpp"
namespace Hexeng::Renderer
{
unsigned int Shader::compile_shader(GLenum shader_type, const char* src)
{
HXG_GL(unsigned int id = glCreateShader(shader_type));
HXG_GL(glShaderSource(id, 1, &src, nullptr));
HXG_GL(glCompileShader(id));
int compile_status;
HXG_GL(glGetShaderiv(id, GL_COMPILE_STATUS, &compile_status));
if (compile_status == GL_FALSE)
{
int lenght;
HXG_GL(glGetShaderiv(id, GL_INFO_LOG_LENGTH, &lenght));
char* message = (char*)_malloca(lenght);
HXG_GL(glGetShaderInfoLog(id, lenght, &lenght, message));
std::cout << "Failed to compile " << (shader_type == GL_VERTEX_SHADER ? "vertex" : "fragment") << " shader!" << std::endl;
std::cout << message << std::endl;
HXG_GL(glDeleteShader(id));
return 0;
}
return id;
}
unsigned int Shader::compile_shader(GLenum shader_type, const std::string& source)
{
const char* src = source.c_str();
return compile_shader(shader_type, src);
}
unsigned int Shader::create_shader(const char* vertex_shader, const char* fragment_shader)
{
HXG_GL(unsigned int prog = glCreateProgram());
unsigned int vs = compile_shader(GL_VERTEX_SHADER, vertex_shader);
unsigned int fs = compile_shader(GL_FRAGMENT_SHADER, fragment_shader);
HXG_GL(glAttachShader(prog, vs));
HXG_GL(glAttachShader(prog, fs));
HXG_GL(glLinkProgram(prog));
HXG_GL(glValidateProgram(prog));
HXG_GL(glDeleteShader(vs));
HXG_GL(glDeleteShader(fs));
return prog;
}
unsigned int Shader::create_shader(const std::string& vertex_shader, const std::string& fragment_shader)
{
const char* vs = vertex_shader.c_str();
const char* fs = fragment_shader.c_str();
return create_shader(vs, fs);
}
Shader::Shader(const char* vs, const char* fs)
: m_id(create_shader(vs, fs))
{
if (unsigned int missing = missing_uniforms())
std::cout << "[Warning] " << missing << " necessary uniforms are missing in a shader" << std::endl;
ToBeDelete(this, [this]() { this->~Shader(); });
}
Shader::Shader(const std::string& vs, const std::string& fs)
: m_id(create_shader(vs, fs))
{
if (unsigned int missing = missing_uniforms())
std::cout << "[Warning] " << missing << " necessary uniforms are missing in a shader" << std::endl;
ToBeDelete(this, [this]() { this->~Shader(); });
}
void Shader::bind() const
{
HXG_GL(glUseProgram(m_id));
}
void Shader::unbind() const
{
HXG_GL(glUseProgram(0));
}
int Shader::get_uniform(const char* uniform) const
{
HXG_GL(int res = glGetUniformLocation(m_id, uniform));
return res;
}
Shader::~Shader()
{
if (m_id)
{
HXG_GL(glDeleteProgram(m_id));
m_id = 0;
}
}
Shader::Shader(Shader&& other) noexcept
: m_id(other.m_id)
{
other.m_id = 0;
ToBeDelete(this, [this]() { this->~Shader(); });
ToBeDelete::remove(&other);
}
Shader& Shader::operator=(Shader&& other) noexcept
{
m_id = other.m_id;
other.m_id = 0;
ToBeDelete(this, [this]() { this->~Shader(); });
ToBeDelete::remove(&other);
return *this;
}
std::vector<UniformInterface*> UniformInterface::necessary_uniforms;
unsigned int Shader::missing_uniforms()
{
unsigned int output = 0;
for (UniformInterface* ui : UniformInterface::necessary_uniforms)
{
if (get_uniform(ui->uniform_name.c_str()) == -1)
output++;
}
return output;
}
void Shader::add_uniforms(const std::vector<UniformInterface*>& uniforms)
{
for (UniformInterface* ui : uniforms)
ui->add_shaders({ this });
}
void Shader::add_necessary_uniforms()
{
add_uniforms(UniformInterface::necessary_uniforms);
}
} | 24.48 | 125 | 0.686547 | [
"vector"
] |
c24efc43bfc48f1ad6d917a56e06307d73edbdd2 | 1,311 | cpp | C++ | chapter_2/MergeSort.cpp | chistyakoviv/introduction-to-algorithms | ef3593082390d1ffbdcfc65721d4bd0244a8b901 | [
"MIT"
] | null | null | null | chapter_2/MergeSort.cpp | chistyakoviv/introduction-to-algorithms | ef3593082390d1ffbdcfc65721d4bd0244a8b901 | [
"MIT"
] | null | null | null | chapter_2/MergeSort.cpp | chistyakoviv/introduction-to-algorithms | ef3593082390d1ffbdcfc65721d4bd0244a8b901 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
void merge(std::vector<int32_t>& A, size_t p, size_t q, size_t r)
{
size_t n1 = q - p + 1;
size_t n2 = r - q;
// We won't be using sentinels, so we don't need extra space
int32_t L[n1], R[n2];
for (size_t i = 0; i < n1; i++)
L[i] = A[p + i];
for (size_t i = 0; i < n2; i++)
R[i] = A[q + i + 1];
size_t i = 0, j = 0, k = p;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
A[k++] = L[i++];
else
A[k++] = R[j++];
}
// Copy the rest back to A
while (i < n1)
A[k++] = L[i++];
while (j < n2)
A[k++] = R[j++];
}
void mergeSort(std::vector<int32_t>& A, size_t p, size_t r)
{
if (p < r)
{
size_t q = (p + r) / 2;
mergeSort(A, p, q);
mergeSort(A, q + 1, r);
merge(A, p, q, r);
}
}
int main()
{
std::vector<int32_t> in;
int32_t value;
std::cout << "Input your numbers (0 terminates the input procedure): ";
do
{
std::cin >> value;
in.push_back(value);
} while (value != 0);
mergeSort(in, 0, in.size() - 1);
std::cout << "\nSorted sequence:\n";
std::cout << "[ ";
for (auto v: in)
{
std::cout << v << " ";
}
std::cout << "]\n\n";
}
| 19.279412 | 75 | 0.437071 | [
"vector"
] |
c250a226363698c8b407b66d13a397ed348a903a | 2,941 | cpp | C++ | SPOJ/SPOJ - DYNACON1/Accepted (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | SPOJ/SPOJ - DYNACON1/Accepted (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | SPOJ/SPOJ - DYNACON1/Accepted (2).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2019-09-16 19:11:23
* solution_verdict: Accepted language: C++
* run_time (ms): 350 memory_used (MB): 34.8
* problem: https://vjudge.net/problem/SPOJ-DYNACON1
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e5;
map<pair<int,int>,vector<pair<int,int> > >mp;
vector<pair<int,int> >seg[5*N+2];
vector<vector<int> >qr;stack<pair<int,int> >st;
int tim,q,n,component,track[N+2],cnt,par[N+2],sz[N+2],ans[N+2];
void init(void)
{
for(int i=1;i<=n;i++)par[i]=i,sz[i]=1;
component=n;
}
void clear()
{
mp.clear();cnt=0,tim=0;qr.clear();
while(st.size())st.pop();
for(int i=0;i<=N;i++)track[i]=0;
for(int i=0;i<=5*N;i++)
seg[i].clear();
}
void add(int node,int lo,int hi,int lt,int rt,pair<int,int>p)
{
if(lo>rt||hi<lt)return ;
if(lo>=lt&&hi<=rt)
{
seg[node].push_back(p);return ;
}
int md=(lo+hi)/2;
add(node*2,lo,md,lt,rt,p);
add(node*2+1,md+1,hi,lt,rt,p);
}
int find(int x)
{
if(x==par[x])return x;
return find(par[x]);//no path compression
}
void rollBack(int now)//deleting what was added in this segment
{
while(st.size()>now)
{
int r1=st.top().first,r2=st.top().second;st.pop();
par[r1]=r1;sz[r2]-=sz[r1];
component++;
}
}
void divide(int node,int lo,int hi)
{
int now=st.size();//remembering the size before entering the segment
for(auto x:seg[node])
{
int r1=find(x.first),r2=find(x.second);
if(r1==r2)continue;
if(sz[r1]>sz[r2])swap(r1,r2);
par[r1]=r2;sz[r2]+=sz[r1];
st.push({r1,r2});component--;
}
if(lo==hi)
{
if(track[lo])
ans[qr[track[lo]-1][0]]=(find(qr[track[lo]-1][1])==find(qr[track[lo]-1][2]));
rollBack(now);return ;
}
int md=(lo+hi)/2;
divide(node*2,lo,md);divide(node*2+1,md+1,hi);
rollBack(now);
}
void addQuery(int ty,int u,int v)
{
if(u>v)swap(u,v);++tim;
if(ty==3)track[tim]=qr.size()+1,qr.push_back({++cnt,u,v});
else
{
if(ty==1)mp[{u,v}].push_back({tim,q});//active from tm to end;
else mp[{u,v}].back().second=tim;//edge is removed;
}
}
void solve()
{
//add all query to the segment tree
for(auto x:mp)
for(auto z:x.second)
add(1,1,q,z.first,z.second,x.first);
divide(1,1,q);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
cin>>n>>q;init();
for(int i=1;i<=q;i++)
{
string ch;cin>>ch;int u,v;cin>>u>>v;
if(ch=="conn")addQuery(3,u,v);
else if(ch=="add")addQuery(1,u,v);
else addQuery(2,u,v);
}
solve();
for(int i=1;i<=cnt;i++)
{
if(ans[i])cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
} | 26.736364 | 111 | 0.518871 | [
"vector"
] |
c2561d0ae46763485f1148c0c9761e3b65c4b691 | 1,886 | cc | C++ | cmake/tribits/examples/TribitsExampleProject/packages/mixed_lang/test/tstRay_Tracer.cc | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 82 | 2016-02-04T18:38:25.000Z | 2022-03-29T03:01:49.000Z | cmake/tribits/examples/TribitsExampleProject/packages/mixed_lang/test/tstRay_Tracer.cc | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 206 | 2015-11-20T01:57:47.000Z | 2022-03-31T21:12:04.000Z | cmake/tribits/examples/TribitsExampleProject/packages/mixed_lang/test/tstRay_Tracer.cc | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 68 | 2016-01-13T22:46:51.000Z | 2022-03-31T06:25:05.000Z | //---------------------------------------------------------------------------//
// tstRay_Tracer.cc
//---------------------------------------------------------------------------//
#include <cmath>
#include <iostream>
#include "Ray_Tracer.hh"
using namespace std;
typedef tribits_mixed::Ray_Tracer Tracer;
typedef Tracer::Vec_Dbl Vec_Dbl;
typedef Tracer::Space_Vector Space_Vector;
int nfail;
int npass;
#define UNIT_TEST(a) if (!a){ ++nfail; } else { ++npass; }
//---------------------------------------------------------------------------//
void test_tracing()
{
// make simple mesh 5x5x5
Vec_Dbl x(6, 0.0), y(6, 0.0), z(6, 0.0);
double dx = 0.1, dy = 0.15, dz = 0.05;
for (int n = 1; n < 6; ++n)
{
x[n] = x[n-1] + dx;
y[n] = y[n-1] + dy;
z[n] = z[n-1] + dz;
}
// interaction probabilities (cross sections)
int N = 125;
Vec_Dbl sigma(N, 1.1);
// make the ray tracer
Tracer t(x, y, z, sigma);
// starting point
Space_Vector b(0.12, 0.44, 0.21);
Space_Vector e(0.43, 0.11, 0.08);
double tau = t.ray_trace(b, e);
double ref = 0.47106262853255509 * 1.1;
UNIT_TEST(fabs(tau - ref) < 1.0e-12 * ref);
}
//---------------------------------------------------------------------------//
int main(int argc, char *argv[])
{
nfail = 0;
npass = 0;
test_tracing();
cout << "Number of passing tests: " << npass << endl;
cout << "Number of failing tests: " << nfail << endl;
if (nfail == 0)
{
cout << "End Result: TEST PASSED" << endl;
}
else
{
cout << "End Result: TEST FAILED" << endl;
return 1;
}
return 0;
}
//---------------------------------------------------------------------------//
// end of tstRay_Tracer.cc
//---------------------------------------------------------------------------//
| 23.575 | 79 | 0.407741 | [
"mesh"
] |
c25f4d1ee43fab9dbddae6acc277828473631997 | 2,173 | cpp | C++ | MumbleVoipModule/Participant.cpp | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | 1 | 2018-04-02T15:38:10.000Z | 2018-04-02T15:38:10.000Z | MumbleVoipModule/Participant.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | null | null | null | MumbleVoipModule/Participant.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | 1 | 2021-09-04T12:37:34.000Z | 2021-09-04T12:37:34.000Z | #include "StableHeaders.h"
#include "Participant.h"
#include "User.h"
namespace MumbleVoip
{
Participant::Participant(QString name, MumbleLib::User* user) :
muted_(false),
speaking_(false),
position_known_(false),
position_(0.0, 0.0, 0.0),
user_(user),
name_(name)
{
avatar_uuid_ = user_->Name();
connect(user_, SIGNAL(StartReceivingAudio()), SLOT(OnStartSpeaking()) );
connect(user_, SIGNAL(StopReceivingAudio()), SLOT(OnStopSpeaking()) );
connect(user_, SIGNAL(PositionUpdated()), SLOT(OnPositionUpdated()) );
connect(user_, SIGNAL(Left()), SLOT(OnUserLeft()) );
}
Participant::~Participant()
{
}
QString Participant::Name() const
{
return name_;
}
QString Participant::AvatarUUID() const
{
return avatar_uuid_;
}
bool Participant::IsSpeaking() const
{
return speaking_;
}
void Participant::Mute(bool mute)
{
muted_ = mute;
}
bool Participant::IsMuted() const
{
return muted_;
}
Vector3df Participant::Position() const
{
return position_;
}
void Participant::Add(MumbleLib::User* user)
{
user_ = user;
}
void Participant::OnStartSpeaking()
{
speaking_ = true;
emit Communications::InWorldVoice::ParticipantInterface::StartSpeaking();
}
void Participant::OnStopSpeaking()
{
speaking_ = false;
emit Communications::InWorldVoice::ParticipantInterface::StopSpeaking();
}
void Participant::OnPositionUpdated()
{
//! @todo ENSURE THAT user_ OBJECT IS NOT DELETED
if (!user_)
return;
position_ = user_->Position();
}
MumbleLib::User* Participant::UserPtr() const
{
return user_;
}
void Participant::OnUserLeft()
{
emit Communications::InWorldVoice::ParticipantInterface::Left();
}
void Participant::SetName(QString name)
{
name_ = name;
emit Communications::InWorldVoice::ParticipantInterface::StateChanged();
}
} // MumbleVoip
| 21.73 | 81 | 0.597791 | [
"object"
] |
c264db986572b7bbf27e19ed24024e2c53d43392 | 2,200 | cpp | C++ | lib/vector_reserve_test.cpp | CarloWood/noexcept_benchmark | 273bf14050378f47978ffb3ba70c0c4d1a83ad8c | [
"Apache-2.0"
] | 15 | 2019-02-11T18:58:23.000Z | 2022-01-20T21:46:24.000Z | lib/vector_reserve_test.cpp | CarloWood/noexcept_benchmark | 273bf14050378f47978ffb3ba70c0c4d1a83ad8c | [
"Apache-2.0"
] | 2 | 2020-04-09T19:30:06.000Z | 2021-08-11T13:05:06.000Z | lib/vector_reserve_test.cpp | CarloWood/noexcept_benchmark | 273bf14050378f47978ffb3ba70c0c4d1a83ad8c | [
"Apache-2.0"
] | 1 | 2019-07-26T14:34:02.000Z | 2019-07-26T14:34:02.000Z | /*
Copyright Niels Dekker, LKEB, Leiden University Medical Center
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.txt
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 "noexcept_benchmark.h"
#include <algorithm>
#include <vector>
#include <cstring>
#ifdef _MSC_VER // Microsoft Visual C++
# pragma warning(disable: 4996) // 'strcpy': This function or variable may be unsafe
#endif
namespace
{
class my_string
{
char* m_data = nullptr;
public:
my_string() = default;
explicit my_string(std::size_t arg)
:
m_data{ (arg == 0) ? nullptr : new char[arg + 1] }
{
if (arg > 0)
{
// Ensure that strlen(m_data) == arg, so that my_string 'knows' its buffer size.
std::fill_n(m_data, arg, ' ');
m_data[arg] = '\0';
}
}
my_string(const my_string& arg)
:
m_data{ arg.m_data }
{
if (m_data != nullptr)
{
m_data = std::strcpy(
new char[std::strlen(m_data) + 1], m_data);
}
}
my_string(my_string&& arg) OPTIONAL_EXCEPTION_SPECIFIER
:
m_data{ arg.m_data }
{
arg.m_data = nullptr;
}
my_string& operator=(const my_string& arg)
{
*this = my_string{ arg };
return *this;
}
my_string& operator=(my_string&& arg) OPTIONAL_EXCEPTION_SPECIFIER
{
m_data = arg.m_data;
arg.m_data = nullptr;
return *this;
}
~my_string()
{
delete[] m_data;
}
};
}
NOEXCEPT_BENCHMARK_SHARED_LIB_EXPORT
double LIB_NAME::test_vector_reserve()
{
std::vector<my_string> strings(NOEXCEPT_BENCHMARK_INITIAL_VECTOR_SIZE, my_string(1));
return noexcept_benchmark::profile_func_call([&strings]
{
strings.reserve(strings.capacity() + 1);
});
}
| 22.44898 | 88 | 0.649091 | [
"vector"
] |
c26e6e48e4007f486d3f75fabd987e46dfc0094f | 3,368 | cc | C++ | xpp_states/src/state.cc | innorobotics/xpp | 5527b2820247c712dba622872a15f0242c2c60ed | [
"BSD-3-Clause"
] | 243 | 2017-11-08T17:10:59.000Z | 2022-03-29T12:56:51.000Z | xpp_states/src/state.cc | innorobotics/xpp | 5527b2820247c712dba622872a15f0242c2c60ed | [
"BSD-3-Clause"
] | 13 | 2017-12-22T13:13:53.000Z | 2021-06-05T12:24:50.000Z | xpp_states/src/state.cc | innorobotics/xpp | 5527b2820247c712dba622872a15f0242c2c60ed | [
"BSD-3-Clause"
] | 91 | 2017-10-27T23:27:24.000Z | 2022-02-02T07:38:09.000Z | /******************************************************************************
Copyright (c) 2017, Alexander W. Winkler. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder 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 <vector>
#include <xpp_states/state.h>
namespace xpp {
StateLinXd::StateLinXd (int dim)
{
kNumDim = dim;
p_ = VectorXd::Zero(dim);
v_ = VectorXd::Zero(dim);
a_ = VectorXd::Zero(dim);
}
StateLinXd::StateLinXd (const VectorXd& _p,
const VectorXd& _v,
const VectorXd& _a)
:StateLinXd(_p.rows())
{
p_ = _p;
v_ = _v;
a_ = _a;
}
StateLinXd::StateLinXd (const VectorXd& _p)
:StateLinXd(_p.rows())
{
p_ = _p;
}
const VectorXd
StateLinXd::GetByIndex (MotionDerivative deriv) const
{
switch (deriv) {
case kPos: return p_; break;
case kVel: return v_; break;
case kAcc: return a_; break;
default: throw std::runtime_error("[StateLinXd::GetByIndex] derivative not part of state");
}
}
VectorXd&
StateLinXd::GetByIndex (MotionDerivative deriv)
{
switch (deriv) {
case kPos: return p_; break;
case kVel: return v_; break;
case kAcc: return a_; break;
default: throw std::runtime_error("[StateLinXd::GetByIndex] derivative not part of state");
}
}
StateLin3d::StateLin3d (const StateLinXd& state_xd) : StateLinXd(3)
{
assert(state_xd.kNumDim == 3);
p_ = state_xd.p_;
v_ = state_xd.v_;
a_ = state_xd.a_;
}
StateLin2d
StateLin3d::Get2D() const
{
StateLin2d p2d;
p2d.p_ = p_.topRows<kDim2d>();
p2d.v_ = v_.topRows<kDim2d>();
p2d.a_ = a_.topRows<kDim2d>();
return p2d;
}
Vector6d
State3d::Get6dVel () const
{
Vector6d h_xd;
h_xd.segment(AX, 3) = ang.w;
h_xd.segment(LX, 3) = lin.v_;
return h_xd;
}
Vector6d
State3d::Get6dAcc () const
{
Vector6d h_xdd;
h_xdd.segment(AX, 3) = ang.wd;
h_xdd.segment(LX, 3) = lin.a_;
return h_xdd;
}
} // namespace xpp
| 27.834711 | 95 | 0.686758 | [
"vector"
] |
c27b0ccffe221b53ff0f2a525140c9569e6366e7 | 10,306 | cpp | C++ | hackathon/gyy/call_plugin/test_call_plugin_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/gyy/call_plugin/test_call_plugin_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/gyy/call_plugin/test_call_plugin_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | /* test_call_plugin_plugin.cpp
* This is a test plugin, you can use it as a demo.
* 2019-5-20 : by YourName
*/
#include "v3d_message.h"
#include <vector>
#include "test_call_plugin_plugin.h"
#include <iostream>
#include "vn_app2.h"
#include "fastmarching_tree.h"
#include "fastmarching_dt.h"
#include "hierarchy_prune.h"
#include "marker_radius.h"
#include "basic_surf_objs.h"
#include "swc_convert.h"
#include "vn_imgpreprocess.h"
#include "volimg_proc.h"
using namespace std;
Q_EXPORT_PLUGIN2(test_call_plugin, TestPlugin);
QStringList TestPlugin::menulist() const
{
return QStringList()
<<tr("call_function")
<<tr("call_plugin")
<<tr("about");
}
QStringList TestPlugin::funclist() const
{
return QStringList()
<<tr("call_function")
<<tr("call_plugin")
<<tr("help");
}
bool app2_dialog0(PARA_APP2 &p2);
void TestPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent)
{
if (menu_name == tr("call_function"))
{
// QString name = QFileDialog::getExistingDirectory(parent, QString("234"));
// QDir dir(name);
// cout<<dir.absolutePath().toStdString()<<endl;
PARA_APP2 p2;
cout<<"31"<<endl;
if(!app2_dialog0(p2)) return;
cout<<"32"<<endl;
QString versionStr = "v2.621";
QString imagePath = QFileDialog::getOpenFileName(parent, QString("open image file:"));
QString markerPath = QFileDialog::getOpenFileName(parent, QString("open marker file:"));
p2.inimg_file = imagePath;
p2.inmarker_file = markerPath;
QString path_tmp("/home/balala/Desktop/call_plugin/");
p2.outswc_file = path_tmp+"outswc"+".swc";
cout<<"33"<<endl;
QString infile = p2.inimg_file;
// p2.p4dImage = callback.loadImage((char *)(qPrintable(infile) ));
// if (!p2.p4dImage || !p2.p4dImage->valid()) return false;
// else
// {
// p2.xc0 = p2.yc0 = p2.zc0 = 0;
// p2.xc1 = p2.p4dImage->getXDim()-1;
// p2.yc1 = p2.p4dImage->getYDim()-1;
// p2.zc1 = p2.p4dImage->getZDim()-1;
// }
// p2.p4dImage=callback.getImage(callback.currentImageWindow());
proc_app2(callback, p2, versionStr);
}
else if (menu_name == tr("call_plugin"))
{
//v3d_msg("To be implemented.");
//V3DPluginCallback2 v3d;
PARA_APP2 p2;
if(!app2_dialog0(p2)) return;
V3DPluginArgItem arg;
V3DPluginArgList input;
V3DPluginArgList output;
QString imagepath = QFileDialog::getOpenFileName(parent, QString("open image file:"));
QString markerpath = QFileDialog::getOpenFileName(parent, QString("open marker file:"));
//QString tmppath = "/home/balala/Desktop/call_plugin";
QString path_tmp("/home/balala/Desktop/call_plugin/");
QString outswc_file = path_tmp+"outswc"+".swc";
arg.type = "random"; std::vector<char*> arg_input_app2;
std:: string fileName_string1(imagepath.toStdString());
char* fileName_char1 = new char[fileName_string1.length() + 1];
strcpy(fileName_char1, fileName_string1.c_str());
arg_input_app2.push_back(fileName_char1);
arg.p = (void *) & arg_input_app2;
input << arg;
arg.type = "random"; vector<char*> arg_paras_app2;
string fileName_string2(markerpath.toStdString());
char *fileName_char2 = new char[fileName_string2.length() + 1];
strcpy(fileName_char2, fileName_string2.c_str());
arg_paras_app2.push_back(fileName_char2);
arg.p = (void *) & arg_paras_app2;
input << arg;
arg.type = "random"; vector<char*> arg_output_app2;
string fileName_string0(outswc_file.toStdString());
char* fileName_char0 = new char[fileName_string0.length() + 1];
strcpy(fileName_char0, fileName_string0.c_str());
arg_output_app2.push_back(fileName_char0);
arg.p = (void *) & arg_output_app2;
output << arg;
//QString plugin_name = "/home/balala/vaa3d_tools/released_plugins/v3d_plugins/vaa3dneuron2";
QString plugin_name = "Vaa3D_Neuron2";
QString func_name = "app2";
callback.callPluginFunc(plugin_name, func_name, input, output);
}
else
{
v3d_msg(tr("This is a test plugin, you can use it as a demo.. "
"Developed by YourName, 2019-5-20"));
}
}
bool TestPlugin::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent)
{
vector<char*> * pinfiles = (input.size() >= 1) ? (vector<char*> * )input[0].p : 0;
vector<char*> * pparas = (input.size() >= 2) ? (vector<char*> * )input[1].p : 0;
vector<char*> * poutfiles = (output.size() >= 1) ? (vector<char*> * )output[0].p : 0;
vector<char*> infiles = (pinfiles != 0) ? *pinfiles : vector<char*>();
vector<char*> paras = (pparas != 0) ? *pparas : vector<char*>();
vector<char*> outfiles = (poutfiles !=0) ? *poutfiles : vector<char*>();
if (func_name == tr("call_function"))
{
//v3d_msg("To be implemented.");
PARA_APP2 p2;
QString versionStr = "v2.621";
//cout << __LINE__ << endl;
p2.inimg_file = infiles.empty() ? "" : infiles[0];
// p2.inmarker_file = paras[0];
if(p2.inimg_file.isEmpty())
{
cerr<<"Need a marker file"<<endl;
return false;
}
p2.outswc_file = outfiles.empty() ? "" : outfiles[0];
int k=0;
QString inmarker_file = paras.empty() ? "" : paras[0];
if(inmarker_file.isEmpty())
{
cerr<<"Need a marker file"<<endl;
return false;
}
p2.inmarker_file = inmarker_file;
proc_app2(callback, p2, versionStr);
}
else if (func_name == tr("call_plugin"))
{
//v3d_msg("To be implemented.");
PARA_APP2 p2;
QString plugin_name = "Vaa3D_Neuron2";
QString func_name = "app2";
callback.callPluginFunc(plugin_name, func_name, input, output);
}
else if (func_name == tr("help"))
{
v3d_msg("To be implemented.");
}
else return false;
return true;
}
bool app2_dialog0(PARA_APP2 &p2)
{
// if(!p2.p4dImage || !p2.p4dImage->valid())
// return false;
int chn_num = 3;
QDialog *dialog = new QDialog();
dialog->setWindowTitle("auto_tracing based on APP2");
QGridLayout *layout = new QGridLayout();
QSpinBox *channel_spinbox = new QSpinBox();
channel_spinbox->setRange(1, chn_num);
channel_spinbox->setValue(1);
QSpinBox *cnntype_spinbox = new QSpinBox();
cnntype_spinbox->setRange(1, 3);
cnntype_spinbox->setValue(2);
QSpinBox *bkgthresh_spinbox = new QSpinBox();
bkgthresh_spinbox->setRange(-2, 255);
bkgthresh_spinbox->setValue(10);
QLineEdit *lenthresh_editor = new QLineEdit(QString("").setNum(p2.length_thresh));
QLineEdit *srratio_editor = new QLineEdit(QString("").setNum(p2.SR_ratio));
QCheckBox *isgsdt_checker = new QCheckBox();
isgsdt_checker->setChecked(p2.is_gsdt);
QCheckBox *iswb_checker = new QCheckBox();
iswb_checker->setChecked(p2.is_break_accept);
QCheckBox *b256_checker = new QCheckBox();
b256_checker->setChecked(p2.b_256cube);
QCheckBox *b_radius2Dchecker = new QCheckBox();
b_radius2Dchecker->setChecked(p2.b_RadiusFrom2D);
QCheckBox *bresample_checker = new QCheckBox();
bresample_checker->setChecked(p2.b_resample);
QCheckBox *b_intensity_checker = new QCheckBox();
b_intensity_checker->setChecked(p2.b_intensity);
QCheckBox *b_brightfiled_checker = new QCheckBox();
b_brightfiled_checker->setChecked(p2.b_brightfiled);
layout->addWidget(new QLabel("color channel"),0,0);
layout->addWidget(channel_spinbox, 0,1,1,5);
layout->addWidget(new QLabel("background_threshold \n(if set as -1, \nthen auto-thresholding)"), 1,0);
layout->addWidget(bkgthresh_spinbox, 1,1,1,5);
QHBoxLayout *hbox1 = new QHBoxLayout();
hbox1->addWidget(new QLabel("auto-downsample"));
hbox1->addWidget(b256_checker);
hbox1->addWidget(new QLabel("use GSDT"));
hbox1->addWidget(isgsdt_checker);
hbox1->addWidget(new QLabel("allow gap"));
hbox1->addWidget(iswb_checker);
hbox1->addWidget(new QLabel("radius from 2D?"));
hbox1->addWidget(b_radius2Dchecker);
QHBoxLayout *hbox2 = new QHBoxLayout();
hbox2->addWidget(new QLabel("auto-resample SWC"));
hbox2->addWidget(bresample_checker);
hbox2->addWidget(new QLabel("high intensity background"));
hbox2->addWidget(new QLabel("bright filed"));
hbox2->addWidget(b_brightfiled_checker);
layout->addLayout(hbox1, 2,0,1,6);
layout->addLayout(hbox2, 3,0,1,6);
layout->addWidget(new QLabel("cnn_type"), 4,0);
layout->addWidget(cnntype_spinbox, 4,1,1,5);
layout->addWidget(new QLabel("length_thresh"), 5,0);
layout->addWidget(lenthresh_editor, 5,1,1,5);
layout->addWidget(new QLabel("SR_ratio"), 6,0);
layout->addWidget(srratio_editor, 6,1,1,5);
QHBoxLayout *hbox3 = new QHBoxLayout();
QPushButton *ok = new QPushButton(" ok ");
ok->setDefault(true);
QPushButton *cancel = new QPushButton("cancel");
hbox3->addWidget(cancel);
hbox3->addWidget(ok);
layout->addLayout(hbox3, 7,0,1,6);
dialog->setLayout(layout);
QObject::connect(ok, SIGNAL(clicked()), dialog, SLOT(accept()));
QObject::connect(cancel, SIGNAL(clicked()), dialog, SLOT(reject()));
if(dialog->exec() != QDialog::Accepted)
return false;
p2.channel = channel_spinbox->value() - 1;
p2.cnn_type = cnntype_spinbox->value();
p2.bkg_thresh = bkgthresh_spinbox->value();
p2.length_thresh = atof(lenthresh_editor->text().toStdString().c_str());
p2.SR_ratio = atof(srratio_editor->text().toStdString().c_str());
p2.is_gsdt = isgsdt_checker->isChecked();
p2.is_break_accept = iswb_checker->isChecked();
p2.b_256cube = b256_checker->isChecked();
p2.b_RadiusFrom2D = b_radius2Dchecker->isChecked();
p2.b_resample = bresample_checker->isChecked();
p2.b_intensity = b_intensity_checker->isChecked();
p2.b_brightfiled = b_brightfiled_checker->isChecked();
if(dialog){delete dialog; dialog = 0;}
return true;
}
| 35.537931 | 159 | 0.650786 | [
"vector"
] |
c27c19a53ad2d32770c9509cade0ecce82cbe9ab | 1,384 | cpp | C++ | Sources/Core/Utils/Serialization.cpp | utilForever/CubbyFlow-v1 | d85c136d8eaa91ecce456c3356c7e578dda5d5bd | [
"MIT"
] | 3 | 2020-04-15T13:41:16.000Z | 2020-12-29T11:23:59.000Z | Sources/Core/Utils/Serialization.cpp | utilForever/CubbyFlow-v1 | d85c136d8eaa91ecce456c3356c7e578dda5d5bd | [
"MIT"
] | null | null | null | Sources/Core/Utils/Serialization.cpp | utilForever/CubbyFlow-v1 | d85c136d8eaa91ecce456c3356c7e578dda5d5bd | [
"MIT"
] | null | null | null | /*************************************************************************
> File Name: Serialization.cpp
> Project Name: CubbyFlow
> Author: Chan-Ho Chris Ohk
> Purpose: Abstract base class for any serializable class.
> Created Time: 2017/05/27
> Copyright (c) 2018, Chan-Ho Chris Ohk
*************************************************************************/
#include <Core/Utils/Serialization.h>
#include <Flatbuffers/generated/FlatData_generated.h>
#include <vector>
namespace CubbyFlow
{
void Serialize(const Serializable* serializable, std::vector<uint8_t>* buffer)
{
serializable->Serialize(buffer);
}
void Serialize(const uint8_t* data, size_t size, std::vector<uint8_t>* buffer)
{
flatbuffers::FlatBufferBuilder builder(1024);
auto fbsData = fbs::CreateFlatData(builder, builder.CreateVector(data, size));
builder.Finish(fbsData);
uint8_t* buf = builder.GetBufferPointer();
size_t sz = builder.GetSize();
buffer->resize(sz);
memcpy(buffer->data(), buf, sz);
}
void Deserialize(const std::vector<uint8_t>& buffer, Serializable* serializable)
{
serializable->Deserialize(buffer);
}
void Deserialize(const std::vector<uint8_t>& buffer, std::vector<uint8_t>* data)
{
auto fbsData = fbs::GetFlatData(buffer.data());
data->resize(fbsData->data()->size());
std::copy(fbsData->data()->begin(), fbsData->data()->end(), data->begin());
}
} | 28.833333 | 81 | 0.643786 | [
"vector"
] |
c27c51b8c81fbdcf51f1774a7710abd3224e6c1f | 15,377 | cpp | C++ | src/rpc/donationwallets.cpp | blakeanator/Monkecoin | ad28b95ac06344c9775f4ba7e6728e8103040c8f | [
"MIT"
] | null | null | null | src/rpc/donationwallets.cpp | blakeanator/Monkecoin | ad28b95ac06344c9775f4ba7e6728e8103040c8f | [
"MIT"
] | null | null | null | src/rpc/donationwallets.cpp | blakeanator/Monkecoin | ad28b95ac06344c9775f4ba7e6728e8103040c8f | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Blake Copeland
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <rpc/donationwallets.h>
#include <chainparams.h>
#include <donationwallets.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <validation.h>
#include <univalue.h>
// TEST
#include <sidh.h>
#include <crypto/sha256.h>
#include <crypto/sha3.h>
// TEST
static UniValue getblockdonation(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
RPCHelpMan{"getblockdonation",
"\nReturns how much currency gets minted for donation wallets for a given block.\n",
{
{"height", RPCArg::Type::NUM, /* default */ "1", "Specifies the block to get the donation reward for."},
},
RPCResult{
RPCResult::Type::NUM, "donation", "How much Monkecoin is distributed to all donations wallets for a given block"
},
RPCExamples{
HelpExampleCli("getblockdonation", "1000")
+ HelpExampleRpc("getblockdonation", "1000")
},
}.ToString());
int nHeight = !request.params[0].isNull() ? request.params[0].get_int() : 1;
if (nHeight < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
std::string result = std::to_string((double)GetBlockDonationSubsidy(nHeight, Params().GetConsensus()) / (double)COIN) + " MKE";
return UniValue(result);
}
static UniValue getblockreward(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
RPCHelpMan{"getblockreward",
"\nReturns the reward for mining a given block.\n",
{
{"height", RPCArg::Type::NUM, /* default */ "1", "Specifies the block to get the reward value for."},
},
RPCResult{
RPCResult::Type::NUM, "reward", "How many Monkecoin are given to the miner as a reward for completing a given block"
},
RPCExamples{
HelpExampleCli("getblockreward", "1000")
+ HelpExampleRpc("getblockreward", "1000")
},
}.ToString());
int nHeight = !request.params[0].isNull() ? request.params[0].get_int() : 1;
if (nHeight < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
std::string result = std::to_string(GetBlockSubsidy(nHeight, Params().GetConsensus()) / COIN) + " MKE";
return UniValue(result);
}
static UniValue getblockrewardhalving(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
RPCHelpMan{"getblockrewardhalving",
"\nReturns the reward for mining a given block.\n",
{
{"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "Specifies the block to get the halving value for."},
},
RPCResult{
RPCResult::Type::NUM, "halving", "How many times the inital reward is halved for a given block"
},
RPCExamples{
HelpExampleCli("getblockrewardhalving", "1000")
+ HelpExampleRpc("getblockrewardhalving", "1000")
},
}.ToString());
int nHeight = !request.params[0].isNull() ? request.params[0].get_int() : 1;
if (nHeight < 0 || nHeight > (int)GetMaxMinableBlocks(Params().GetConsensus()))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
return GetBlockSubsidyHalving(nHeight, Params().GetConsensus());
}
static UniValue getblockrewardhalvingmax(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getblockrewardhalvingmax",
"\nReturns how many times the mining reward will be halved.\n",
{},
RPCResult{
RPCResult::Type::NUM, "steps", "The total number of halving steps in the lifetime of the minting process"
},
RPCExamples{
HelpExampleCli("getblockrewardhalvingmax", "")
+ HelpExampleRpc("getblockrewardhalvingmax", "")
},
}.ToString());
return GetBlockSubsidyHalvingMax(Params().GetConsensus());
}
static UniValue getcelebrationblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getcelebrationblock",
"\nReturns the celebration block. This block is the block after the last minable block, and rewards _ MKE to donation wallets.\n",
{},
RPCResult{
RPCResult::Type::NUM, "block", "The block number for the Celebration Block (if there is one)"
},
RPCExamples{
HelpExampleCli("getcelebrationblock", "")
+ HelpExampleRpc("getcelebrationblock", "")
},
}.ToString());
// If the celebration block is enabled
if (ENABLE_CELEBRATION_BLOCK)
{
return GetCelebrationBlock(Params().GetConsensus());
}
return UniValue("Celebration block not enabled");
}
static UniValue getdonationwallets(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
RPCHelpMan{"getdonationwallets",
"\nReturns information on all the donation wallets.\n",
{},
RPCResult {
RPCResult::Type::ARR, "", "",
{
{RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "name", "The name of the non-profit associated with the wallet"},
{RPCResult::Type::STR, "address", "The current address for the nonprofit"},
{RPCResult::Type::BOOL, "active", "If the non-profit is active or not"},
{RPCResult::Type::NUM, "confirmations", "The number of confirmations of the most recent transaction included"},
}},
}
},
RPCExamples{
HelpExampleCli("getdonationwallets", "")
+ HelpExampleRpc("getdonationwallets", "")
},
}.ToString());
}
UniValue result(UniValue::VARR);
// Go through all the donation wallets (skip the first index)
for (unsigned int i = 1; i < DonationWallets::GetSize(true); i++)
{
const DonationWalletDescriptor& wallet = donationWallets[i];
UniValue obj(UniValue::VOBJ);
obj.pushKV("name", wallet.name);
//obj.pushKV("address", wallet.pubkey);
obj.pushKV("address", "");
obj.pushKV("active", wallet.active);
result.push_back(obj);
}
return result;
}
static UniValue getmaxminableblocks(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getmaxminableblocks",
"\nReturns the maximum number of blocks that can be mined for a reward.\n",
{},
RPCResult{
RPCResult::Type::NUM, "height", "Last block that has a mining reward"
},
RPCExamples{
HelpExampleCli("getmaxminableblocks", "")
+ HelpExampleRpc("getmaxminableblocks", "")
},
}.ToString());
return GetMaxMinableBlocks(Params().GetConsensus());
}
static UniValue getsupplyratio(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getsupplyratio",
"\nReturns supply ratio for how much of the total currency supply is allocated to minres vs donations.\n",
{},
RPCResult{
RPCResult::Type::STR, "ratio", "The supply distribution percentage between miners and non-profits"
},
RPCExamples{
HelpExampleCli("getsupplyratio", "")
+ HelpExampleRpc("getsupplyratio", "")
},
}.ToString());
std::string result = "Miners: " + std::to_string(GetTotalMiningSubsidyPercentage(Params().GetConsensus()) * 100.0) + "%\nDonations: " + std::to_string(GetTotalDonationSubsidyPercentage(Params().GetConsensus()) * 100.0) + "%";
return UniValue(result);
}
static UniValue getsupplytotal(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"getsupplytotal",
"\nReturns the entire supply of Monkecoins.\n",
{},
RPCResult{
RPCResult::Type::STR, "distribution", "The supply distribution between miners and non-profits"
},
RPCExamples{
HelpExampleCli("getsupplytotal", "")
+ HelpExampleRpc("getsupplytotal", "")
},
}.ToString());
std::string result = "Total: " + std::to_string(MAX_MONEY / COIN) + " MKE\n-----------------------\nMiners: " + std::to_string(GetTotalMiningSubsidySupply(Params().GetConsensus()) / COIN) + " MKE\nDonations: " + std::to_string(GetTotalDonationSubsidySupply(Params().GetConsensus()) / COIN) + " MKE";
return UniValue(result);
}
static UniValue donationtest(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"donationtest",
"\ntest.\n",
{},
RPCResult{
RPCResult::Type::STR, "test", "test"
},
RPCExamples{
HelpExampleCli("donationtest", "")
+ HelpExampleRpc("donationtest", "")
},
}.ToString());
//uint8_t privateKey[644] = "";
//uint8_t publicKey[564]= "";
//int i = crypto_kem_keypair_SIKEp751(publicKey, privateKey);
uint8_t privateKey[602]= "";
uint8_t publicKey[335] = "";
int i = crypto_kem_keypair_SIKEp751_compressed(publicKey, privateKey);
//std::vector<uint8_t> prikv(privateKey, privateKey + 374);
//std::string prikvs = HexStr(prikv);
//std::string prikvs = HexStr(Span<uint8_t>(privateKey, privateKey + 374));
std::vector<uint8_t> pubkv(publicKey, publicKey + 335);
std::string pubkvs = HexStr(pubkv);
std::string result = "SIDH (" + std::to_string(i) + ")\nprivate: " + HexStr(MakeUCharSpan(privateKey)) + "\npublic: " + pubkvs;
return UniValue(result);
}
static UniValue donationtest2(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
RPCHelpMan{"donationtest2",
"\ntest2.\n",
{},
RPCResult{
RPCResult::Type::STR, "test2", "test2"
},
RPCExamples{
HelpExampleCli("donationtest2", "")
+ HelpExampleRpc("donationtest2", "")
},
}.ToString());
std::string bla = "";
uint8_t test[0] = {};
CSHA256 sha = CSHA256();
sha.Write(test, 0);
unsigned char buf[CSHA256::OUTPUT_SIZE];
sha.Finalize(buf);
bla += "SHA256 (to buf): " + HexStr(MakeUCharSpan(buf));
uint8_t o0 = buf[0];
bla += "\nFirst: " + std::to_string(o0);
CSHA256 sha2 = CSHA256();
sha2.Write(test, 0);
uint256 result;
sha2.Finalize(result.begin());
bla += "\nSHA256 (to int): " + result.GetHex(false);
uint8_t o1 = *result.data();
bla += "\nFirst: " + std::to_string(o1);
result.SetHex(HexStr(MakeUCharSpan(buf)));
bla += "\nSHA256 (fo hex): " + result.GetHex(false);
uint8_t o2 = *result.data();
bla += "\nFirst: " + std::to_string(o2);
//strncat(bla, &o, 1);
//uint256 resultbla2;
//CHash256().Write(test, 0).Finalize(resultbla2);
//bla += "\nSHA256 (2): " + resultbla2.GetHex();
Span<uint8_t> test2(test, 0);
bla += "\nSHA256 (4): " + Hash(test2).GetHex();
bla += "\nempty: " + std::to_string(test2.empty()) + " size: " + std::to_string(test2.size());
std::string ret;
for (int i = 0; i < 200000; i++) {
ret += (char)(i);
ret += (char)(i >> 4);
ret += (char)(i >> 8);
ret += (char)(i >> 12);
ret += (char)(i >> 16);
}
SHA3_256 sha3 = SHA3_256();
sha3.Write(MakeUCharSpan(ret));
uint256 result3;
sha3.Finalize(result3);
bla += "\nTEST: " + result3.GetHex(false);
return UniValue(bla);
/*
std::string s = "monke";
std::vector<uint8_t> test2(s.begin(), s.end());
//uint8_t empty[SHA3_256::OUTPUT_SIZE] = "";
//Span<uint8_t> output(empty);
uint8_t output[SHA3_256::OUTPUT_SIZE];
SHA3_256 sha = SHA3_256();
sha.Write(test2);
sha.Finalize(output);
*/
//std::vector<uint8_t> test3(output, output + SHA3_256::OUTPUT_SIZE);
//std::vector<uint8_t> test3;
//test3.insert(test3.begin(), std::end(output), std::begin(output));
//uint256 test4 = uint256(test3);
//return UniValue(test4.GetHex());
//return UniValue(HexStr(MakeUCharSpan(output)));
//return UniValue(HexStr(output));
}
const CRPCCommand commands[] =
{ // category name actor (function) argNames
// ----------------- ------------------------ ----------------------- ----------
{ "donation", "getblockdonation", &getblockdonation, {"height"} },
{ "donation", "getblockreward", &getblockreward, {"height"} },
{ "donation", "getblockrewardhalving", &getblockrewardhalving, {"height"} },
{ "donation", "getblockrewardhalvingmax", &getblockrewardhalvingmax, {} },
{ "donation", "getcelebrationblock", &getcelebrationblock, {} },
{ "donation", "getdonationwallets", &getdonationwallets, {} },
{ "donation", "getmaxminableblocks", &getmaxminableblocks, {} },
{ "donation", "getsupplyratio", &getsupplyratio, {} },
{ "donation", "getsupplytotal", &getsupplytotal, {} },
{ "donation", "donationtest", &donationtest, {} },
{ "donation", "donationtest2", &donationtest2, {} },
};
void RegisterDonationWalletRPCCommands(CRPCTable& t)
{
for (const auto& c : commands) {
t.appendCommand(c.name, &c);
}
}
| 36.699284 | 311 | 0.550107 | [
"vector"
] |
c27e6cea8b8abfeea4ff13aba504a3e8950876aa | 2,275 | hpp | C++ | llarp/util/meta/memfn.hpp | wratc/loki-network | 0d6d0ec7b27f80c2836eb5d4c4f6e7b1974dd178 | [
"Zlib"
] | 3 | 2018-11-17T07:38:39.000Z | 2021-04-29T23:39:47.000Z | llarp/util/meta/memfn.hpp | wratc/loki-network | 0d6d0ec7b27f80c2836eb5d4c4f6e7b1974dd178 | [
"Zlib"
] | 1 | 2020-03-28T08:59:56.000Z | 2020-03-28T08:59:56.000Z | llarp/util/meta/memfn.hpp | wratc/loki-network | 0d6d0ec7b27f80c2836eb5d4c4f6e7b1974dd178 | [
"Zlib"
] | 2 | 2021-01-28T05:36:14.000Z | 2021-01-28T05:47:53.000Z | #ifndef LLARP_UTIL_MEMFN
#define LLARP_UTIL_MEMFN
#include <type_traits>
#include <utility>
#include <memory>
namespace llarp
{
namespace util
{
// Wraps a member function and instance into a callable object that invokes
// the method (non-const overload).
template <
typename Return, typename Class, typename Derived, typename... Arg,
typename =
std::enable_if_t< std::is_base_of< Class, Derived >::value > >
auto
memFn(Return (Class::*f)(Arg...), Derived* self)
{
return [f, self](Arg... args) -> Return {
return (self->*f)(std::forward< Arg >(args)...);
};
}
// Wraps a member function and instance into a lambda that invokes the
// method (const overload).
template <
typename Return, typename Class, typename Derived, typename... Arg,
typename =
std::enable_if_t< std::is_base_of< Class, Derived >::value > >
auto
memFn(Return (Class::*f)(Arg...) const, const Derived* self)
{
return [f, self](Arg... args) -> Return {
return (self->*f)(std::forward< Arg >(args)...);
};
}
// Wraps a member function and shared pointer to an instance into a lambda
// that invokes the method.
template <
typename Return, typename Class, typename Derived, typename... Arg,
typename =
std::enable_if_t< std::is_base_of< Class, Derived >::value > >
auto
memFn(Return (Class::*f)(Arg...), std::shared_ptr< Derived > self)
{
return [f, self = std::move(self)](Arg... args) -> Return {
return (self.get()->*f)(std::forward< Arg >(args)...);
};
}
// Wraps a member function and shared pointer to an instance into a lambda
// that invokes the method (const method overload).
template <
typename Return, typename Class, typename Derived, typename... Arg,
typename =
std::enable_if_t< std::is_base_of< Class, Derived >::value > >
auto
memFn(Return (Class::*f)(Arg...) const, std::shared_ptr< Derived > self)
{
return [f, self = std::move(self)](Arg... args) -> Return {
return (self.get()->*f)(std::forward< Arg >(args)...);
};
}
} // namespace util
} // namespace llarp
#endif
| 31.597222 | 79 | 0.595604 | [
"object"
] |
c288866499560755355c307e8c0be622d776bcc1 | 812 | cpp | C++ | GreedyScheduling/main.cpp | utsavm9/Stanford-Algorithms-Course | 2200a792e3e607b98b4fbf33ce890d3899c06ece | [
"MIT"
] | null | null | null | GreedyScheduling/main.cpp | utsavm9/Stanford-Algorithms-Course | 2200a792e3e607b98b4fbf33ce890d3899c06ece | [
"MIT"
] | null | null | null | GreedyScheduling/main.cpp | utsavm9/Stanford-Algorithms-Course | 2200a792e3e607b98b4fbf33ce890d3899c06ece | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cstdio>
#include <utility>
#include <algorithm>
using namespace std;
bool sortFunc(pair<int, int> a, pair<int, int> b) {
float score1 = ((float) a.first) / a.second;
float score2 = ((float) b.first) / b.second;
return (score1 > score2);
}
int main() {
freopen("jobs.txt", "r", stdin);
int tests = 0;
vector<pair<int, int>> jobs;
cin >> tests;
while (tests-- > 0) {
int w, l;
cin >> w >> l;
jobs.push_back(make_pair(w, l));
}
sort(jobs.begin(), jobs.end(), sortFunc);
long long int sum = 0;
long long time = 0;
for (pair<int, int> p: jobs) {
time += p.second;
sum += time * p.first;
}
cout << sum;
return 0;
} | 20.3 | 52 | 0.51601 | [
"vector"
] |
c2899c483b485f1134db813815f706cddb0f090f | 2,582 | cc | C++ | src/iplanner/dataset/dataset.cc | jsonpark/iplanner2 | 858aeb3d54b519283a0a9e71cc6878a9114d2ea8 | [
"MIT"
] | null | null | null | src/iplanner/dataset/dataset.cc | jsonpark/iplanner2 | 858aeb3d54b519283a0a9e71cc6878a9114d2ea8 | [
"MIT"
] | null | null | null | src/iplanner/dataset/dataset.cc | jsonpark/iplanner2 | 858aeb3d54b519283a0a9e71cc6878a9114d2ea8 | [
"MIT"
] | null | null | null | #include "iplanner/dataset/dataset.h"
#include <iostream>
#include <fstream>
namespace iplanner
{
Dataset::Dataset() = default;
Dataset::~Dataset() = default;
int Dataset::NumSequences()
{
return 1;
}
void Dataset::SelectSequence(int idx)
{
}
void Dataset::SelectSequence(const std::string& name)
{
}
void Dataset::SelectFrame(int index)
{
}
std::string Dataset::GetCurrentSequenceName() const
{
return std::string("Dataset");
}
int Dataset::FrameRate() const
{
return 60;
}
int Dataset::RgbWidth()
{
// Default Kinect v2
return 1920;
}
int Dataset::RgbHeight()
{
return 1080;
}
int Dataset::DepthWidth()
{
return 512;
}
int Dataset::DepthHeight()
{
return 424;
}
int Dataset::NumFrames() const
{
return 10;
}
std::vector<unsigned char> Dataset::GetRgbImage()
{
return std::vector<unsigned char>(RgbWidth() * RgbHeight() * 3, 0);
}
std::vector<unsigned short> Dataset::GetDepthImage()
{
return std::vector<unsigned short>(DepthWidth() * DepthHeight(), 0);
}
bool Dataset::PreviousSequence()
{
return false;
}
bool Dataset::NextSequence()
{
return false;
}
bool Dataset::PreviousFrame()
{
return false;
}
bool Dataset::NextFrame()
{
return false;
}
std::shared_ptr<HumanModel> Dataset::GetHumanModel() const
{
return nullptr;
}
std::shared_ptr<HumanLabel> Dataset::GetHumanLabel() const
{
return nullptr;
}
double Dataset::CurrentSequenceLength() const
{
return static_cast<double>(NumFrames()) / FrameRate();
}
Trajectory Dataset::GetTrajectory()
{
return Trajectory(9, 5, 1.);
}
void Dataset::SaveTrajectory(Trajectory trajectory)
{
std::cout << "Dataset base class SaveTrajectory" << std::endl;
}
double Dataset::CurrentTime() const
{
return 0.;
}
Trajectory Dataset::LoadTrajectory(const std::string& filename)
{
std::ifstream in(filename);
int rows, cols;
double time;
in >> rows >> cols >> time;
Trajectory trajectory(rows, cols, time);
for (int j = 0; j < cols; j++)
{
for (int i = 0; i < rows; i++)
in >> trajectory(i, j);
}
in.close();
return trajectory;
}
void Dataset::SaveTrajectory(Trajectory trajectory, const std::string& filename)
{
// tab separated values
std::ofstream out(filename);
out << trajectory.Rows() << '\t' << trajectory.Cols() << '\t' << trajectory.Time() << std::endl;
// Transpose the matrix so that each line represents a robot joint values at a frame
for (int j = 0; j < trajectory.Cols(); j++)
{
for (int i = 0; i < trajectory.Rows(); i++)
out << trajectory(i, j) << '\t';
out << std::endl;
}
out.close();
}
}
| 15.648485 | 98 | 0.665376 | [
"vector"
] |
c28a9979fd355baea4d2443e930e9ec8661ccb46 | 191,134 | cpp | C++ | MonoNative/mscorlib/System/mscorlib_System_Convert.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/mscorlib_System_Convert.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/mscorlib_System_Convert.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #include <mscorlib/System/mscorlib_System_Convert.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Byte.h>
#include <mscorlib/System/mscorlib_System_DateTime.h>
#include <mscorlib/System/mscorlib_System_Decimal.h>
#include <mscorlib/System/mscorlib_System_SByte.h>
namespace mscorlib
{
namespace System
{
//Public Methods
std::vector<mscorlib::System::Byte*> Convert::FromBase64CharArray(std::vector<mscorlib::System::Char*> inArray, mscorlib::System::Int32 offset, mscorlib::System::Int32 length)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Char")), 1));
__parameter_types__[1] = Global::GetType(typeid(offset).name());
__parameter_types__[2] = Global::GetType(typeid(length).name());
__parameters__[0] = Global::FromPrimitiveArray<mscorlib::System::Char*>(inArray, typeid(mscorlib::System::Char).name());
__parameters__[1] = &offset;
__parameters__[2] = &length;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "FromBase64CharArray", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<mscorlib::System::Byte*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new mscorlib::System::Byte (__array_item__));
}
return __array_result__;
}
std::vector<mscorlib::System::Byte*> Convert::FromBase64String(mscorlib::System::String s)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(s).name());
__parameters__[0] = (MonoObject*)s;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "FromBase64String", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<mscorlib::System::Byte*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new mscorlib::System::Byte (__array_item__));
}
return __array_result__;
}
std::vector<mscorlib::System::Byte*> Convert::FromBase64String(const char *s)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), s);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "FromBase64String", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<mscorlib::System::Byte*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new mscorlib::System::Byte (__array_item__));
}
return __array_result__;
}
mscorlib::System::TypeCode::__ENUM__ Convert::GetTypeCode(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "GetTypeCode", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return static_cast<mscorlib::System::TypeCode::__ENUM__>(*(mscorlib::System::Int32*)mono_object_unbox(__result__));
}
mscorlib::System::Boolean Convert::IsDBNull(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "IsDBNull", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToBase64CharArray(std::vector<mscorlib::System::Byte*> inArray, mscorlib::System::Int32 offsetIn, mscorlib::System::Int32 length, std::vector<mscorlib::System::Char*> outArray, mscorlib::System::Int32 offsetOut)
{
MonoType *__parameter_types__[5];
void *__parameters__[5];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameter_types__[1] = Global::GetType(typeid(offsetIn).name());
__parameter_types__[2] = Global::GetType(typeid(length).name());
__parameter_types__[3] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Char")), 1));
__parameter_types__[4] = Global::GetType(typeid(offsetOut).name());
__parameters__[0] = Global::FromArray<mscorlib::System::Byte*>(inArray, typeid(mscorlib::System::Byte).name());
__parameters__[1] = &offsetIn;
__parameters__[2] = &length;
__parameters__[3] = Global::FromPrimitiveArray<mscorlib::System::Char*>(outArray, typeid(mscorlib::System::Char).name());
__parameters__[4] = &offsetOut;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBase64CharArray", NullMonoObject, 5, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::String Convert::ToBase64String(std::vector<mscorlib::System::Byte*> inArray)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameters__[0] = Global::FromArray<mscorlib::System::Byte*>(inArray, typeid(mscorlib::System::Byte).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBase64String", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToBase64String(std::vector<mscorlib::System::Byte*> inArray, mscorlib::System::Int32 offset, mscorlib::System::Int32 length)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameter_types__[1] = Global::GetType(typeid(offset).name());
__parameter_types__[2] = Global::GetType(typeid(length).name());
__parameters__[0] = Global::FromArray<mscorlib::System::Byte*>(inArray, typeid(mscorlib::System::Byte).name());
__parameters__[1] = &offset;
__parameters__[2] = &length;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBase64String", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToBase64String(std::vector<mscorlib::System::Byte*> inArray, mscorlib::System::Base64FormattingOptions::__ENUM__ options)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameter_types__[1] = Global::GetType(typeid(options).name());
__parameters__[0] = Global::FromArray<mscorlib::System::Byte*>(inArray, typeid(mscorlib::System::Byte).name());
mscorlib::System::Int32 __param_options__ = options;
__parameters__[1] = &__param_options__;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBase64String", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToBase64String(std::vector<mscorlib::System::Byte*> inArray, mscorlib::System::Int32 offset, mscorlib::System::Int32 length, mscorlib::System::Base64FormattingOptions::__ENUM__ options)
{
MonoType *__parameter_types__[4];
void *__parameters__[4];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameter_types__[1] = Global::GetType(typeid(offset).name());
__parameter_types__[2] = Global::GetType(typeid(length).name());
__parameter_types__[3] = Global::GetType(typeid(options).name());
__parameters__[0] = Global::FromArray<mscorlib::System::Byte*>(inArray, typeid(mscorlib::System::Byte).name());
__parameters__[1] = &offset;
__parameters__[2] = &length;
mscorlib::System::Int32 __param_options__ = options;
__parameters__[3] = &__param_options__;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBase64String", NullMonoObject, 4, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::Int32 Convert::ToBase64CharArray(std::vector<mscorlib::System::Byte*> inArray, mscorlib::System::Int32 offsetIn, mscorlib::System::Int32 length, std::vector<mscorlib::System::Char*> outArray, mscorlib::System::Int32 offsetOut, mscorlib::System::Base64FormattingOptions::__ENUM__ options)
{
MonoType *__parameter_types__[6];
void *__parameters__[6];
__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameter_types__[1] = Global::GetType(typeid(offsetIn).name());
__parameter_types__[2] = Global::GetType(typeid(length).name());
__parameter_types__[3] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Char")), 1));
__parameter_types__[4] = Global::GetType(typeid(offsetOut).name());
__parameter_types__[5] = Global::GetType(typeid(options).name());
__parameters__[0] = Global::FromArray<mscorlib::System::Byte*>(inArray, typeid(mscorlib::System::Byte).name());
__parameters__[1] = &offsetIn;
__parameters__[2] = &length;
__parameters__[3] = Global::FromPrimitiveArray<mscorlib::System::Char*>(outArray, typeid(mscorlib::System::Char).name());
__parameters__[4] = &offsetOut;
mscorlib::System::Int32 __param_options__ = options;
__parameters__[5] = &__param_options__;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBase64CharArray", NullMonoObject, 6, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean Convert::ToBoolean(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToBoolean", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Byte Convert::ToByte(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Byte(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::Char Convert::ToChar(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToChar", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Char*)mono_object_unbox(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::DateTime Convert::ToDateTime(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDateTime", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::DateTime(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Decimal Convert::ToDecimal(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDecimal", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Decimal(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Double Convert::ToDouble(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToDouble", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Double*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int16 Convert::ToInt16(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int16*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int32 Convert::ToInt32(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::Int64 Convert::ToInt64(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::SByte Convert::ToSByte(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSByte", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::SByte(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::Single Convert::ToSingle(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToSingle", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::Single*)mono_object_unbox(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Boolean value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = reinterpret_cast<void*>(value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Byte value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Byte value, mscorlib::System::Int32 toBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(toBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &toBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Char value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::DateTime value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Decimal value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Double value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Single value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int32 value, mscorlib::System::Int32 toBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(toBase).name());
__parameters__[0] = &value;
__parameters__[1] = &toBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int32 value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int64 value, mscorlib::System::Int32 toBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(toBase).name());
__parameters__[0] = &value;
__parameters__[1] = &toBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int64 value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::SByte value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int16 value, mscorlib::System::Int32 toBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(toBase).name());
__parameters__[0] = &value;
__parameters__[1] = &toBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::Int16 value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::UInt32 value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::UInt64 value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::String Convert::ToString(mscorlib::System::UInt16 value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = &value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToString", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::String(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt16 Convert::ToUInt16(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt16", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt16*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt32 Convert::ToUInt32(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt32", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt32*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Byte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Char value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::DateTime value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Decimal value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Double value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Single value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Int32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Int64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::SByte value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Int16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(const char *value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::String value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(const char *value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::String value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(const char *value, mscorlib::System::Int32 fromBase)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType(typeid(fromBase).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), value);
__parameters__[1] = &fromBase;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::UInt32 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::UInt64 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::UInt16 value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = &value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Object value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::UInt64 Convert::ToUInt64(mscorlib::System::Object value, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ToUInt64", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return *(mscorlib::System::UInt64*)mono_object_unbox(__result__);
}
mscorlib::System::Object Convert::ChangeType(mscorlib::System::Object value, mscorlib::System::Type conversionType)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(conversionType).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)conversionType;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ChangeType", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Convert::ChangeType(mscorlib::System::Object value, mscorlib::System::TypeCode::__ENUM__ typeCode)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(typeCode).name());
__parameters__[0] = (MonoObject*)value;
mscorlib::System::Int32 __param_typeCode__ = typeCode;
__parameters__[1] = &__param_typeCode__;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ChangeType", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Convert::ChangeType(mscorlib::System::Object value, mscorlib::System::Type conversionType, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(conversionType).name());
__parameter_types__[2] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
__parameters__[1] = (MonoObject*)conversionType;
__parameters__[2] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ChangeType", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Convert::ChangeType(mscorlib::System::Object value, mscorlib::System::TypeCode::__ENUM__ typeCode, mscorlib::System::IFormatProvider provider)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameter_types__[1] = Global::GetType(typeid(typeCode).name());
__parameter_types__[2] = Global::GetType(typeid(provider).name());
__parameters__[0] = (MonoObject*)value;
mscorlib::System::Int32 __param_typeCode__ = typeCode;
__parameters__[1] = &__param_typeCode__;
__parameters__[2] = (MonoObject*)provider;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Convert", 0, NULL, "ChangeType", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
// Get/Set:DBNull
mscorlib::System::Object Convert::get_DBNull()
{
return Global::GetFieldValue("mscorlib", "System", "Convert", 0, NULL, "DBNull");
}
void Convert::set_DBNull(mscorlib::System::Object value)
{
throw;
}
}
}
| 50.914758 | 307 | 0.720552 | [
"object",
"vector"
] |
c28b42696c36867e78e5cba3b4a1b8d5ee67f321 | 1,221 | cpp | C++ | code-examples/patterns/lab_k29_2021_03_02_iterator.cpp | kzhereb/knu-ips-ooop-2020-2021 | 777b4a847a537510048fd582eda0816ce05db4b5 | [
"MIT"
] | null | null | null | code-examples/patterns/lab_k29_2021_03_02_iterator.cpp | kzhereb/knu-ips-ooop-2020-2021 | 777b4a847a537510048fd582eda0816ce05db4b5 | [
"MIT"
] | 34 | 2021-03-25T08:28:26.000Z | 2021-05-20T13:12:48.000Z | code-examples/patterns/lab_k29_2021_03_02_iterator.cpp | kzhereb/knu-ips-ooop-2020-2021 | 777b4a847a537510048fd582eda0816ce05db4b5 | [
"MIT"
] | 1 | 2020-09-28T12:58:26.000Z | 2020-09-28T12:58:26.000Z | /*
* lab_k29_2021_03_02_iterator.cpp
*
* Created on: Mar 2, 2021
* Author: KZ
*/
#include "../list/list.h"
#include "../doctest.h"
#include <algorithm>
#include <iterator>
#include <vector>
#include <sstream>
TEST_CASE("std::copy using iterators") {
std::vector<int> source {1, 3, 5, 7, 9};
std::vector<int> destination;
SUBCASE("using std::back_inserter") {
std::copy(source.begin(), source.end(), std::back_inserter(destination));
}
SUBCASE("set size") {
destination.resize(source.size());
std::copy(source.begin(), source.end(), destination.begin());
}
CHECK(destination.size() == source.size());
CHECK(destination[0] == source[0]);
}
TEST_CASE("custom iterator for DoublyLinkedList") {
DoublyLinkedList<int> mylist;
mylist.append(1);
mylist.append(3);
mylist.append(5);
std::stringstream out;
for(int value: mylist) {
out<<value<<std::endl;
}
CHECK(std::string(out.str()) == "1\n3\n5\n");
std::vector<int> destination;
std::copy(mylist.begin(), mylist.end(), std::back_inserter(destination));
CHECK(destination.size() == 3);
for (std::size_t i = 0; i< destination.size(); i++) {
CHECK(destination[i] == mylist[i]);
}
}
| 24.42 | 76 | 0.634726 | [
"vector"
] |
c293fdfd112287bf425bebfa4fbb490a7e2fc382 | 6,793 | cpp | C++ | src/mongo/db/matcher/schema/expression_internal_schema_allowed_properties.cpp | puppyofkosh/mongo | ed601dd01169b8c1fad9fb8d388da0523a1b48f5 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/matcher/schema/expression_internal_schema_allowed_properties.cpp | puppyofkosh/mongo | ed601dd01169b8c1fad9fb8d388da0523a1b48f5 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/matcher/schema/expression_internal_schema_allowed_properties.cpp | puppyofkosh/mongo | ed601dd01169b8c1fad9fb8d388da0523a1b48f5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2017 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/matcher/schema/expression_internal_schema_allowed_properties.h"
namespace mongo {
constexpr StringData InternalSchemaAllowedPropertiesMatchExpression::kName;
void InternalSchemaAllowedPropertiesMatchExpression::init(
boost::container::flat_set<StringData> properties,
StringData namePlaceholder,
std::vector<PatternSchema> patternProperties,
std::unique_ptr<ExpressionWithPlaceholder> otherwise) {
_properties = std::move(properties);
_namePlaceholder = namePlaceholder;
_patternProperties = std::move(patternProperties);
_otherwise = std::move(otherwise);
}
void InternalSchemaAllowedPropertiesMatchExpression::debugString(StringBuilder& debug,
int level) const {
_debugAddSpace(debug, level);
BSONObjBuilder builder;
serialize(&builder);
debug << builder.obj().toString() << "\n";
const auto* tag = getTag();
if (tag) {
debug << " ";
tag->debugString(&debug);
}
debug << "\n";
}
bool InternalSchemaAllowedPropertiesMatchExpression::equivalent(const MatchExpression* expr) const {
if (matchType() != expr->matchType()) {
return false;
}
const auto* other = static_cast<const InternalSchemaAllowedPropertiesMatchExpression*>(expr);
return _properties == other->_properties && _namePlaceholder == other->_namePlaceholder &&
_otherwise->equivalent(other->_otherwise.get()) &&
std::is_permutation(_patternProperties.begin(),
_patternProperties.end(),
other->_patternProperties.begin(),
other->_patternProperties.end(),
[](const auto& expr1, const auto& expr2) {
return expr1.first.rawRegex == expr2.first.rawRegex &&
expr1.second->equivalent(expr2.second.get());
});
}
bool InternalSchemaAllowedPropertiesMatchExpression::matches(const MatchableDocument* doc,
MatchDetails* details) const {
return _matchesBSONObj(doc->toBSON());
}
bool InternalSchemaAllowedPropertiesMatchExpression::matchesSingleElement(const BSONElement& elem,
MatchDetails*) const {
if (elem.type() != BSONType::Object) {
return false;
}
return _matchesBSONObj(elem.embeddedObject());
}
bool InternalSchemaAllowedPropertiesMatchExpression::_matchesBSONObj(const BSONObj& obj) const {
for (auto&& property : obj) {
bool checkOtherwise = true;
for (auto&& constraint : _patternProperties) {
if (constraint.first.regex->PartialMatch(property.fieldName())) {
checkOtherwise = false;
if (!constraint.second->matchesBSONElement(property)) {
return false;
}
}
}
if (checkOtherwise &&
_properties.find(property.fieldNameStringData()) != _properties.end()) {
checkOtherwise = false;
}
if (checkOtherwise && !_otherwise->matchesBSONElement(property)) {
return false;
}
}
return true;
}
void InternalSchemaAllowedPropertiesMatchExpression::serialize(BSONObjBuilder* builder) const {
BSONObjBuilder expressionBuilder(
builder->subobjStart(InternalSchemaAllowedPropertiesMatchExpression::kName));
BSONArrayBuilder propertiesBuilder(expressionBuilder.subarrayStart("properties"));
for (auto&& property : _properties) {
propertiesBuilder.append(property);
}
propertiesBuilder.doneFast();
expressionBuilder.append("namePlaceholder", _namePlaceholder);
BSONArrayBuilder patternPropertiesBuilder(expressionBuilder.subarrayStart("patternProperties"));
for (auto&& item : _patternProperties) {
BSONObjBuilder itemBuilder(patternPropertiesBuilder.subobjStart());
itemBuilder.appendRegex("regex", item.first.rawRegex);
BSONObjBuilder subexpressionBuilder(itemBuilder.subobjStart("expression"));
item.second->getFilter()->serialize(&subexpressionBuilder);
subexpressionBuilder.doneFast();
}
patternPropertiesBuilder.doneFast();
BSONObjBuilder otherwiseBuilder(expressionBuilder.subobjStart("otherwise"));
_otherwise->getFilter()->serialize(&otherwiseBuilder);
otherwiseBuilder.doneFast();
expressionBuilder.doneFast();
}
std::unique_ptr<MatchExpression> InternalSchemaAllowedPropertiesMatchExpression::shallowClone()
const {
std::vector<PatternSchema> clonedPatternProperties;
clonedPatternProperties.reserve(_patternProperties.size());
for (auto&& constraint : _patternProperties) {
clonedPatternProperties.emplace_back(Pattern(constraint.first.rawRegex),
constraint.second->shallowClone());
}
auto clone = stdx::make_unique<InternalSchemaAllowedPropertiesMatchExpression>();
clone->init(_properties,
_namePlaceholder,
std::move(clonedPatternProperties),
_otherwise->shallowClone());
return {std::move(clone)};
}
} // namespace mongo
| 40.921687 | 100 | 0.67599 | [
"object",
"vector"
] |
c29488f886e52f46d4e5501b2eaec6ac16f413fc | 38,852 | cpp | C++ | testing/test_aplicacion_almacenamiento.cpp | miglesias91/visualizador-de-contextos | ec1be5533ccef1b5881ce67b8f0d0ab0280b8d3a | [
"Apache-2.0"
] | null | null | null | testing/test_aplicacion_almacenamiento.cpp | miglesias91/visualizador-de-contextos | ec1be5533ccef1b5881ce67b8f0d0ab0280b8d3a | [
"Apache-2.0"
] | 18 | 2018-02-15T19:02:14.000Z | 2018-06-03T00:33:08.000Z | testing/test_aplicacion_almacenamiento.cpp | miglesias91/visualizador-de-contextos | ec1be5533ccef1b5881ce67b8f0d0ab0280b8d3a | [
"Apache-2.0"
] | null | null | null | // gtest
#include <gtest/gtest.h>
// aplicacion
#include <aplicacion/include/IAdministradorAplicacion.h>
#include <aplicacion/include/ConfiguracionAplicacion.h>
#include <aplicacion/include/GestorEntidades.h>
// modelo
#include <modelo/include/Concepto.h>
#include <modelo/include/Consulta.h>
#include <modelo/include/Fecha.h>
#include <modelo/include/Grafico.h>
#include <modelo/include/Medio.h>
#include <modelo/include/Periodo.h>
using namespace visualizador::modelo;
using namespace visualizador::aplicacion;
TEST(aplicacionAlmacenamiento, GuardarYCargarNuevoConcepto)
{
Termino* termino_corrupcion = new Termino("corrupcion", "etiqueta_corurp");
termino_corrupcion->asignarNuevoId();
Termino* termino_irregularidad = new Termino("irregularidad","etiqueta_irregular");
termino_irregularidad->asignarNuevoId();
std::vector<Termino*> terminos_corrupcion;
terminos_corrupcion.push_back(termino_corrupcion);
terminos_corrupcion.push_back(termino_irregularidad);
Concepto* concepto_corrupcion = new Concepto(terminos_corrupcion, "corrupcion");
concepto_corrupcion->asignarNuevoId();
unsigned long long int hashcode_irregularidad = termino_irregularidad->hashcode();
unsigned long long int hashcode_corrupcion = termino_corrupcion->hashcode();
unsigned long long int hashcode_concepto_corrupcion = concepto_corrupcion->hashcode();
unsigned long long int hashcode_relaciones_irregularidad = termino_irregularidad->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_corrupcion = termino_corrupcion->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_concepto_corrupcion = concepto_corrupcion->getRelaciones()->hashcode();
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_irregularidad);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_irregularidad->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_corrupcion);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_corrupcion->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_corrupcion);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_corrupcion->getRelaciones());
Concepto* concepto_a_recuperar = new Concepto();
concepto_a_recuperar->setId(new herramientas::utiles::ID(*concepto_corrupcion->getId()));
IAdministradorAplicacion::getInstanciaAdminEntidades()->recuperar(concepto_a_recuperar);
IAdministradorAplicacion::getInstanciaAdminEntidades()->recuperar(concepto_a_recuperar->getRelaciones());
concepto_a_recuperar->recuperarContenidoDeRelaciones();
ASSERT_STREQ("corrupcion", concepto_a_recuperar->getEtiqueta().c_str());
ASSERT_EQ(3, concepto_a_recuperar->getId()->numero());
ASSERT_EQ(hashcode_concepto_corrupcion, concepto_a_recuperar->hashcode());
ASSERT_EQ(hashcode_relaciones_concepto_corrupcion, concepto_a_recuperar->getRelaciones()->hashcode());
ASSERT_EQ(3, concepto_a_recuperar->getRelaciones()->getId()->numero());
ASSERT_EQ(1, concepto_a_recuperar->getRelacionesConcepto()->getRelacionConTerminos()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(2, concepto_a_recuperar->getRelacionesConcepto()->getRelacionConTerminos()->getIdsGrupoComoUint()[1]);
ASSERT_STREQ("etiqueta_corurp", concepto_a_recuperar->getTerminos()[0]->getEtiqueta().c_str());
ASSERT_EQ(1, concepto_a_recuperar->getTerminos()[0]->getId()->numero());
ASSERT_STREQ("corrupcion", concepto_a_recuperar->getTerminos()[0]->getValor().c_str());
ASSERT_EQ(hashcode_corrupcion, concepto_a_recuperar->getTerminos()[0]->hashcode());
ASSERT_EQ(hashcode_relaciones_corrupcion, concepto_a_recuperar->getTerminos()[0]->getRelaciones()->hashcode());
ASSERT_EQ(1, concepto_a_recuperar->getTerminos()[0]->getRelaciones()->getId()->numero());
ASSERT_EQ(3, concepto_a_recuperar->getTerminos()[0]->getRelacionesTermino()->getRelacionConConceptos()->getIdsGrupoComoUint()[0]);
ASSERT_STREQ("etiqueta_irregular", concepto_a_recuperar->getTerminos()[1]->getEtiqueta().c_str());
ASSERT_EQ(2, concepto_a_recuperar->getTerminos()[1]->getId()->numero());
ASSERT_STREQ("irregularidad", concepto_a_recuperar->getTerminos()[1]->getValor().c_str());
ASSERT_EQ(hashcode_irregularidad, concepto_a_recuperar->getTerminos()[1]->hashcode());
ASSERT_EQ(hashcode_relaciones_irregularidad, concepto_a_recuperar->getTerminos()[1]->getRelaciones()->hashcode());
ASSERT_EQ(2, concepto_a_recuperar->getTerminos()[1]->getRelaciones()->getId()->numero());
ASSERT_EQ(3, concepto_a_recuperar->getTerminos()[1]->getRelacionesTermino()->getRelacionConConceptos()->getIdsGrupoComoUint()[0]);
delete concepto_a_recuperar;
delete concepto_corrupcion;
}
TEST(aplicacionAlmacenamiento, GuardarYCargarNuevaConsulta)
{
IAlmacenable::getGestorIDs()->setIdActual(0);
// 1ero: armo el modelo
Fecha* inicio_primavera_2017 = new Fecha(21, 9, 2017);
inicio_primavera_2017->asignarNuevoId();
Fecha* fin_primavera_2017 = new Fecha(21, 12, 2017);
fin_primavera_2017->asignarNuevoId();
Periodo* primavera_2017 = new Periodo(inicio_primavera_2017, fin_primavera_2017);
primavera_2017->asignarNuevoId();
Reporte* reporte = new Grafico("torta");
reporte->asignarNuevoId();
std::vector<Termino*> terminos_corrupcion;
Termino* termino_corrupcion = new Termino("corrupcion");
termino_corrupcion->asignarNuevoId();
Termino* termino_irregularidad = new Termino("irregularidad");
termino_irregularidad->asignarNuevoId();
terminos_corrupcion.push_back(termino_corrupcion);
terminos_corrupcion.push_back(termino_irregularidad);
Concepto* concepto_corrupcion = new Concepto(terminos_corrupcion, "corrupcion");
concepto_corrupcion->asignarNuevoId();
Termino* termino_crisis = new Termino("crisis");
termino_crisis->asignarNuevoId();
Termino* termino_conflicto = new Termino("conflicto");
termino_conflicto->asignarNuevoId();
Termino* termino_desorden = new Termino("desorden");
termino_desorden->asignarNuevoId();
std::vector<Termino*> terminos_crisis;
terminos_crisis.push_back(termino_crisis);
terminos_crisis.push_back(termino_conflicto);
terminos_crisis.push_back(termino_desorden);
Concepto* concepto_crisis = new Concepto(terminos_crisis, "crisis");
concepto_crisis->asignarNuevoId();
Termino* termino_movilizacion = new Termino("movilizacion");
termino_movilizacion->asignarNuevoId();
Termino* termino_paro = new Termino("paro");
termino_paro->asignarNuevoId();
Termino* termino_marcha = new Termino("marcha");
termino_marcha->asignarNuevoId();
std::vector<Termino*> terminos_movilizacion;
terminos_movilizacion.push_back(termino_movilizacion);
terminos_movilizacion.push_back(termino_paro);
terminos_movilizacion.push_back(termino_marcha);
Concepto* concepto_movilizacion = new Concepto(terminos_movilizacion);
concepto_movilizacion->asignarNuevoId();
std::vector<Concepto*> conceptos;
conceptos.push_back(concepto_corrupcion);
conceptos.push_back(concepto_crisis);
conceptos.push_back(concepto_movilizacion);
// estos news de los medios en verdad no deberian usarse nunca. (PONER LOS NEW COMO METODOS PRIVADOS.
MedioTwitter* medio_clarin = new MedioTwitter("clarincom", "twitter_clarin");
medio_clarin->asignarNuevoId();
MedioTwitter* medio_infobae = new MedioTwitter("infobae", "twitter_infobae");
medio_infobae->asignarNuevoId();
std::vector<MedioTwitter*> medios;
medios.push_back(medio_clarin);
medios.push_back(medio_infobae);
// estos news de las secciones en verdad no deberian usarse nunca. (PONER LOS NEW COMO METODOS PRIVADOS.
Seccion* seccion_politica = new Seccion("politica");
seccion_politica->asignarNuevoId();
Seccion* seccion_economia = new Seccion("economia");
seccion_economia->asignarNuevoId();
std::vector<Seccion*> secciones;
secciones.push_back(seccion_politica);
secciones.push_back(seccion_economia);
Consulta* consulta = new Consulta(primavera_2017, reporte, conceptos, medios, secciones, "primavera_2017");
consulta->asignarNuevoId();
// 3ero: recupero los hashcodes de las entidades.
unsigned long long int hashcode_fecha_desde = inicio_primavera_2017->hashcode();
unsigned long long int hashcode_fecha_hasta = fin_primavera_2017->hashcode();
unsigned long long int hashcode_periodo = primavera_2017->hashcode();
unsigned long long int hashcode_reporte = reporte->hashcode();
unsigned long long int hashcode_termino_corrupcion = termino_corrupcion->hashcode();
unsigned long long int hashcode_termino_irregularidad = termino_irregularidad->hashcode();
unsigned long long int hashcode_concepto_corrupcion = concepto_corrupcion->hashcode();
unsigned long long int hashcode_termino_crisis = termino_crisis->hashcode();
unsigned long long int hashcode_termino_conflicto = termino_conflicto->hashcode();
unsigned long long int hashcode_termino_desorden = termino_desorden->hashcode();
unsigned long long int hashcode_concepto_crisis = concepto_crisis->hashcode();
unsigned long long int hashcode_termino_movilizacion = termino_movilizacion->hashcode();
unsigned long long int hashcode_termino_paro = termino_paro->hashcode();
unsigned long long int hashcode_termino_marcha = termino_marcha->hashcode();
unsigned long long int hashcode_concepto_movilizacion = concepto_movilizacion->hashcode();
unsigned long long int hashcode_medio_clarin = medio_clarin->hashcode();
unsigned long long int hashcode_medio_infobae = medio_infobae->hashcode();
unsigned long long int hashcode_seccion_politica = seccion_politica->hashcode();
unsigned long long int hashcode_seccion_economia = seccion_economia->hashcode();
unsigned long long int hashcode_consulta = consulta->hashcode();
unsigned long long int hashcode_relaciones_consulta = consulta->getRelaciones()->hashcode();
// 3ero: ahora si recupero los hashcodes de las relaciones porque ya se agrego el id de 'consulta' a las relaciones de todos. (se agrego cuando le asigne un nuevo id a 'consulta': linea 205: "consulta->asignarNuevoId();").
unsigned long long int hashcode_relaciones_fecha_desde = inicio_primavera_2017->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_fecha_hasta = fin_primavera_2017->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_periodo = primavera_2017->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_reporte = reporte->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_corrupcion = termino_corrupcion->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_irregularidad = termino_irregularidad->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_concepto_corrupcion = concepto_corrupcion->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_crisis = termino_crisis->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_desorden = termino_desorden->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_conflicto = termino_conflicto->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_concepto_crisis = concepto_crisis->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_movilizacion = termino_movilizacion->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_paro = termino_paro->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_termino_marcha = termino_marcha->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_concepto_movilizacion = concepto_movilizacion->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_medio_clarin = medio_clarin->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_medio_infobae = medio_infobae->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_seccion_politica = seccion_politica->getRelaciones()->hashcode();
unsigned long long int hashcode_relaciones_seccion_economia = seccion_economia->getRelaciones()->hashcode();
// 4to: almaceno todo (con cada una de sus relaciones actualizadas y correctas.
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(inicio_primavera_2017);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(inicio_primavera_2017->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(fin_primavera_2017);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(fin_primavera_2017->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(primavera_2017);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(primavera_2017->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(reporte);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(reporte->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_corrupcion);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_corrupcion->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_irregularidad);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_irregularidad->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_corrupcion);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_corrupcion->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_crisis);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_crisis->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_conflicto);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_conflicto->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_desorden);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_desorden->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_crisis);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_crisis->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_movilizacion);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_movilizacion->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_paro);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_paro->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_marcha);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_marcha->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_movilizacion);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_movilizacion->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(medio_clarin);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(medio_clarin->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(medio_infobae);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(medio_infobae->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(seccion_politica);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(seccion_politica->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(seccion_economia);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(seccion_economia->getRelaciones());
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(consulta);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(consulta->getRelaciones());
// 5to: AHORA RECUPERO TODO
Consulta* consulta_a_recuperar = new Consulta();
consulta_a_recuperar->setId(new herramientas::utiles::ID(*consulta->getId()));
IAdministradorAplicacion::getInstanciaAdminEntidades()->recuperar(consulta_a_recuperar);
IAdministradorAplicacion::getInstanciaAdminEntidades()->recuperar(consulta_a_recuperar->getRelaciones());
consulta_a_recuperar->recuperarContenidoDeRelaciones();
// test consulta
ASSERT_STREQ("primavera_2017", consulta_a_recuperar->getEtiqueta().c_str());
ASSERT_EQ(19, consulta_a_recuperar->getId()->numero());
ASSERT_EQ(hashcode_consulta, consulta_a_recuperar->hashcode());
// test relaciones consulta
ASSERT_EQ(hashcode_relaciones_consulta, consulta_a_recuperar->getRelaciones()->hashcode());
ASSERT_EQ(17, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConSecciones()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(18, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConSecciones()->getIdsGrupoComoUint()[1]);
ASSERT_EQ(15, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConMediosTwitter()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(16, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConMediosTwitter()->getIdsGrupoComoUint()[1]);
ASSERT_EQ(6, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConConceptos()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(10, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConConceptos()->getIdsGrupoComoUint()[1]);
ASSERT_EQ(14, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConConceptos()->getIdsGrupoComoUint()[2]);
ASSERT_EQ(3, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConReporte());
ASSERT_EQ(2, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConPeriodo());
// test secciones
ASSERT_STREQ("politica", consulta_a_recuperar->getSecciones()[0]->getEtiqueta().c_str());
ASSERT_EQ(17, consulta_a_recuperar->getSecciones()[0]->getId()->numero());
ASSERT_EQ(hashcode_seccion_politica, consulta_a_recuperar->getSecciones()[0]->hashcode());
ASSERT_STREQ("economia", consulta_a_recuperar->getSecciones()[1]->getEtiqueta().c_str());
ASSERT_EQ(18, consulta_a_recuperar->getSecciones()[1]->getId()->numero());
ASSERT_EQ(hashcode_seccion_economia, consulta_a_recuperar->getSecciones()[1]->hashcode());
// test relaciones secciones
ASSERT_EQ(19, consulta_a_recuperar->getSecciones()[0]->getRelacionesSeccion()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_seccion_politica, consulta_a_recuperar->getSecciones()[0]->getRelaciones()->hashcode());
ASSERT_EQ(19, consulta_a_recuperar->getSecciones()[1]->getRelacionesSeccion()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_seccion_economia, consulta_a_recuperar->getSecciones()[1]->getRelaciones()->hashcode());
// test medios
ASSERT_STREQ("twitter_clarin", consulta_a_recuperar->getMediosTwitter()[0]->getEtiqueta().c_str());
ASSERT_STREQ("clarincom", consulta_a_recuperar->getMediosTwitter()[0]->getNombreUsuario().c_str());
ASSERT_EQ(15, consulta_a_recuperar->getMediosTwitter()[0]->getId()->numero());
ASSERT_EQ(hashcode_medio_clarin, consulta_a_recuperar->getMediosTwitter()[0]->hashcode());
ASSERT_STREQ("twitter_infobae", consulta_a_recuperar->getMediosTwitter()[1]->getEtiqueta().c_str());
ASSERT_STREQ("infobae", consulta_a_recuperar->getMediosTwitter()[1]->getNombreUsuario().c_str());
ASSERT_EQ(16, consulta_a_recuperar->getMediosTwitter()[1]->getId()->numero());
ASSERT_EQ(hashcode_medio_infobae, consulta_a_recuperar->getMediosTwitter()[1]->hashcode());
// test relaciones medios
ASSERT_EQ(19, consulta_a_recuperar->getMediosTwitter()[0]->getRelacionesMedio()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_medio_clarin, consulta_a_recuperar->getMediosTwitter()[0]->getRelaciones()->hashcode());
ASSERT_EQ(19, consulta_a_recuperar->getMediosTwitter()[1]->getRelacionesMedio()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_medio_infobae, consulta_a_recuperar->getMediosTwitter()[1]->getRelaciones()->hashcode());
// test concepto 0
ASSERT_STREQ("corrupcion", consulta_a_recuperar->getConceptos()[0]->getEtiqueta().c_str());
ASSERT_EQ(6, consulta_a_recuperar->getConceptos()[0]->getId()->numero());
ASSERT_EQ(hashcode_concepto_corrupcion, consulta_a_recuperar->getConceptos()[0]->hashcode());
ASSERT_STREQ("corrupcion", consulta_a_recuperar->getConceptos()[0]->getTerminos()[0]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[0]->getTerminos()[0]->getEtiqueta().c_str());
ASSERT_EQ(4, consulta_a_recuperar->getConceptos()[0]->getTerminos()[0]->getId()->numero());
ASSERT_EQ(hashcode_termino_corrupcion, consulta_a_recuperar->getConceptos()[0]->getTerminos()[0]->hashcode());
ASSERT_STREQ("irregularidad", consulta_a_recuperar->getConceptos()[0]->getTerminos()[1]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[0]->getTerminos()[1]->getEtiqueta().c_str());
ASSERT_EQ(5, consulta_a_recuperar->getConceptos()[0]->getTerminos()[1]->getId()->numero());
ASSERT_EQ(hashcode_termino_irregularidad, consulta_a_recuperar->getConceptos()[0]->getTerminos()[1]->hashcode());
// test relaciones concepto 0
ASSERT_EQ(19, consulta_a_recuperar->getConceptos()[0]->getRelacionesConcepto()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_concepto_corrupcion, consulta_a_recuperar->getConceptos()[0]->getRelaciones()->hashcode());
// test concepto 1
ASSERT_STREQ("crisis", consulta_a_recuperar->getConceptos()[1]->getEtiqueta().c_str());
ASSERT_EQ(10, consulta_a_recuperar->getConceptos()[1]->getId()->numero());
ASSERT_EQ(hashcode_concepto_crisis, consulta_a_recuperar->getConceptos()[1]->hashcode());
ASSERT_STREQ("crisis", consulta_a_recuperar->getConceptos()[1]->getTerminos()[0]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[1]->getTerminos()[0]->getEtiqueta().c_str());
ASSERT_EQ(7, consulta_a_recuperar->getConceptos()[1]->getTerminos()[0]->getId()->numero());
ASSERT_EQ(hashcode_termino_crisis, consulta_a_recuperar->getConceptos()[1]->getTerminos()[0]->hashcode());
ASSERT_STREQ("conflicto", consulta_a_recuperar->getConceptos()[1]->getTerminos()[1]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[1]->getTerminos()[1]->getEtiqueta().c_str());
ASSERT_EQ(8, consulta_a_recuperar->getConceptos()[1]->getTerminos()[1]->getId()->numero());
ASSERT_EQ(hashcode_termino_conflicto, consulta_a_recuperar->getConceptos()[1]->getTerminos()[1]->hashcode());
ASSERT_STREQ("desorden", consulta_a_recuperar->getConceptos()[1]->getTerminos()[2]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[1]->getTerminos()[2]->getEtiqueta().c_str());
ASSERT_EQ(9, consulta_a_recuperar->getConceptos()[1]->getTerminos()[2]->getId()->numero());
ASSERT_EQ(hashcode_termino_desorden, consulta_a_recuperar->getConceptos()[1]->getTerminos()[2]->hashcode());
// test relaciones concepto 1
ASSERT_EQ(19, consulta_a_recuperar->getConceptos()[1]->getRelacionesConcepto()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_concepto_crisis, consulta_a_recuperar->getConceptos()[1]->getRelaciones()->hashcode());
// test concepto 2
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[2]->getEtiqueta().c_str());
ASSERT_EQ(14, consulta_a_recuperar->getConceptos()[2]->getId()->numero());
ASSERT_EQ(hashcode_concepto_movilizacion, consulta_a_recuperar->getConceptos()[2]->hashcode());
ASSERT_STREQ("movilizacion", consulta_a_recuperar->getConceptos()[2]->getTerminos()[0]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[2]->getTerminos()[0]->getEtiqueta().c_str());
ASSERT_EQ(11, consulta_a_recuperar->getConceptos()[2]->getTerminos()[0]->getId()->numero());
ASSERT_EQ(hashcode_termino_movilizacion, consulta_a_recuperar->getConceptos()[2]->getTerminos()[0]->hashcode());
ASSERT_STREQ("paro", consulta_a_recuperar->getConceptos()[2]->getTerminos()[1]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[2]->getTerminos()[1]->getEtiqueta().c_str());
ASSERT_EQ(12, consulta_a_recuperar->getConceptos()[2]->getTerminos()[1]->getId()->numero());
ASSERT_EQ(hashcode_termino_paro, consulta_a_recuperar->getConceptos()[2]->getTerminos()[1]->hashcode());
ASSERT_STREQ("marcha", consulta_a_recuperar->getConceptos()[2]->getTerminos()[2]->getValor().c_str());
ASSERT_STREQ("", consulta_a_recuperar->getConceptos()[2]->getTerminos()[2]->getEtiqueta().c_str());
ASSERT_EQ(13, consulta_a_recuperar->getConceptos()[2]->getTerminos()[2]->getId()->numero());
ASSERT_EQ(hashcode_termino_marcha, consulta_a_recuperar->getConceptos()[2]->getTerminos()[2]->hashcode());
// test relaciones concepto 2
ASSERT_EQ(19, consulta_a_recuperar->getConceptos()[2]->getRelacionesConcepto()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_concepto_movilizacion, consulta_a_recuperar->getConceptos()[2]->getRelaciones()->hashcode());
// test reporte
ASSERT_STREQ("torta", consulta_a_recuperar->getReporte()->getEtiqueta().c_str());
ASSERT_EQ(3, consulta_a_recuperar->getReporte()->getId()->numero());
ASSERT_EQ(hashcode_reporte, consulta_a_recuperar->getReporte()->hashcode());
// test relaciones reporte
ASSERT_EQ(19, consulta_a_recuperar->getReporte()->getRelacionesReporte()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_reporte, consulta_a_recuperar->getReporte()->getRelaciones()->hashcode());
// test periodo
ASSERT_STREQ("", consulta_a_recuperar->getPeriodo()->getEtiqueta().c_str());
ASSERT_EQ(2, consulta_a_recuperar->getPeriodo()->getId()->numero());
ASSERT_EQ(hashcode_periodo, consulta_a_recuperar->getPeriodo()->hashcode());
ASSERT_STREQ("", consulta_a_recuperar->getPeriodo()->getDesde()->getEtiqueta().c_str());
ASSERT_EQ(0, consulta_a_recuperar->getPeriodo()->getDesde()->getId()->numero());
ASSERT_EQ(21, consulta_a_recuperar->getPeriodo()->getDesde()->getDia());
ASSERT_EQ(9, consulta_a_recuperar->getPeriodo()->getDesde()->getMes());
ASSERT_EQ(2017, consulta_a_recuperar->getPeriodo()->getDesde()->getAnio());
ASSERT_EQ(hashcode_fecha_desde, consulta_a_recuperar->getPeriodo()->getDesde()->hashcode());
ASSERT_STREQ("", consulta_a_recuperar->getPeriodo()->getHasta()->getEtiqueta().c_str());
ASSERT_EQ(1, consulta_a_recuperar->getPeriodo()->getHasta()->getId()->numero());
ASSERT_EQ(21, consulta_a_recuperar->getPeriodo()->getHasta()->getDia());
ASSERT_EQ(12, consulta_a_recuperar->getPeriodo()->getHasta()->getMes());
ASSERT_EQ(2017, consulta_a_recuperar->getPeriodo()->getHasta()->getAnio());
ASSERT_EQ(hashcode_fecha_hasta, consulta_a_recuperar->getPeriodo()->getHasta()->hashcode());
// test relaciones reporte
ASSERT_EQ(19, consulta_a_recuperar->getPeriodo()->getRelacionesPeriodo()->getRelacionConConsultas()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(hashcode_relaciones_periodo, consulta_a_recuperar->getPeriodo()->getRelaciones()->hashcode());
delete consulta;
delete consulta_a_recuperar;
}
TEST(aplicacionAlmacenamiento, GuardarYCargarIDActualCorrectamente)
{
IAlmacenable::getGestorIDs()->setIdActual(100);
Termino* termino_corrupcion = new Termino("corrupcion", "etiqueta_corurp");
termino_corrupcion->asignarNuevoId();
Termino* termino_irregularidad = new Termino("irregularidad", "etiqueta_irregular");
termino_irregularidad->asignarNuevoId();
std::vector<Termino*> terminos_corrupcion;
terminos_corrupcion.push_back(termino_corrupcion);
terminos_corrupcion.push_back(termino_irregularidad);
Concepto* concepto_corrupcion = new Concepto(terminos_corrupcion, "corrupcion");
concepto_corrupcion->asignarNuevoId();
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_irregularidad);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(termino_corrupcion);
IAdministradorAplicacion::getInstanciaAdminEntidades()->almacenar(concepto_corrupcion);
Concepto* concepto_a_recuperar = new Concepto();
concepto_a_recuperar->setId(new herramientas::utiles::ID(*concepto_corrupcion->getId()));
IAdministradorAplicacion::getInstanciaAdminEntidades()->recuperar(concepto_a_recuperar);
IAdministradorAplicacion::getInstanciaAdminEntidades()->cerrarBD();
unsigned long long int id_actual = IAlmacenable::getGestorIDs()->getIdActual();
IAdministradorAplicacion::getInstanciaAdminEntidades()->abrirBD();
unsigned long long int id_actual_recuperado = IAdministradorAplicacion::getInstanciaAdminEntidades()->recuperarIDActual();
delete concepto_corrupcion;
delete concepto_a_recuperar;
ASSERT_EQ(id_actual, id_actual_recuperado);
}
TEST(aplicacionAlmacenamiento, GestorEntidadAlmacenarCorrectamente)
{
IAlmacenable::getGestorIDs()->setIdActual(200);
Termino* termino1 = new Termino("termino_ok", "gestorentidad-almacenamiento-test");
termino1->asignarNuevoId();
Termino* termino2 = new Termino("termino_ok2", "gestorentidad-almacenamiento-test");
termino2->asignarNuevoId();
std::vector<Termino*> terminos_corrupcion;
terminos_corrupcion.push_back(termino1);
terminos_corrupcion.push_back(termino2);
Concepto* concepto1 = new Concepto(terminos_corrupcion, "gestorentidad-almacenamiento-test");
concepto1->asignarNuevoId();
GestorEntidades gestor_terminos;
gestor_terminos.gestionar<Termino>();
gestor_terminos.almacenar(termino1);
gestor_terminos.almacenar(termino2);
gestor_terminos.guardarCambios();
GestorEntidades gestor_conceptos;
gestor_conceptos.gestionar<Concepto>();
gestor_conceptos.almacenar(concepto1);
gestor_conceptos.guardarCambios();
GestorEntidades gestor_conceptos_nuevo;
gestor_conceptos_nuevo.gestionar<Concepto>();
bool existe = gestor_conceptos_nuevo.existe(concepto1);
delete concepto1;
ASSERT_EQ(true, existe);
}
TEST(aplicacionAlmacenamiento, GestorEntidadEliminarCorrectamente)
{
IAlmacenable::getGestorIDs()->setIdActual(200);
GestorEntidades gestor_conceptos;
gestor_conceptos.gestionar<Concepto>();
Termino* termino1 = new Termino("termino_ok", "gestorentidad-almacenamiento-test");
termino1->asignarNuevoId();
Termino* termino2 = new Termino("termino_ok2", "gestorentidad-almacenamiento-test");
termino2->asignarNuevoId();
std::vector<Termino*> terminos_corrupcion;
terminos_corrupcion.push_back(termino1);
terminos_corrupcion.push_back(termino2);
Concepto* concepto1 = new Concepto(terminos_corrupcion, "gestorentidad-almacenamiento-test");
concepto1->asignarNuevoId();
gestor_conceptos.eliminar(concepto1);
gestor_conceptos.guardarCambios();
GestorEntidades gestor_terminos;
gestor_terminos.gestionar<Termino>();
gestor_terminos.eliminar(termino1);
gestor_terminos.eliminar(termino2);
gestor_terminos.guardarCambios();
GestorEntidades gestor_conceptos_nuevo;
gestor_conceptos_nuevo.gestionar<Concepto>();
bool existe1 = gestor_conceptos_nuevo.existe(concepto1);
GestorEntidades gestor_terminos_nuevo;
gestor_terminos_nuevo.gestionar<Termino>();
bool existe2 = gestor_terminos_nuevo.existe(termino1);
bool existe3 = gestor_terminos_nuevo.existe(termino2);
delete concepto1;
ASSERT_EQ(false, existe1);
ASSERT_EQ(false, existe2);
ASSERT_EQ(false, existe3);
}
TEST(aplicacionAlmacenamiento, GestorEntidadVinculacionRelacionesCorrecta)
{
IAlmacenable::getGestorIDs()->setIdActual(300);
// 1ero: armo el modelo
Fecha* inicio_primavera_2017 = new Fecha(21, 9, 2017);
inicio_primavera_2017->asignarNuevoId();
Fecha* fin_primavera_2017 = new Fecha(21, 12, 2017);
fin_primavera_2017->asignarNuevoId();
Periodo* primavera_2017 = new Periodo(inicio_primavera_2017, fin_primavera_2017);
primavera_2017->asignarNuevoId();
Reporte* reporte = new Grafico("torta");
reporte->asignarNuevoId();
std::vector<Termino*> terminos_corrupcion;
Termino* termino_corrupcion = new Termino("corrupcion");
termino_corrupcion->asignarNuevoId();
Termino* termino_irregularidad = new Termino("irregularidad");
termino_irregularidad->asignarNuevoId();
terminos_corrupcion.push_back(termino_corrupcion);
terminos_corrupcion.push_back(termino_irregularidad);
Concepto* concepto_corrupcion = new Concepto(terminos_corrupcion, "corrupcion");
concepto_corrupcion->asignarNuevoId();
Termino* termino_crisis = new Termino("crisis");
termino_crisis->asignarNuevoId();
Termino* termino_conflicto = new Termino("conflicto");
termino_conflicto->asignarNuevoId();
Termino* termino_desorden = new Termino("desorden");
termino_desorden->asignarNuevoId();
std::vector<Termino*> terminos_crisis;
terminos_crisis.push_back(termino_crisis);
terminos_crisis.push_back(termino_conflicto);
terminos_crisis.push_back(termino_desorden);
Concepto* concepto_crisis = new Concepto(terminos_crisis, "crisis");
concepto_crisis->asignarNuevoId();
Termino* termino_movilizacion = new Termino("movilizacion");
termino_movilizacion->asignarNuevoId();
Termino* termino_paro = new Termino("paro");
termino_paro->asignarNuevoId();
Termino* termino_marcha = new Termino("marcha");
termino_marcha->asignarNuevoId();
std::vector<Termino*> terminos_movilizacion;
terminos_movilizacion.push_back(termino_movilizacion);
terminos_movilizacion.push_back(termino_paro);
terminos_movilizacion.push_back(termino_marcha);
Concepto* concepto_movilizacion = new Concepto(terminos_movilizacion);
concepto_movilizacion->asignarNuevoId();
std::vector<Concepto*> conceptos;
conceptos.push_back(concepto_corrupcion);
conceptos.push_back(concepto_crisis);
conceptos.push_back(concepto_movilizacion);
// estos news de los medios en verdad no deberian usarse nunca. (PONER LOS NEW COMO METODOS PRIVADOS.
MedioTwitter* medio_clarin = new MedioTwitter("clarin");
medio_clarin->asignarNuevoId();
MedioTwitter* medio_infobae = new MedioTwitter("infobae");
medio_infobae->asignarNuevoId();
std::vector<MedioTwitter*> medios;
medios.push_back(medio_clarin);
medios.push_back(medio_infobae);
// estos news de las secciones en verdad no deberian usarse nunca. (PONER LOS NEW COMO METODOS PRIVADOS.
Seccion* seccion_politica = new Seccion("politica");
seccion_politica->asignarNuevoId();
Seccion* seccion_economia = new Seccion("economia");
seccion_economia->asignarNuevoId();
std::vector<Seccion*> secciones;
secciones.push_back(seccion_politica);
secciones.push_back(seccion_economia);
Consulta* consulta = new Consulta(primavera_2017, reporte, conceptos, medios, secciones, "primavera_2017");
consulta->asignarNuevoId();
// 2do: guardo todas las entidades y sus relaciones.
GestorEntidades gestor_entidades;
gestor_entidades.almacenar(inicio_primavera_2017);
gestor_entidades.almacenar(fin_primavera_2017);
gestor_entidades.almacenar(primavera_2017);
gestor_entidades.almacenar(reporte);
gestor_entidades.almacenar(termino_corrupcion);
gestor_entidades.almacenar(termino_irregularidad);
gestor_entidades.almacenar(concepto_corrupcion);
gestor_entidades.almacenar(termino_crisis);
gestor_entidades.almacenar(termino_conflicto);
gestor_entidades.almacenar(termino_desorden);
gestor_entidades.almacenar(concepto_crisis);
gestor_entidades.almacenar(termino_movilizacion);
gestor_entidades.almacenar(termino_paro);
gestor_entidades.almacenar(termino_marcha);
gestor_entidades.almacenar(concepto_movilizacion);
gestor_entidades.almacenar(medio_clarin);
gestor_entidades.almacenar(medio_infobae);
gestor_entidades.almacenar(seccion_politica);
gestor_entidades.almacenar(seccion_economia);
gestor_entidades.almacenar(consulta);
gestor_entidades.guardarCambios();
// 3ero: elimino algunas entidades para ver si se cumplen los cambios en las relaciones.
gestor_entidades.eliminar(seccion_politica);
gestor_entidades.eliminar(medio_clarin);
gestor_entidades.eliminar(concepto_crisis);
gestor_entidades.eliminar(termino_movilizacion);
gestor_entidades.guardarCambios();
// 4to: recupero la consulta a ver si se modificaron las relaciones.
Consulta* consulta_a_recuperar = new Consulta();
consulta_a_recuperar->setId(new herramientas::utiles::ID(*consulta->getId()));
gestor_entidades.recuperar(consulta_a_recuperar);
// test relaciones consulta
ASSERT_EQ(318, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConSecciones()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(316, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConMediosTwitter()->getIdsGrupoComoUint()[0]);;
ASSERT_EQ(306, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConConceptos()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(314, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConConceptos()->getIdsGrupoComoUint()[1]);
ASSERT_EQ(303, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConReporte());
ASSERT_EQ(302, consulta_a_recuperar->getRelacionesConsulta()->getRelacionConPeriodo());
// test relaciones concepto
ASSERT_EQ(312, consulta_a_recuperar->getConceptos()[1]->getRelacionesConcepto()->getRelacionConTerminos()->getIdsGrupoComoUint()[0]);
ASSERT_EQ(313, consulta_a_recuperar->getConceptos()[1]->getRelacionesConcepto()->getRelacionConTerminos()->getIdsGrupoComoUint()[1]);
delete consulta;
delete consulta_a_recuperar;
} | 53.662983 | 227 | 0.769716 | [
"vector"
] |
c2954ec3ce9aafbe52a58f951797a2cb0998165d | 1,578 | cpp | C++ | Algorithms/1970.Last_Day_Where_You_Can_Still_Cross.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/1970.Last_Day_Where_You_Can_Still_Cross.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/1970.Last_Day_Where_You_Can_Still_Cross.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | #define fi first
#define se second
typedef pair<int,int> pi;
class Solution {
public:
int n,m;
int day[20001];
int dir[4] = {0,1,0,-1};
int id(int r , int c) {
return r*m+c;
}
bool check(int d) {
queue<pi> q;
bool mark[n][m];
memset(mark,false,sizeof(mark));
for( int i = 0 ; i < m ; i++ )
if(d < day[id(0,i)]) {
q.push(pi(0,i));
mark[0][i] = true;
}
while(!q.empty()) {
pi p = q.front();
q.pop();
int r = p.fi;
int c = p.se;
if(r == n-1)
return true;
for( int i = 0 ; i < 4 ; i++ ) {
int x = r + dir[i];
int y = c + dir[i^1];
if(x < 0 || x >= n || y < 0 || y >= m)
continue;
if(mark[x][y] || d >= day[id(x,y)])
continue;
q.push(pi(x,y));
mark[x][y] = true;
}
}
return false;
}
int latestDayToCross(int row, int col, vector<vector<int>>& ar) {
n = row;
m = col;
for( int i = 0 ; i < n*m ; i++ ) {
int r = ar[i][0];
int c = ar[i][1];
r--,c--;
day[id(r,c)] = i+1;
}
int l = 1 , r = n*m , ans = 0;
while(l <= r) {
int mid = (l+r) >> 1;
if(check(mid))
ans = mid , l = mid+1;
else
r = mid-1;
}
return ans;
}
}; | 25.868852 | 69 | 0.333967 | [
"vector"
] |
c2a0f061eb4b50e54bed45f809a9fd1d36ca453c | 5,590 | hpp | C++ | src/rdb_protocol/wire_func.hpp | zadcha/rethinkdb | bb4f5cc28242dc1e29e9a46a8a931ec54420070c | [
"Apache-2.0"
] | 21,684 | 2015-01-01T03:42:20.000Z | 2022-03-30T13:32:44.000Z | src/rdb_protocol/wire_func.hpp | RethonkDB/rethonkdb | 8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee | [
"Apache-2.0"
] | 4,067 | 2015-01-01T00:04:51.000Z | 2022-03-30T13:42:56.000Z | src/rdb_protocol/wire_func.hpp | RethonkDB/rethonkdb | 8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee | [
"Apache-2.0"
] | 1,901 | 2015-01-01T21:05:59.000Z | 2022-03-21T08:14:25.000Z | // Copyright 2010-2015 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_WIRE_FUNC_HPP_
#define RDB_PROTOCOL_WIRE_FUNC_HPP_
#include <vector>
#include "containers/counted.hpp"
#include "containers/optional.hpp"
#include "rdb_protocol/sym.hpp"
#include "rdb_protocol/error.hpp"
#include "rpc/serialize_macros.hpp"
#include "version.hpp"
namespace ql {
class raw_term_t;
class func_t;
class env_t;
class wire_func_t {
public:
wire_func_t();
explicit wire_func_t(const counted_t<const func_t> &f);
~wire_func_t();
wire_func_t(const wire_func_t ©ee);
wire_func_t &operator=(const wire_func_t &assignee);
// Constructs a wire_func_t with a body and arglist, but no scope.
wire_func_t(const raw_term_t &body,
std::vector<sym_t> arg_names);
counted_t<const func_t> compile_wire_func() const;
backtrace_id_t get_bt() const;
template <cluster_version_t W>
friend void serialize(write_message_t *wm, const wire_func_t &);
template <cluster_version_t W>
friend archive_result_t deserialize(read_stream_t *s, wire_func_t *wf);
template <cluster_version_t W>
friend archive_result_t deserialize_wire_func(read_stream_t *s, wire_func_t *wf);
bool is_simple_selector() const;
std::string print_source() const;
private:
bool has() const { return func.has(); }
friend class maybe_wire_func_t; // for has().
counted_t<const func_t> func;
};
class maybe_wire_func_t {
protected:
template<class... Args>
explicit maybe_wire_func_t(Args... args) : wrapped(args...) { }
public:
template <cluster_version_t W>
friend void serialize(write_message_t *wm, const maybe_wire_func_t &);
template <cluster_version_t W>
friend archive_result_t deserialize(read_stream_t *s, maybe_wire_func_t *);
counted_t<const func_t> compile_wire_func_or_null() const;
private:
bool has() const { return wrapped.has(); }
wire_func_t wrapped;
};
class map_wire_func_t : public wire_func_t {
public:
template <class... Args>
explicit map_wire_func_t(Args... args) : wire_func_t(args...) { }
};
class filter_wire_func_t {
public:
filter_wire_func_t() { }
filter_wire_func_t(const ql::wire_func_t &_filter_func,
const optional<ql::wire_func_t> &_default_filter_val)
: filter_func(_filter_func),
default_filter_val(_default_filter_val) { }
filter_wire_func_t(const counted_t<const func_t> &_filter_func,
const optional<ql::wire_func_t> &_default_filter_val)
: filter_func(_filter_func),
default_filter_val(_default_filter_val) { }
ql::wire_func_t filter_func;
optional<ql::wire_func_t> default_filter_val;
};
RDB_DECLARE_SERIALIZABLE(filter_wire_func_t);
class reduce_wire_func_t : public wire_func_t {
public:
template <class... Args>
explicit reduce_wire_func_t(Args... args) : wire_func_t(args...) { }
};
enum class result_hint_t { NO_HINT, AT_MOST_ONE };
class concatmap_wire_func_t : public wire_func_t {
public:
concatmap_wire_func_t() { }
template <class... Args>
explicit concatmap_wire_func_t(result_hint_t _result_hint, Args... args)
: wire_func_t(args...), result_hint(_result_hint) { }
// We use this so that terms which rewrite to a `concat_map` but can never
// produce more than one result can be handled correctly by `changes`.
result_hint_t result_hint;
};
// These are fake functions because we don't need to send anything.
// TODO: make `count` behave like `sum`, `avg`, etc.
struct count_wire_func_t {
};
RDB_DECLARE_SERIALIZABLE(count_wire_func_t);
class zip_wire_func_t {
};
RDB_DECLARE_SERIALIZABLE_FOR_CLUSTER(zip_wire_func_t);
class group_wire_func_t {
public:
group_wire_func_t() : bt(backtrace_id_t::empty()) { }
group_wire_func_t(std::vector<counted_t<const func_t> > &&_funcs,
bool _append_index, bool _multi);
std::vector<counted_t<const func_t> > compile_funcs() const;
bool should_append_index() const;
bool is_multi() const;
backtrace_id_t get_bt() const;
RDB_DECLARE_ME_SERIALIZABLE(group_wire_func_t);
private:
std::vector<wire_func_t> funcs;
bool append_index, multi;
backtrace_id_t bt;
};
class distinct_wire_func_t {
public:
distinct_wire_func_t() : use_index(false) { }
explicit distinct_wire_func_t(bool _use_index) : use_index(_use_index) { }
bool use_index;
};
RDB_DECLARE_SERIALIZABLE_FOR_CLUSTER(distinct_wire_func_t);
template <class T>
class skip_terminal_t;
class skip_wire_func_t : public maybe_wire_func_t {
protected:
skip_wire_func_t() { }
template <class... Args>
explicit skip_wire_func_t(backtrace_id_t _bt, Args... args)
: maybe_wire_func_t(args...), bt(_bt) { }
private:
template <class T>
friend class skip_terminal_t;
backtrace_id_t bt;
};
class sum_wire_func_t : public skip_wire_func_t {
public:
template <class... Args>
explicit sum_wire_func_t(Args... args) : skip_wire_func_t(args...) { }
};
class avg_wire_func_t : public skip_wire_func_t {
public:
template <class... Args>
explicit avg_wire_func_t(Args... args) : skip_wire_func_t(args...) { }
};
class min_wire_func_t : public skip_wire_func_t {
public:
template <class... Args>
explicit min_wire_func_t(Args... args) : skip_wire_func_t(args...) { }
};
class max_wire_func_t : public skip_wire_func_t {
public:
template <class... Args>
explicit max_wire_func_t(Args... args) : skip_wire_func_t(args...) { }
};
} // namespace ql
#endif // RDB_PROTOCOL_WIRE_FUNC_HPP_
| 30.546448 | 85 | 0.721646 | [
"vector"
] |
c2a113951cd2c4cf5931fbabcba31d47a9c5e5b8 | 6,359 | hpp | C++ | include/http_handler.hpp | RobertLeahy/MCPP | 2b9223afa35ae215b9af7e5398ce8f7f6dd70377 | [
"Unlicense"
] | 19 | 2015-04-25T15:19:59.000Z | 2022-02-28T03:00:42.000Z | include/http_handler.hpp | RobertLeahy/MCPP | 2b9223afa35ae215b9af7e5398ce8f7f6dd70377 | [
"Unlicense"
] | 1 | 2016-01-28T08:50:02.000Z | 2021-08-24T02:34:48.000Z | include/http_handler.hpp | RobertLeahy/MCPP | 2b9223afa35ae215b9af7e5398ce8f7f6dd70377 | [
"Unlicense"
] | 7 | 2015-04-17T16:38:45.000Z | 2021-06-25T03:39:39.000Z | /**
* \file
*/
#pragma once
#include <rleahylib/rleahylib.hpp>
#include <promise.hpp>
#include <socketpair.hpp>
#include <curl/curl.h>
#include <cstddef>
#include <exception>
#include <memory>
#include <unordered_map>
namespace MCPP {
/**
* A single HTTP request or response
* header.
*/
class HTTPHeader {
public:
/**
* The key associated with this
* header.
*/
String Key;
/**
* The value associated with this
* header.
*/
String Value;
};
/**
* A single HTTP cookie.
*/
class HTTPCookie {
public:
/**
* The key associated with this
* cookie.
*/
String Key;
/**
* The value associated with this
* cookie.
*/
String Value;
};
/**
* The response to an HTTP request.
*/
class HTTPResponse {
public:
/**
* The numerical status code associated
* with this response.
*/
Word Status;
/**
* HTTP major version number.
*/
Word MajorVersion;
/**
* HTTP minor version number.
*/
Word MinorVersion;
/**
* Server's response.
*/
String Response;
/**
* The headers that were sent in the
* response.
*/
Vector<HTTPHeader> Headers;
/**
* Raw bytes representing the body of the
* response.
*/
Vector<Byte> Body;
/**
* Attempts to retrieve the body of the
* response as a string.
*
* Scans the headers looking for a character
* set. If a character set cannot be found,
* falls back to UTF-8.
*
* \return
* A string representing the body of this
* response.
*/
String GetBody () const;
};
/**
* HTTP verbs.
*/
enum class HTTPVerb {
GET,
POST,
HEAD
};
/**
* An HTTP request.
*/
class HTTPRequest {
public:
/**
* Creates a new GET request.
*/
HTTPRequest () noexcept;
/**
* Creates a new GET request with default
* settings for the specified URL.
*
* \param [in] url
* The URL to which to send this request.
*/
HTTPRequest (String url) noexcept;
/**
* The URL to which this request shall be
* sent.
*/
String URL;
/**
* The HTTP verb that shall be invoked.
*/
HTTPVerb Verb;
/**
* A collection of headers to send.
*/
Vector<HTTPHeader> Headers;
/**
* The body of the request. Only relevant
* for verbs with a body.
*/
Vector<Byte> Body;
/**
* The referer.
*/
Nullable<String> Referer;
/**
* The user agent string.
*/
Nullable<String> UserAgent;
/**
* A collection of cookies to be sent.
*/
Vector<HTTPCookie> Cookies;
/**
* Whether this request requires SSL or
* TLS.
*/
bool RequireSSL;
/**
* The maximum number of bytes which will
* be accepted as part of the header before
* the request will be terminated.
*/
Nullable<Word> MaxHeaderBytes;
/**
* The maximum number of bytes which will be
* accepted as part of the body before the
* request will be terminated.
*/
Nullable<Word> MaxBodyBytes;
/**
* Whether redirects should be followed.
*/
bool FollowRedirects;
/**
* If redirects are to be followed, how many
* should be followed. Null means an
* unlimited number.
*/
Nullable<Word> MaxRedirects;
};
/**
* An exception thrown to indicate that the HTTPHandler
* shut down during the execution of a request.
*/
class HTTPHandlerError : public std::exception {
public:
virtual const char * what () const noexcept override;
};
/**
* Provides asynchronous HTTP handling mechanisms.
*/
class HTTPHandler {
public:
typedef std::function<void (std::exception_ptr)> PanicType;
private:
class Request {
private:
CURL * handle;
Nullable<Promise<HTTPResponse>> promise;
HTTPResponse response;
// The original request
HTTPRequest request;
// Encoded strings for legacy cURL
Vector<char> url;
Vector<char> referer;
Vector<char> uas;
Vector<char> cookies;
// Values that are actually relevant
// to the consumer
Vector<Byte> request_body;
Word headers_curr;
std::exception_ptr ex;
template <typename... Args>
void set (CURLoption, Args &&...);
static std::size_t header (void *, std::size_t, std::size_t, void *) noexcept;
static std::size_t body (char *, std::size_t, std::size_t, void *) noexcept;
public:
Request (HTTPRequest);
~Request () noexcept;
void Complete (CURLcode) noexcept;
Word Header (const void *, Word) noexcept;
Word ResponseBody (const void *, Word) noexcept;
Tuple<CURL *,Promise<HTTPResponse>> Get () const noexcept;
};
// Control
ControlSocket control;
// Multi handle
CURLM * handle;
// Worker thread
Thread thread;
// Pending requests and shutdown
// synchronization
mutable Mutex lock;
mutable CondVar wait;
bool stop;
std::unordered_map<
CURL *,
std::unique_ptr<Request>
> requests;
// Called on panic
PanicType panic;
// Panics
[[noreturn]]
void do_panic () const noexcept;
// Determines -- based on control socket --
// whether worker should stop
bool should_stop ();
// Worker functions
void worker_func () noexcept;
void worker ();
public:
/**
* Creates and starts a new HTTPHandler.
*
* \param [in] panic
* A callback which will be invoked when
* and if something goes wrong internal
* to the handler. Optional. Default is
* to call std::abort.
*/
HTTPHandler (PanicType panic=PanicType{});
/**
* Shuts down and destroys an HTTPHandler.
*/
~HTTPHandler () noexcept;
/**
* Asynchronously performs an HTTP request.
*
* \param [in] request
* The request to perform.
*
* \return
* A promise of a future HTTP response.
*/
Promise<HTTPResponse> Execute (HTTPRequest request);
};
}
| 15.937343 | 83 | 0.569115 | [
"vector"
] |
c2a3e0aef67ef536b0681449cae64ac0ae46cbae | 12,395 | cpp | C++ | Sources/Utilities/Execution/ExecutionThread.cpp | XessWaffle/3redNet | 809b6fe22f5a14d531fe26360faab634be19f621 | [
"MIT"
] | null | null | null | Sources/Utilities/Execution/ExecutionThread.cpp | XessWaffle/3redNet | 809b6fe22f5a14d531fe26360faab634be19f621 | [
"MIT"
] | null | null | null | Sources/Utilities/Execution/ExecutionThread.cpp | XessWaffle/3redNet | 809b6fe22f5a14d531fe26360faab634be19f621 | [
"MIT"
] | null | null | null | #include "ExecutionThread.h"
#include "Error.cuh"
#define MAX_VECTORS 10
ExecutionThread::ExecutionThread() {
}
ExecutionThread::ExecutionThread(std::string data_path, std::string network_path, NeuralNetwork to_manage, Dimension input) {
this->to_manage = to_manage;
this->input_space = input;
this->manage_nnfm = NeuralNetworkFileManager(network_path, to_manage.name);
this->manage_input_dat = DataTextFileManager(data_path, to_manage.name + "_IN");
this->manage_output_dat = DataTextFileManager(data_path, to_manage.name + "_OUT");
this->network_outputs = DataTextFileManager(network_path, to_manage.name + "_OUTPUTS");
manage_input_dat.read(0);
std::string input_line = manage_input_dat.get_read_stack().at(0);
chnl_tot = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
z_tot = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
t_tot = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
printf("Chnl: %i > Z: %i > T: %i\n", chnl_tot, z_tot, t_tot);
manage_input_dat.clear_read_stack();
int curr_dev;
cudaGetDevice(&curr_dev);
cudaStreamCreate(&stream);
to_manage.set_stream(stream);
printf("Copying %s Network to GPU %i\n", to_manage.name.c_str(), curr_dev);
this->to_manage.malloc();
}
ExecutionThread::ExecutionThread(std::string data_path, std::string network_path, std::string name, Dimension input) {
this->input_space = input;
this->manage_nnfm = NeuralNetworkFileManager(network_path, name);
this->manage_input_dat = DataTextFileManager(data_path, name + "_IN");
this->manage_output_dat = DataTextFileManager(data_path, name + "_OUT");
this->network_outputs = DataTextFileManager(network_path, name + "_OUTPUTS");
manage_input_dat.read(0);
std::string input_line = manage_input_dat.get_read_stack().at(0);
printf("input_line %s", input_line);
chnl_tot = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
z_tot = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
t_tot = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
printf("Chnl: %i > Z: %i > T: %i\n", chnl_tot, z_tot, t_tot);
manage_input_dat.clear_read_stack();
printf("Loading network %s.", name.c_str());
manage_nnfm.prepare_parse(); printf(".");
manage_nnfm.read_network_file(); printf(".");
manage_nnfm.read_network_dimensions(); printf(".");
manage_nnfm.parse_network(); printf(".complete\n");
this->to_manage = manage_nnfm.get_parsed();
this->to_manage.name = name;
int curr_dev;
cudaGetDevice(&curr_dev);
cudaStreamCreate(&stream);
to_manage.set_stream(stream);
printf("Copying %s Network to GPU %i\n", name.c_str(), curr_dev);
this->to_manage.malloc();
}
NeuralNetwork ExecutionThread::get_network() {
return to_manage;
}
void ExecutionThread::set_network(NeuralNetwork n_manage) {
this->to_manage = n_manage;
}
void ExecutionThread::load_data(int image) {
int read_index = 2;
int i = 0;
std::string input_line;
int input_data_size = 0;
printf("Reading Image %i", image);
do {
manage_input_dat.read_until("IMAGE_END");
//printf("Read Loc: %i\n", read_index);
if (image != 0) {
input_line = manage_input_dat.get_read_stack().at(0);
}
else {
input_line = manage_input_dat.get_read_stack().at(1);
}
//printf("Input Line: %s\n", input_line.c_str());
input_data_size = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
curr_c = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
if (curr_c == channel_focus && channel_focus != -1) {
break;
}
else if (channel_focus == -1) {
break;
}
image++;
i++;
printf(", %i", image);
manage_input_dat.clear_read_stack();
// read_index = read_index + input_data_size + 2;
} while (true);
printf("Read Location %i\n", read_index);
curr_t = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
curr_z = std::stoi(input_line.substr(0, input_line.find(',')));
input_line = input_line.erase(0, input_line.find(',') + 1);
//manage_input_dat.clear_read_stack();
//manage_input_dat.read_all(read_index + 1, read_index + input_data_size + 1);
std::vector<std::string> input_lines = manage_input_dat.get_read_stack();
image -= i;
if (image == 0) {
input_lines.erase(input_lines.begin());
input_lines.erase(input_lines.begin());
}
else {
input_lines.erase(input_lines.begin());
}
printf("Loading Vectors.");
for (int i = 0; i < input_data_size; i++) {
std::string to_parse = input_lines.at(i);
start_x = std::stoi(to_parse.substr(0, to_parse.find(',')));
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
start_y = std::stoi(to_parse.substr(0, to_parse.find(',')));
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
//printf("Start Loc: (%i, %i)\n", start_x, start_y);
int num_vectors = std::stoi(to_parse.substr(0, to_parse.find(',')));
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
Vector* vec_alloc = new Vector[MAX_VECTORS];
//printf("Vectors Found: ");
for (int v = 0; v < num_vectors; v++) {
Vector to_add = { 0,0,0 };
to_add.x = std::stod(to_parse.substr(0, to_parse.find(',')));
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
to_add.y = std::stod(to_parse.substr(0, to_parse.find(',')));
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
to_add.z = curr_z;
vec_alloc[v] = to_add;
//printf("{%i, %i, %i}, ", to_add.x, to_add.y, to_add.z);
}
for (int v = num_vectors; v < MAX_VECTORS; v++) {
Vector to_add = { -1,-1, curr_z };
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
vec_alloc[v] = to_add;
}
outputs_per_input.push_back(vec_alloc);
int num_img_vals = input_space.width * input_space.height * input_space.depth;
double* img_vals = new double[num_img_vals];
//printf("Parse: %s\n", to_parse.c_str());
for (int j = 0; j < num_img_vals; j++) {
try {
img_vals[j] = std::stod(to_parse.substr(0, to_parse.find(',')));
}
catch (std::exception &e) {
img_vals[j] = 0;
}
to_parse = to_parse.erase(0, to_parse.find(',') + 1);
}
input.push_back(img_vals);
if (i % 300 == 0) {
printf(".");
}
}
printf("complete\n");
load_complete = true;
}
void ExecutionThread::push_data() {
Dimension wrap = to_manage.get_layer(0).get_dim();
printf("Wrap = {%i, %i, %i}: Beginning push....", wrap.width, wrap.height, wrap.depth);
for (int i = 0; i < input.size(); i++) {
to_manage.nem.push(input.at(i), wrap.width * wrap.height * wrap.depth);
if (i % 400 == 0) {
printf(".");
}
}
printf("complete\n");
push_complete = true;
}
void ExecutionThread::execute(int i) {
Dimension fin_dim = to_manage.get_layer(to_manage.layers - 1).get_dim();
Dimension wrap_dim = to_manage.get_layer(0).get_dim();
execution_complete = false;
printf("%s Iteration %i:", to_manage.name.c_str(), i);
double* preferred = det_pref(i);
std::string pref_string = "";
pref_string += "" + std::to_string(i) + ",0.0,";
for (int j = 0; j < fin_dim.width * fin_dim.height; j++) {
pref_string += "" + std::to_string(preferred[j]);
pref_string += ",";
}
manage_output_dat.push_write(pref_string);
to_manage.execute(preferred);
execution_complete = true;
double* output = to_manage.output;
double error = 0.0;
Error calc = Error();
std::string output_string = "";
output_string += "" + std::to_string(i);
output_string += ",";
for (int j = 0; j < fin_dim.width * fin_dim.height; j++) {
error += calc.compute(output[j], preferred[j], ErrorType::MSE);
}
printf(" Error - %f :> complete\n", error);
cudaDeviceSynchronize();
output_string += "" + std::to_string(error);
output_string += ",";
for (int j = 0; j < fin_dim.width * fin_dim.height; j++) {
output_string += "" + std::to_string(output[j]);
output_string += ",";
}
manage_output_dat.push_write(output_string);
curr_img_index++;
}
void ExecutionThread::execute_manual() {
Dimension fin_dim = to_manage.get_layer(to_manage.layers - 1).get_dim();
Dimension wrap_dim = to_manage.get_layer(0).get_dim();
for (int i = 0; i < input.size(); i++) {
to_manage.execute();
double* output = to_manage.output;
std::string output_string = "";
output_string += "" + std::to_string(i);
output_string += ",";
if (i == input.size() / 2) {
execution_half_complete = true;
}
for (int j = 0; j < fin_dim.width * fin_dim.height; j++) {
output_string += "" + std::to_string(output[j]);
output_string += ",";
}
manage_output_dat.push_write(output_string);
}
curr_img_index++;
execution_complete = true;
}
void ExecutionThread::write() {
printf("Writing Data... \n");
manage_output_dat.write_stack();
for (int i = 0; i < input.size(); i++) {
delete[] input.at(i);
delete[] outputs_per_input.at(i);
}
input.clear();
outputs_per_input.clear();
write_complete = true;
}
void ExecutionThread::save() {
to_manage.save();
manage_nnfm.set_to_write(to_manage);
manage_nnfm.prepare_write();
manage_nnfm.write_network_file();
manage_nnfm.write_network_dimensions();
manage_nnfm.write_network();
save_complete = true;
}
void ExecutionThread::set_channel_focus(int channel_focus) {
this->channel_focus = channel_focus;
}
void ExecutionThread::set_execution_device(int device) {
this->execution_device = device;
}
void ExecutionThread::run_manual() {
if (begin_load) {
std::thread ld(&ExecutionThread::load_data, this, 1);
begin_load = false;
}
if (begin_push) {
std::thread pd(&ExecutionThread::push_data, this);
begin_push = false;
}
if (begin_execution) {
std::thread ex(&ExecutionThread::execute_manual, this);
begin_execution = false;
}
if (prep_save) {
std::thread s(&ExecutionThread::save, this);
return;
}
if (begin_write) {
std::thread wr(&ExecutionThread::write, this);
begin_write = false;
}
if (load_complete) {
begin_load = false;
begin_push = true;
load_complete = false;
}
if (push_complete) {
begin_push = false;
begin_execution = true;
push_complete = false;
}
if (execution_complete) {
begin_execution = false;
begin_write = true;
execution_complete = false;
}
if (execution_half_complete) {
begin_load = true;
execution_half_complete = false;
}
if (curr_img_index == chnl_tot * t_tot * z_tot - 1) {
data_file_complete = true;
return;
}
}
void ExecutionThread::run(int image) {
finished = false;
manage_output_dat.push_write("IMAGE_START,\n");
load_data(image);
printf("Load Finished\n");
push_data();
for (int i = 0; i < input.size(); i++) {
while (!begin_execution) {}
execute(i);
begin_execution = false;
}
manage_output_dat.push_write("IMAGE_END,\n");
write();
if (curr_img_index == chnl_tot / 2 * t_tot * z_tot - 1) {
data_file_complete = true;
return;
}
to_manage.apply();
finshed = true;
}
void ExecutionThread::stop() {
prep_save = true;
}
void ExecutionThread::set_save() {
prep_save = true;
}
void ExecutionThread::set_execution() {
begin_execution = true;
}
double* ExecutionThread::det_pref(int index) {
Dimension fin_dim = to_manage.get_layer(to_manage.layers - 1).get_dim();
Dimension wrap_dim = to_manage.get_layer(0).get_dim();
Vector* vectors = outputs_per_input.at(index);
double* preferred = new double[fin_dim.width * fin_dim.height * fin_dim.depth];
for (int x = 0; x < fin_dim.width; x++) {
for (int y = 0; y < fin_dim.height; y++) {
if (x == 0) {
if (vectors[y].x > 1) {
preferred[x + y * fin_dim.width] = vectors[y].x - start_x;
}
else {
preferred[x + y * fin_dim.width] = -1;
}
}
else if (x == 1) {
if (vectors[y].x > 1) {
preferred[x + y * fin_dim.width] = vectors[y].y - start_y;
}
else {
preferred[x + y * fin_dim.width] = -1;
}
}
else {
preferred[x + y * fin_dim.width] = 1.0;
}
}
}
return preferred;
}
| 22.784926 | 125 | 0.666317 | [
"vector"
] |
c2ad7db383504f764621344ac0b1dcd34f6e258f | 6,334 | cc | C++ | be/src/runtime/sorted-run-merger.cc | AtScaleInc/Impala | 1073a9108220faffe61c3bc9dff7a953adde12df | [
"Apache-2.0"
] | 51 | 2015-01-02T04:10:26.000Z | 2020-11-21T16:33:19.000Z | be/src/runtime/sorted-run-merger.cc | AtScaleInc/Impala | 1073a9108220faffe61c3bc9dff7a953adde12df | [
"Apache-2.0"
] | 58 | 2015-01-29T15:52:19.000Z | 2016-04-19T08:19:02.000Z | be/src/runtime/sorted-run-merger.cc | AtScaleInc/Impala | 1073a9108220faffe61c3bc9dff7a953adde12df | [
"Apache-2.0"
] | 8 | 2015-03-16T11:03:41.000Z | 2019-07-11T06:39:31.000Z | // Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "runtime/sorted-run-merger.h"
#include "exprs/expr.h"
#include "runtime/descriptors.h"
#include "runtime/row-batch.h"
#include "runtime/sorter.h"
#include "runtime/tuple-row.h"
#include "util/runtime-profile.h"
using namespace boost;
using namespace std;
namespace impala {
// BatchedRowSupplier returns individual rows in a batch obtained from a sorted input
// run (a RunBatchSupplier). Used as the heap element in the min heap maintained by the
// merger.
// Next() advances the row supplier to the next row in the input batch and retrieves
// the next batch from the input if the current input batch is exhausted. Transfers
// ownership from the current input batch to an output batch if requested.
class SortedRunMerger::BatchedRowSupplier {
public:
// Construct an instance from a sorted input run.
BatchedRowSupplier(SortedRunMerger* parent, const RunBatchSupplier& sorted_run)
: sorted_run_(sorted_run),
input_row_batch_(NULL),
input_row_batch_index_(-1),
parent_(parent) {
}
// Retrieves the first batch of sorted rows from the run.
Status Init(bool* done) {
RETURN_IF_ERROR(sorted_run_(&input_row_batch_));
if (input_row_batch_ == NULL) {
*done = true;
return Status::OK;
}
RETURN_IF_ERROR(Next(NULL, done));
return Status::OK;
}
// Increment the current row index. If the current input batch is exhausted fetch the
// next one from the sorted run. Transfer ownership to transfer_batch if not NULL.
Status Next(RowBatch* transfer_batch, bool* done) {
DCHECK_NOTNULL(input_row_batch_);
++input_row_batch_index_;
if (input_row_batch_index_ < input_row_batch_->num_rows()) {
*done = false;
} else {
ScopedTimer<MonotonicStopWatch> timer(parent_->get_next_batch_timer_);
if (transfer_batch != NULL) {
input_row_batch_->TransferResourceOwnership(transfer_batch);
}
RETURN_IF_ERROR(sorted_run_(&input_row_batch_));
DCHECK(input_row_batch_ == NULL || input_row_batch_->num_rows() > 0);
*done = input_row_batch_ == NULL;
input_row_batch_index_ = 0;
}
return Status::OK;
}
TupleRow* current_row() const {
return input_row_batch_->GetRow(input_row_batch_index_);
}
private:
friend class SortedRunMerger;
// The run from which this object supplies rows.
RunBatchSupplier sorted_run_;
// The current input batch being processed.
RowBatch* input_row_batch_;
// Index into input_row_batch_ of the current row being processed.
int input_row_batch_index_;
// The parent merger instance.
SortedRunMerger* parent_;
};
void SortedRunMerger::Heapify(int parent_index) {
int left_index = 2 * parent_index + 1;
int right_index = left_index + 1;
if (left_index >= min_heap_.size()) return;
int least_child;
// Find the least child of parent.
if (right_index >= min_heap_.size() ||
compare_less_than_(min_heap_[left_index]->current_row(),
min_heap_[right_index]->current_row())) {
least_child = left_index;
} else {
least_child = right_index;
}
// If the parent is out of place, swap it with the least child and invoke
// Heapify recursively.
if (compare_less_than_(min_heap_[least_child]->current_row(),
min_heap_[parent_index]->current_row())) {
iter_swap(min_heap_.begin() + least_child, min_heap_.begin() + parent_index);
Heapify(least_child);
}
}
SortedRunMerger::SortedRunMerger(const TupleRowComparator& compare_less_than,
RowDescriptor* row_desc, RuntimeProfile* profile, bool deep_copy_input)
: compare_less_than_(compare_less_than),
input_row_desc_(row_desc),
deep_copy_input_(deep_copy_input) {
get_next_timer_ = ADD_TIMER(profile, "MergeGetNext");
get_next_batch_timer_ = ADD_TIMER(profile, "MergeGetNextBatch");
}
Status SortedRunMerger::Prepare(const vector<RunBatchSupplier>& input_runs) {
DCHECK_EQ(min_heap_.size(), 0);
min_heap_.reserve(input_runs.size());
BOOST_FOREACH(const RunBatchSupplier& input_run, input_runs) {
BatchedRowSupplier* new_elem = pool_.Add(new BatchedRowSupplier(this, input_run));
bool empty;
RETURN_IF_ERROR(new_elem->Init(&empty));
if (!empty) min_heap_.push_back(new_elem);
}
// Construct the min heap from the sorted runs.
int last_parent = (min_heap_.size() / 2) - 1;
for (int i = last_parent; i >= 0; --i) {
Heapify(i);
}
return Status::OK;
}
Status SortedRunMerger::GetNext(RowBatch* output_batch, bool* eos) {
ScopedTimer<MonotonicStopWatch> timer(get_next_timer_);
if (min_heap_.empty()) {
*eos = true;
return Status::OK;
}
while (!output_batch->AtCapacity()) {
BatchedRowSupplier* min = min_heap_[0];
int output_row_index = output_batch->AddRow();
TupleRow* output_row = output_batch->GetRow(output_row_index);
if (deep_copy_input_) {
min->current_row()->DeepCopy(output_row, input_row_desc_->tuple_descriptors(),
output_batch->tuple_data_pool(), false);
} else {
// Simply copy tuple pointers if deep_copy is false.
memcpy(output_row, min->current_row(),
input_row_desc_->tuple_descriptors().size() * sizeof(Tuple*));
}
output_batch->CommitLastRow();
bool min_run_complete;
// Advance to the next element in min. output_batch is supplied to transfer
// resource ownership if the input batch in min is exhausted.
RETURN_IF_ERROR(min->Next(deep_copy_input_ ? NULL : output_batch,
&min_run_complete));
if (min_run_complete) {
// Remove the element from the heap.
iter_swap(min_heap_.begin(), min_heap_.end() - 1);
min_heap_.pop_back();
if (min_heap_.empty()) break;
}
Heapify(0);
}
*eos = min_heap_.empty();
return Status::OK;
}
}
| 33.513228 | 87 | 0.715346 | [
"object",
"vector"
] |
c2af5f463ab5b086124ca62fcd03907c67325852 | 7,902 | cpp | C++ | src/CorpseSummoner.cpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | null | null | null | src/CorpseSummoner.cpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | null | null | null | src/CorpseSummoner.cpp | frederic-tingaud-sonarsource/xania | 0cf7bcbd72a0fc4acb3a9d33ba8f325833aeacc9 | [
"BSD-2-Clause"
] | null | null | null | /************************************************************************/
/* Xania (M)ulti(U)ser(D)ungeon server source code */
/* (C) 2020 Xania Development Team */
/* See the header to file: merc.h for original code copyrights */
/************************************************************************/
#include "CorpseSummoner.hpp"
#include "AFFECT_DATA.hpp"
#include "AffectFlag.hpp"
#include "Char.hpp"
#include "Object.hpp"
#include "ObjectExtraFlag.hpp"
#include "ObjectType.hpp"
#include "Room.hpp"
#include "TimeInfoData.hpp"
#include "VnumRooms.hpp"
#include "common/BitOps.hpp"
#include "handler.hpp"
#include "interp.h"
#include "lookup.h"
#include "string_utils.hpp"
#include <fmt/format.h>
using namespace std::chrono;
using namespace std::literals;
SpecialFunc spec_lookup(std::string_view name);
CorpseSummoner::CorpseSummoner(Dependencies &dependencies) : mud_{dependencies}, last_advice_time_{0} {}
time_t CorpseSummoner::last_advice_time() { return last_advice_time_; }
void CorpseSummoner::summoner_awaits(Char *ch, const time_t time_secs) {
if (time_secs - last_advice_time_ > 30) {
last_advice_time_ = time_secs;
mud_.interpret(ch,
"say If you wish to summon your corpse, purchase a shard that is powerful enough for your level "
"and give it to me. Please read the sign for more details."sv);
}
}
void CorpseSummoner::SummonCorpse(Char *player, Char *summoner, Object *catalyst) {
mud_.act("$n clutches $p between $s bony fingers and begins to whisper.", summoner, catalyst, nullptr, To::Room);
mud_.act("The runes on the summoning stone begin to glow more brightly!", summoner, catalyst, nullptr, To::Room);
std::string corpse_name = fmt::format("corpse of {}", player->name);
if (auto corpse = get_pc_corpse_world(summoner, corpse_name)) {
mud_.obj_from_room(*corpse);
mud_.obj_to_room(*corpse, summoner->in_room);
mud_.act("|BThere is a flash of light and a corpse materialises on the ground before you!|w", summoner, nullptr,
nullptr, To::Room);
apply_summoning_fatigue(player);
} else {
mud_.act("The runes dim and the summoner tips $s head in shame.", summoner, nullptr, nullptr, To::Room);
}
mud_.extract_obj(catalyst);
}
bool CorpseSummoner::check_summoner_preconditions(Char *player, Char *summoner) {
if (player->is_npc() || summoner->is_pc() || summoner->spec_fun != mud_.spec_fun_summoner()) {
return false;
} else
return true;
}
std::optional<std::string_view> CorpseSummoner::is_catalyst_invalid(Char *player, Object *catalyst) {
if (!check_enum_bit(catalyst->extra_flags, ObjectExtraFlag::SummonCorpse)) {
return object_wrong_type;
} else if (catalyst->level + ShardLevelRange < player->level) {
return object_too_weak;
} else
return {};
}
bool CorpseSummoner::check_catalyst(Char *player, Char *summoner, Object *catalyst) {
if (auto reason = is_catalyst_invalid(player, catalyst)) {
mud_.act("|C$n tells you '$t|C'|w", summoner, *reason, player, To::Vict, MobTrig::Yes, Position::Type::Dead);
mud_.obj_from_char(catalyst);
mud_.obj_to_char(catalyst, player);
mud_.act("$n gives $p to $N.", summoner, catalyst, player, To::NotVict);
mud_.act("$n gives you $p.", summoner, catalyst, player, To::Vict);
return false;
} else
return true;
}
/*
* Find a player corpse in the world.
* Similar to get_obj_world(), it ignores corpses in ch's current room as well as object visibility and it
* matches on short description because corpse names (keywords) don't include the
* corpse owner's name.
*/
std::optional<Object *> CorpseSummoner::get_pc_corpse_world(Char *ch, std::string_view corpse_short_descr) {
for (auto obj : mud_.object_list()) {
if (obj->type == ObjectType::Pccorpse && obj->in_room && obj->in_room != ch->in_room) {
if (matches(corpse_short_descr, obj->short_descr))
return obj;
}
}
return {};
}
/**
* Temporarily weaken the person who requested the summoning.
*/
void CorpseSummoner::apply_summoning_fatigue(Char *player) {
AFFECT_DATA af;
af.type = mud_.weaken_sn();
af.level = 5;
af.duration = 2;
af.location = AffectLocation::Str;
af.modifier = -3;
af.bitvector = to_int(AffectFlag::Weaken);
mud_.affect_to_char(player, af);
player->send_line("You are stunned and fall the ground.");
mud_.act("$n is knocked off $s feet!", player, nullptr, nullptr, To::Room);
player->position = Position::Type::Resting;
}
namespace {
/**
* The default implementation of CorpseSummoner's dependencies is intentionally
* hidden in this file and anon namespace.
*/
class DependenciesImpl : public CorpseSummoner::Dependencies {
public:
DependenciesImpl();
void interpret(Char *ch, std::string_view msg);
void act(std::string_view msg, const Char *ch, Act1Arg arg1, Act2Arg arg2, const To to, const MobTrig mob_trig,
const Position::Type position);
void act(std::string_view msg, const Char *ch, Act1Arg arg1, Act2Arg arg2, const To to);
void obj_from_char(Object *obj);
void obj_to_char(Object *obj, Char *ch);
void obj_from_room(Object *obj);
void obj_to_room(Object *obj, Room *room);
void extract_obj(Object *obj);
void affect_to_char(Char *ch, const AFFECT_DATA &af);
GenericList<Object *> &object_list();
[[nodiscard]] SpecialFunc spec_fun_summoner() const;
[[nodiscard]] int weaken_sn() const;
private:
const SpecialFunc spec_fun_summoner_;
const int weaken_sn_;
};
DependenciesImpl::DependenciesImpl()
: spec_fun_summoner_{spec_lookup("spec_summoner")}, weaken_sn_{skill_lookup("weaken")} {}
void DependenciesImpl::interpret(Char *ch, std::string_view msg) { ::interpret(ch, msg); }
void DependenciesImpl::act(std::string_view msg, const Char *ch, Act1Arg arg1, Act2Arg arg2, const To to,
const MobTrig mob_trig, const Position::Type position) {
::act(msg, ch, arg1, arg2, to, mob_trig, position);
}
void DependenciesImpl::act(std::string_view msg, const Char *ch, Act1Arg arg1, Act2Arg arg2, const To to) {
::act(msg, ch, arg1, arg2, to);
}
void DependenciesImpl::obj_from_char(Object *obj) { ::obj_from_char(obj); }
void DependenciesImpl::obj_to_char(Object *obj, Char *ch) { ::obj_to_char(obj, ch); }
void DependenciesImpl::obj_from_room(Object *obj) { ::obj_from_room(obj); }
void DependenciesImpl::obj_to_room(Object *obj, Room *room) { ::obj_to_room(obj, room); }
void DependenciesImpl::extract_obj(Object *obj) { ::extract_obj(obj); }
void DependenciesImpl::affect_to_char(Char *ch, const AFFECT_DATA &af) { ::affect_to_char(ch, af); }
GenericList<Object *> &DependenciesImpl::object_list() { return ::object_list; }
SpecialFunc DependenciesImpl::spec_fun_summoner() const { return spec_fun_summoner_; }
int DependenciesImpl::weaken_sn() const { return weaken_sn_; }
DependenciesImpl dependencies;
CorpseSummoner corpse_summoner(dependencies);
}
/**
* Special program for corpse summoner NPCs. Currently just one of
* these in the Necropolis, but there could be more in future.
*/
bool spec_summoner(Char *ch) {
if (ch->is_pos_preoccupied() || ch->in_room->vnum != Rooms::MidgaardNecropolis)
return false;
corpse_summoner.summoner_awaits(ch, system_clock::to_time_t(current_time));
return true;
}
void handle_corpse_summoner(Char *player, Char *summoner, Object *catalyst) {
if (!corpse_summoner.check_summoner_preconditions(player, summoner)) {
return;
}
if (!corpse_summoner.check_catalyst(player, summoner, catalyst)) {
return;
}
corpse_summoner.SummonCorpse(player, summoner, catalyst);
}
| 38.735294 | 120 | 0.67793 | [
"object"
] |
c2af60f78f0ae12b18cd4ae9a43050c3a54855b2 | 19,768 | cpp | C++ | src/ngraph/runtime/intelgpu/visualize_tree.cpp | huningxin/ngraph | 28622bdea4b4ad84405b8484b31673ae7d31cf76 | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/intelgpu/visualize_tree.cpp | huningxin/ngraph | 28622bdea4b4ad84405b8484b31673ae7d31cf76 | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/intelgpu/visualize_tree.cpp | huningxin/ngraph | 28622bdea4b4ad84405b8484b31673ae7d31cf76 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <fstream>
#include <map>
#include <memory>
#include "ngraph/runtime/intelgpu/visualize_tree.hpp"
#include "ngraph/node.hpp"
#include "ngraph/op/all.hpp"
#include "ngraph/op/any.hpp"
#include "ngraph/op/argmax.hpp"
#include "ngraph/op/argmin.hpp"
#include "ngraph/op/avg_pool.hpp"
#include "ngraph/op/batch_norm.hpp"
#include "ngraph/op/broadcast.hpp"
#include "ngraph/op/concat.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/convolution.hpp"
#include "ngraph/op/dot.hpp"
#include "ngraph/op/get_output_element.hpp"
#include "ngraph/op/lrn.hpp"
#include "ngraph/op/max.hpp"
#include "ngraph/op/max_pool.hpp"
#include "ngraph/op/min.hpp"
#include "ngraph/op/one_hot.hpp"
#include "ngraph/op/pad.hpp"
#include "ngraph/op/product.hpp"
#include "ngraph/op/reduce.hpp"
#include "ngraph/op/reduce_window.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/op/slice.hpp"
#include "ngraph/op/sum.hpp"
#include "ngraph/util.hpp"
using namespace ngraph;
using namespace std;
#define NGRAPH_OP(a, b) a,
enum class OP_TYPEID
{
#include "ngraph/op/op_tbl.hpp"
UNDEFINED_OP
};
#undef NGRAPH_OP
static OP_TYPEID get_typeid(const string& s)
{
// This expands the op list in op_tbl.hpp into a list of enumerations that look like this:
// {"Abs", OP_TYPEID::Abs},
// {"Acos", OP_TYPEID::Acos},
// ...
#define NGRAPH_OP(a, b) {#a, OP_TYPEID::a},
static const unordered_map<string, OP_TYPEID> typeid_map{
#include "ngraph/op/op_tbl.hpp"
};
#undef NGRAPH_OP
auto it = typeid_map.find(s);
if (it == typeid_map.end())
{
return OP_TYPEID::UNDEFINED_OP;
}
return it->second;
}
static const string table_begin = "\n<table border=\"0\">";
static const string table_end = "\n</table>";
static const string cell_end = "</td>";
static const string table_row_end = cell_end + "</tr>";
static const string font_small_begin = "<font point-size=\"7\">";
static const string font_end = "</font>";
static string cell_begin(const string& align = string("left"))
{
return string("<td align=\"") + align + "\">";
}
static string table_row_begin(const string& align = string("left"))
{
return string("\n<tr>") + cell_begin(align);
}
template <typename T>
static string print_table_row_dims(const string& name, const T& shape)
{
return table_row_begin() + font_small_begin + name + vector_to_string(shape) + font_end +
table_row_end;
}
template <typename T>
static string print_table_row_value(const string& name, T val)
{
stringstream result;
result << table_row_begin() << font_small_begin << name << ":" << val << font_end
<< table_row_end;
return result.str();
}
void print_node_parameters(ostringstream& writer, const shared_ptr<Node>& node)
{
switch (get_typeid(node->description()))
{
case OP_TYPEID::BatchNormTrainingBackprop:
{
const shared_ptr<op::BatchNormTrainingBackprop> batch_norm =
static_pointer_cast<op::BatchNormTrainingBackprop>(node);
writer << print_table_row_value("EPS", batch_norm->get_eps_value());
break;
}
case OP_TYPEID::BatchNormInference:
{
const shared_ptr<op::BatchNormInference> batch_norm =
static_pointer_cast<op::BatchNormInference>(node);
writer << print_table_row_value("EPS", batch_norm->get_eps_value());
break;
}
case OP_TYPEID::BatchNormTraining:
{
const shared_ptr<op::BatchNormTraining> batch_norm =
static_pointer_cast<op::BatchNormTraining>(node);
writer << print_table_row_value("EPS", batch_norm->get_eps_value());
break;
}
case OP_TYPEID::GetOutputElement:
{
const shared_ptr<op::GetOutputElement> elem =
static_pointer_cast<op::GetOutputElement>(node);
writer << print_table_row_value("element", elem->get_n());
break;
}
case OP_TYPEID::MaxPool:
{
const shared_ptr<op::MaxPool> max_pool = static_pointer_cast<op::MaxPool>(node);
writer << print_table_row_dims("win_shape", max_pool->get_window_shape())
<< print_table_row_dims("win_strides", max_pool->get_window_movement_strides())
<< print_table_row_dims("pad_above", max_pool->get_padding_above())
<< print_table_row_dims("pad_below", max_pool->get_padding_below());
break;
}
case OP_TYPEID::MaxPoolBackprop:
{
const shared_ptr<op::MaxPoolBackprop> max_pool_b =
static_pointer_cast<op::MaxPoolBackprop>(node);
writer << print_table_row_dims("win_shape", max_pool_b->get_window_shape())
<< print_table_row_dims("win_strides", max_pool_b->get_window_movement_strides())
<< print_table_row_dims("pad_above", max_pool_b->get_padding_above())
<< print_table_row_dims("pad_below", max_pool_b->get_padding_below());
break;
}
case OP_TYPEID::AvgPool:
{
const shared_ptr<op::AvgPool> avg_pool = static_pointer_cast<op::AvgPool>(node);
writer << print_table_row_dims("win_shape", avg_pool->get_window_shape())
<< print_table_row_dims("win_strides", avg_pool->get_window_movement_strides())
<< print_table_row_dims("pad_above", avg_pool->get_padding_above())
<< print_table_row_dims("pad_below", avg_pool->get_padding_below())
<< print_table_row_value("pad_included",
avg_pool->get_include_padding_in_avg_computation());
break;
}
case OP_TYPEID::AvgPoolBackprop:
{
const shared_ptr<op::AvgPoolBackprop> avg_pool_b =
static_pointer_cast<op::AvgPoolBackprop>(node);
writer << print_table_row_dims("win_shape", avg_pool_b->get_window_shape())
<< print_table_row_dims("win_strides", avg_pool_b->get_window_movement_strides())
<< print_table_row_dims("pad_above", avg_pool_b->get_padding_above())
<< print_table_row_dims("pad_below", avg_pool_b->get_padding_below())
<< print_table_row_value("pad_included",
avg_pool_b->get_include_padding_in_avg_computation());
break;
}
case OP_TYPEID::Broadcast:
{
const shared_ptr<op::Broadcast> broadcast = static_pointer_cast<op::Broadcast>(node);
writer << print_table_row_dims("broadcast_axis", broadcast->get_broadcast_axes());
break;
}
case OP_TYPEID::Max:
case OP_TYPEID::Min:
case OP_TYPEID::Product:
case OP_TYPEID::Sum:
{
const shared_ptr<op::util::ArithmeticReduction> arith_op =
static_pointer_cast<op::util::ArithmeticReduction>(node);
writer << print_table_row_dims("reduction_axis", arith_op->get_reduction_axes());
break;
}
case OP_TYPEID::All:
case OP_TYPEID::Any:
{
const shared_ptr<op::util::LogicalReduction> logical_op =
static_pointer_cast<op::util::LogicalReduction>(node);
writer << print_table_row_dims("reduction_axis", logical_op->get_reduction_axes());
break;
}
case OP_TYPEID::ArgMin:
case OP_TYPEID::ArgMax:
{
const shared_ptr<op::util::IndexReduction> arg_op =
static_pointer_cast<op::util::IndexReduction>(node);
writer << print_table_row_value("reduction_axis", arg_op->get_reduction_axis())
<< table_row_begin() << font_small_begin
<< "idx_elem_type:" << arg_op->get_element_type() << font_end << table_row_end;
break;
}
case OP_TYPEID::LRN:
{
const shared_ptr<op::LRN> lrn_op = static_pointer_cast<op::LRN>(node);
writer << print_table_row_value("nsize", lrn_op->get_nsize())
<< print_table_row_value("bias", lrn_op->get_bias())
<< print_table_row_value("alpha", lrn_op->get_alpha())
<< print_table_row_value("beta", lrn_op->get_beta());
break;
}
case OP_TYPEID::OneHot:
{
const shared_ptr<op::OneHot> one_hot_op = static_pointer_cast<op::OneHot>(node);
writer << print_table_row_value("one_hot_axis", one_hot_op->get_one_hot_axis());
break;
}
case OP_TYPEID::Dot:
{
const shared_ptr<op::Dot> dot_op = static_pointer_cast<op::Dot>(node);
writer << print_table_row_value("reduction_axes_count", dot_op->get_reduction_axes_count());
break;
}
case OP_TYPEID::Constant:
{
size_t val_id = 0;
const shared_ptr<op::Constant> constant_op = static_pointer_cast<op::Constant>(node);
const vector<string>& values = constant_op->get_value_strings();
// let's print no more than 3 items
for (auto it = values.cbegin(); (it != values.cend()) && (val_id < 3); ++it)
{
writer << print_table_row_value("value[" + to_string(val_id) + "]", *it);
++val_id;
}
break;
}
case OP_TYPEID::Reshape:
{
const shared_ptr<op::Reshape> op_reshape = static_pointer_cast<op::Reshape>(node);
writer << print_table_row_dims("broadcast_axes", op_reshape->get_input_order())
<< print_table_row_value("transpose", op_reshape->get_is_transpose());
break;
}
case OP_TYPEID::Concat:
{
const shared_ptr<op::Concat> concat_op = static_pointer_cast<op::Concat>(node);
writer << print_table_row_value("concat_axis", concat_op->get_concatenation_axis());
break;
}
case OP_TYPEID::Reduce:
{
const shared_ptr<op::Reduce> red_op = static_pointer_cast<op::Reduce>(node);
const AxisSet& axis = red_op->get_reduction_axes();
writer << print_table_row_dims("reduction_axis", red_op->get_reduction_axes())
<< print_table_row_value("Function:TBD", 0);
break;
}
case OP_TYPEID::ReduceWindow:
{
const shared_ptr<op::ReduceWindow> red_win_op = static_pointer_cast<op::ReduceWindow>(node);
writer << print_table_row_dims("window_shape", red_win_op->get_window_shape())
<< print_table_row_dims("window_stride", red_win_op->get_window_movement_strides())
<< print_table_row_value("Function:TBD", 0);
break;
}
case OP_TYPEID::Pad:
{
const shared_ptr<op::Pad> pad = static_pointer_cast<op::Pad>(node);
writer << print_table_row_dims("pad_above", pad->get_padding_above())
<< print_table_row_dims("pad_below", pad->get_padding_below())
<< print_table_row_dims("pad_interior", pad->get_padding_interior());
break;
}
case OP_TYPEID::Slice:
{
const shared_ptr<op::Slice> elem = static_pointer_cast<op::Slice>(node);
writer << print_table_row_dims("upper_bounds", elem->get_upper_bounds())
<< print_table_row_dims("lower_bounds", elem->get_lower_bounds())
<< print_table_row_dims("strides", elem->get_strides());
break;
}
case OP_TYPEID::Convolution:
{
const shared_ptr<op::Convolution> conv_op = static_pointer_cast<op::Convolution>(node);
writer << print_table_row_dims("win_stride", conv_op->get_window_movement_strides())
<< print_table_row_dims("win_dilation", conv_op->get_window_dilation_strides())
<< print_table_row_dims("data_dilation", conv_op->get_data_dilation_strides())
<< print_table_row_dims("pad_above", conv_op->get_padding_above())
<< print_table_row_dims("pad_below", conv_op->get_padding_below());
break;
}
case OP_TYPEID::ConvolutionBackpropFilters:
{
const shared_ptr<op::ConvolutionBackpropFilters> conv_op_filt =
static_pointer_cast<op::ConvolutionBackpropFilters>(node);
writer << print_table_row_dims("filters_shape", conv_op_filt->get_filters_shape())
<< print_table_row_dims("window_movement_strides_forward",
conv_op_filt->get_window_movement_strides_forward())
<< print_table_row_dims("window_dilation_strides_forward",
conv_op_filt->get_window_dilation_strides_forward())
<< print_table_row_dims("data_dilation_strides_forward",
conv_op_filt->get_data_dilation_strides_forward())
<< print_table_row_dims("pad_above_forward",
conv_op_filt->get_padding_above_forward())
<< print_table_row_dims("pad_below_forward",
conv_op_filt->get_padding_below_forward())
<< print_table_row_dims("window_movement_strides_backward",
conv_op_filt->get_window_movement_strides_backward())
<< print_table_row_dims("window_dilation_strides_backward",
conv_op_filt->get_window_dilation_strides_backward())
<< print_table_row_dims("data_dilation_strides_backward",
conv_op_filt->get_data_dilation_strides_backward())
<< print_table_row_dims("padding_above_backward",
conv_op_filt->get_padding_above_backward())
<< print_table_row_dims("padding_below_backward",
conv_op_filt->get_padding_below_backward());
break;
}
case OP_TYPEID::ConvolutionBackpropData:
{
const shared_ptr<op::ConvolutionBackpropData> conv_op_data =
static_pointer_cast<op::ConvolutionBackpropData>(node);
writer << print_table_row_dims("data_batch_shape", conv_op_data->get_data_batch_shape())
<< print_table_row_dims("window_movement_strides_forward",
conv_op_data->get_window_movement_strides_forward())
<< print_table_row_dims("window_dilation_strides_forward",
conv_op_data->get_window_dilation_strides_forward())
<< print_table_row_dims("data_dilation_strides_forward",
conv_op_data->get_data_dilation_strides_forward())
<< print_table_row_dims("pad_above_forward",
conv_op_data->get_padding_above_forward())
<< print_table_row_dims("pad_below_forward",
conv_op_data->get_padding_below_forward())
<< print_table_row_dims("window_movement_strides_backward",
conv_op_data->get_window_movement_strides_backward())
<< print_table_row_dims("window_dilation_strides_backward",
conv_op_data->get_window_dilation_strides_backward())
<< print_table_row_dims("data_dilation_strides_backward",
conv_op_data->get_data_dilation_strides_backward())
<< print_table_row_dims("padding_above_backward",
conv_op_data->get_padding_above_backward())
<< print_table_row_dims("padding_below_backward",
conv_op_data->get_padding_below_backward());
break;
}
case OP_TYPEID::UNDEFINED_OP:
default:
{
; // Some operations are not defined in ngraph/op/op_tbl.hpp
}
}
}
void print_node(ostringstream& writer, const shared_ptr<Node>& node)
{
writer << node->get_name() << " [";
if (node->is_parameter())
{
writer << "shape=box color=blue ";
}
else if (node->is_output())
{
writer << "shape=box style=filled fillcolor=pink ";
}
else
{
writer << "shape=ellipse color=black";
}
// Print text inside figure using HTML layout
writer << " label=<" << table_begin;
if (!node->get_inputs().empty())
{
size_t arg_idx = 0;
for (const descriptor::Input& op_input : node->get_inputs())
{
writer << table_row_begin() << font_small_begin
<< op_input.get_element_type().c_type_string() << " input" << arg_idx
<< vector_to_string(op_input.get_shape()) << font_end << table_row_end;
++arg_idx;
}
}
if (!node->get_outputs().empty())
{
size_t arg_idx = 0;
for (const descriptor::Output& op_output : node->get_outputs())
{
writer << table_row_begin() << font_small_begin
<< op_output.get_element_type().c_type_string() << " output" << arg_idx
<< vector_to_string(op_output.get_shape()) << font_end << table_row_end;
++arg_idx;
}
}
writer << table_row_begin("center") << node->get_name() << table_row_end;
print_node_parameters(writer, node);
writer << table_end;
writer << " >];\n";
}
void runtime::intelgpu::visualize_tree(const shared_ptr<Function>& func,
const string& file_prefix,
const string& file_suffix)
{
map<string, size_t> operations;
ostringstream writer;
// Begin of the main graph
writer << "digraph ngraph\n{\nsplines=\"line\";\n\n";
for (const shared_ptr<Node> op : func->get_ordered_ops())
{
print_node(writer, op);
for (const descriptor::Input& op_input : op->get_inputs())
{
writer << op_input.get_output().get_node()->get_name() << " -> " << op->get_name()
<< ";\n";
}
// collect summary statistic for operations used in the graph
const string op_name = op->get_name().substr(0, op->get_name().find_first_of("_"));
auto it = operations.find(op_name);
if (it == operations.end())
{
it = operations.emplace(op_name, 0).first;
}
++(it->second);
}
// print summary with operations used
writer << "\nsubgraph clusterFooter\n{\nmargin=0\nstyle=\"invis\"\nLEGEND ["
<< "shape=box style=filled fillcolor=gray margin=0 label=<" << table_begin
<< table_row_begin("center") << "Operations summary" << table_row_end;
size_t total_op_count = 0;
for (const auto& it : operations)
{
writer << table_row_begin() << font_small_begin << it.first << ":" << font_end << cell_end
<< cell_begin() << font_small_begin << it.second << font_end << table_row_end;
total_op_count += it.second;
}
writer << table_row_begin() << "Total:" << cell_end << cell_begin() << total_op_count
<< table_row_end << table_end << "\n>];\n}\n";
// End of the main graph
writer << "}\n";
ofstream out_file(file_prefix + func->get_name() + file_suffix + ".dot");
if (out_file)
{
out_file << writer.str();
out_file.close();
}
}
| 38.913386 | 100 | 0.622875 | [
"shape",
"vector"
] |
c2b2c4db17e61f29293acacaf1933f6e63487fb6 | 2,251 | cpp | C++ | lib/tNamed.cpp | B1Z0N/KPI-geometrylib | a83b4394f9c150c131f6533d8cd8c39886684886 | [
"MIT"
] | 2 | 2019-04-28T16:38:54.000Z | 2019-12-27T20:09:43.000Z | lib/tNamed.cpp | B1Z0N/KPI-geometrylib | a83b4394f9c150c131f6533d8cd8c39886684886 | [
"MIT"
] | null | null | null | lib/tNamed.cpp | B1Z0N/KPI-geometrylib | a83b4394f9c150c131f6533d8cd8c39886684886 | [
"MIT"
] | null | null | null | #include "../include/geometry.hpp"
void NormAngle(double &phi)
{
phi -= ceil(phi / (2 * Pi)) * 2 * Pi;
}
tNamed::tNamed(char const *NewName)
{
char const *N = NewName;
fNameLength = 0;
while (*N != '\0')
{
fNameLength++;
N++;
}
fName = new char[fNameLength + 1];
for (int j = 0; j <= fNameLength; j++)
fName[j] = NewName[j];
}
tNamed::tNamed(const tNamed &x)
{ // copying constructor
if ((fName = (char *)malloc((x.fNameLength + 1) * sizeof(char))) == NULL)
{
cerr << "No memory for " << x.fNameLength + 1 << "symbols to copy " << x.fName << "." << endl;
}
else
{
fNameLength = x.fNameLength;
for (unsigned long j = 0; j <= fNameLength; j++)
fName[j] = x.fName[j];
}
}
tNamed::~tNamed()
{
fNameLength = 0;
}
const char *tNamed::Name() const
{
return fName;
}
char *tNamed::Name()
{
return fName;
}
int tNamed::NameLength() const
{
return fNameLength;
}
tNamed &tNamed::operator=(const tNamed &x)
{
if (fName)
delete fName;
if ((fName = (char *)malloc((x.fNameLength + 1) * sizeof(char))) == NULL)
{
cerr << "No memory for " << x.fNameLength + 1 << "symbols to copy " << x.fName << "." << endl;
}
else
{
fNameLength = x.fNameLength;
for (unsigned long j = 0; j <= fNameLength; j++)
fName[j] = x.fName[j];
}
return *this;
}
char sign(double x)
{
if (x >= 0)
return '+';
else
return '-';
}
// TODO3: make variadic templates solution
double Deter2(double a, double b, double c, double d)
{
return (a * d - c * b);
}
double Deter3(double a, double b, double c, double d, double e, double f, double g,
double h, double i)
{
return (a * Deter2(e, f, h, i) - b * Deter2(d, f, g, i) + c * Deter2(d, e, g, h));
}
double Deter4(double a, double b, double c, double d, double e,
double f, double g, double h, double i, double j, double k,
double l, double m, double n, double o, double p)
{
return (a * Deter3(f, g, h, j, k, l, n, o, p) - b * Deter3(e, g, h, i, k, l, m, o, p) + c * Deter3(e, f, h, i, j, l, m, n, p) - d * Deter3(e, f, g, i, j, k, m, n, o));
} | 21.854369 | 171 | 0.5251 | [
"geometry"
] |
c2b859e203f5d391d5d9b7224d54be87a9ddcc32 | 34,179 | cpp | C++ | third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2013 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 "core/css/resolver/AnimatedStyleBuilder.h"
#include "core/animation/animatable/AnimatableClipPathOperation.h"
#include "core/animation/animatable/AnimatableColor.h"
#include "core/animation/animatable/AnimatableDouble.h"
#include "core/animation/animatable/AnimatableDoubleAndBool.h"
#include "core/animation/animatable/AnimatableFilterOperations.h"
#include "core/animation/animatable/AnimatableImage.h"
#include "core/animation/animatable/AnimatableLength.h"
#include "core/animation/animatable/AnimatableLengthBox.h"
#include "core/animation/animatable/AnimatableLengthBoxAndBool.h"
#include "core/animation/animatable/AnimatableLengthPoint.h"
#include "core/animation/animatable/AnimatableLengthPoint3D.h"
#include "core/animation/animatable/AnimatableLengthSize.h"
#include "core/animation/animatable/AnimatablePath.h"
#include "core/animation/animatable/AnimatableRepeatable.h"
#include "core/animation/animatable/AnimatableSVGPaint.h"
#include "core/animation/animatable/AnimatableShadow.h"
#include "core/animation/animatable/AnimatableShapeValue.h"
#include "core/animation/animatable/AnimatableStrokeDasharrayList.h"
#include "core/animation/animatable/AnimatableTransform.h"
#include "core/animation/animatable/AnimatableUnknown.h"
#include "core/animation/animatable/AnimatableValue.h"
#include "core/animation/animatable/AnimatableVisibility.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/css/CSSPropertyMetadata.h"
#include "core/css/resolver/StyleBuilder.h"
#include "core/css/resolver/StyleResolverState.h"
#include "core/style/ComputedStyle.h"
#include "wtf/MathExtras.h"
#include <type_traits>
namespace blink {
namespace {
Length animatableValueToLengthWithZoom(const AnimatableValue* value,
float zoom,
ValueRange range = ValueRangeAll) {
if (value->isLength())
return toAnimatableLength(value)->getLength(zoom, range);
ASSERT(toAnimatableUnknown(value)->toCSSValueID() == CSSValueAuto);
return Length(Auto);
}
Length animatableValueToLength(const AnimatableValue* value,
const StyleResolverState& state,
ValueRange range = ValueRangeAll) {
return animatableValueToLengthWithZoom(value, state.style()->effectiveZoom(),
range);
}
UnzoomedLength animatableValueToUnzoomedLength(
const AnimatableValue* value,
const StyleResolverState&,
ValueRange range = ValueRangeAll) {
return UnzoomedLength(animatableValueToLengthWithZoom(value, 1, range));
}
BorderImageLength animatableValueToBorderImageLength(
const AnimatableValue* value,
const StyleResolverState& state) {
if (value->isLength())
return BorderImageLength(toAnimatableLength(value)->getLength(
state.style()->effectiveZoom(), ValueRangeNonNegative));
if (value->isDouble())
return BorderImageLength(
clampTo<double>(toAnimatableDouble(value)->toDouble(), 0));
ASSERT(toAnimatableUnknown(value)->toCSSValueID() == CSSValueAuto);
return Length(Auto);
}
template <typename T>
T animatableValueClampTo(const AnimatableValue* value,
T min = defaultMinimumForClamp<T>(),
T max = defaultMaximumForClamp<T>()) {
static_assert(std::is_integral<T>::value,
"should use integral type T when rounding values");
return clampTo<T>(
roundForImpreciseConversion<T>(toAnimatableDouble(value)->toDouble()),
min, max);
}
template <typename T>
T animatableLineWidthClamp(const AnimatableValue* value) {
double doubleValue = toAnimatableDouble(value)->toDouble();
// This matches StyleBuilderConverter::convertLineWidth().
return (doubleValue > 0 && doubleValue < 1)
? 1
: animatableValueClampTo<T>(value);
}
LengthBox animatableValueToLengthBox(const AnimatableValue* value,
const StyleResolverState& state,
ValueRange range = ValueRangeAll) {
const AnimatableLengthBox* animatableLengthBox = toAnimatableLengthBox(value);
return LengthBox(
animatableValueToLength(animatableLengthBox->top(), state, range),
animatableValueToLength(animatableLengthBox->right(), state, range),
animatableValueToLength(animatableLengthBox->bottom(), state, range),
animatableValueToLength(animatableLengthBox->left(), state, range));
}
BorderImageLengthBox animatableValueToBorderImageLengthBox(
const AnimatableValue* value,
const StyleResolverState& state) {
const AnimatableLengthBox* animatableLengthBox = toAnimatableLengthBox(value);
return BorderImageLengthBox(
animatableValueToBorderImageLength(animatableLengthBox->top(), state),
animatableValueToBorderImageLength(animatableLengthBox->right(), state),
animatableValueToBorderImageLength(animatableLengthBox->bottom(), state),
animatableValueToBorderImageLength(animatableLengthBox->left(), state));
}
LengthPoint animatableValueToLengthPoint(const AnimatableValue* value,
const StyleResolverState& state,
ValueRange range = ValueRangeAll) {
const AnimatableLengthPoint* animatableLengthPoint =
toAnimatableLengthPoint(value);
return LengthPoint(
animatableValueToLength(animatableLengthPoint->x(), state, range),
animatableValueToLength(animatableLengthPoint->y(), state, range));
}
TransformOrigin animatableValueToTransformOrigin(
const AnimatableValue* value,
const StyleResolverState& state,
ValueRange range = ValueRangeAll) {
const AnimatableLengthPoint3D* animatableLengthPoint3D =
toAnimatableLengthPoint3D(value);
return TransformOrigin(
animatableValueToLength(animatableLengthPoint3D->x(), state),
animatableValueToLength(animatableLengthPoint3D->y(), state),
clampTo<float>(
toAnimatableDouble(animatableLengthPoint3D->z())->toDouble()));
}
LengthSize animatableValueToLengthSize(const AnimatableValue* value,
const StyleResolverState& state,
ValueRange range) {
const AnimatableLengthSize* animatableLengthSize =
toAnimatableLengthSize(value);
return LengthSize(
animatableValueToLength(animatableLengthSize->width(), state, range),
animatableValueToLength(animatableLengthSize->height(), state, range));
}
void setFillSize(FillLayer* fillLayer,
const AnimatableValue* value,
StyleResolverState& state) {
if (value->isLengthSize())
fillLayer->setSize(FillSize(
SizeLength,
animatableValueToLengthSize(value, state, ValueRangeNonNegative)));
else
CSSToStyleMap::mapFillSize(state, fillLayer,
*toAnimatableUnknown(value)->toCSSValue());
}
template <CSSPropertyID property>
void setOnFillLayers(FillLayer& fillLayers,
const AnimatableValue* value,
StyleResolverState& state) {
const Vector<RefPtr<AnimatableValue>>& values =
toAnimatableRepeatable(value)->values();
ASSERT(!values.isEmpty());
FillLayer* fillLayer = &fillLayers;
FillLayer* prev = 0;
for (size_t i = 0; i < values.size(); ++i) {
if (!fillLayer)
fillLayer = prev->ensureNext();
const AnimatableValue* layerValue = values[i].get();
switch (property) {
case CSSPropertyBackgroundImage:
case CSSPropertyWebkitMaskImage:
if (layerValue->isImage()) {
fillLayer->setImage(state.styleImage(
property, *toAnimatableImage(layerValue)->toCSSValue()));
} else {
ASSERT(toAnimatableUnknown(layerValue)->toCSSValueID() ==
CSSValueNone);
fillLayer->setImage(nullptr);
}
break;
case CSSPropertyBackgroundPositionX:
case CSSPropertyWebkitMaskPositionX:
fillLayer->setXPosition(animatableValueToLength(layerValue, state));
break;
case CSSPropertyBackgroundPositionY:
case CSSPropertyWebkitMaskPositionY:
fillLayer->setYPosition(animatableValueToLength(layerValue, state));
break;
case CSSPropertyBackgroundSize:
case CSSPropertyWebkitMaskSize:
setFillSize(fillLayer, layerValue, state);
break;
default:
ASSERT_NOT_REACHED();
}
prev = fillLayer;
fillLayer = fillLayer->next();
}
while (fillLayer) {
switch (property) {
case CSSPropertyBackgroundImage:
case CSSPropertyWebkitMaskImage:
fillLayer->clearImage();
break;
case CSSPropertyBackgroundPositionX:
case CSSPropertyWebkitMaskPositionX:
fillLayer->clearXPosition();
break;
case CSSPropertyBackgroundPositionY:
case CSSPropertyWebkitMaskPositionY:
fillLayer->clearYPosition();
break;
case CSSPropertyBackgroundSize:
case CSSPropertyWebkitMaskSize:
fillLayer->clearSize();
break;
default:
ASSERT_NOT_REACHED();
}
fillLayer = fillLayer->next();
}
}
FontStretch animatableValueToFontStretch(const AnimatableValue* value) {
ASSERT(FontStretchUltraCondensed == 1 && FontStretchUltraExpanded == 9);
unsigned index = round(toAnimatableDouble(value)->toDouble()) - 1;
static const FontStretch stretchValues[] = {
FontStretchUltraCondensed, FontStretchExtraCondensed,
FontStretchCondensed, FontStretchSemiCondensed,
FontStretchNormal, FontStretchSemiExpanded,
FontStretchExpanded, FontStretchExtraExpanded,
FontStretchUltraExpanded};
index = clampTo<unsigned>(index, 0, WTF_ARRAY_LENGTH(stretchValues) - 1);
return stretchValues[index];
}
FontWeight animatableValueToFontWeight(const AnimatableValue* value) {
int index = round(toAnimatableDouble(value)->toDouble() / 100) - 1;
static const FontWeight weights[] = {
FontWeight100, FontWeight200, FontWeight300, FontWeight400, FontWeight500,
FontWeight600, FontWeight700, FontWeight800, FontWeight900};
index = clampTo<int>(index, 0, WTF_ARRAY_LENGTH(weights) - 1);
return weights[index];
}
FontDescription::Size animatableValueToFontSize(const AnimatableValue* value) {
float size = clampTo<float>(toAnimatableDouble(value)->toDouble(), 0);
return FontDescription::Size(0, size, true);
}
TransformOperation* animatableValueToTransformOperation(
const AnimatableValue* value,
TransformOperation::OperationType type) {
const TransformOperations& transformList =
toAnimatableTransform(value)->transformOperations();
ASSERT(transformList.size() == 1);
ASSERT(transformList.operations()[0].get()->type() == type);
return transformList.operations()[0].get();
}
} // namespace
// FIXME: Generate this function.
void AnimatedStyleBuilder::applyProperty(CSSPropertyID property,
StyleResolverState& state,
const AnimatableValue* value) {
ASSERT(CSSPropertyMetadata::isInterpolableProperty(property));
if (value->isUnknown()) {
StyleBuilder::applyProperty(property, state,
*toAnimatableUnknown(value)->toCSSValue());
return;
}
ComputedStyle* style = state.style();
switch (property) {
case CSSPropertyBackgroundColor:
style->setBackgroundColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkBackgroundColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyBackgroundImage:
setOnFillLayers<CSSPropertyBackgroundImage>(
style->accessBackgroundLayers(), value, state);
return;
case CSSPropertyBackgroundPositionX:
setOnFillLayers<CSSPropertyBackgroundPositionX>(
style->accessBackgroundLayers(), value, state);
return;
case CSSPropertyBackgroundPositionY:
setOnFillLayers<CSSPropertyBackgroundPositionY>(
style->accessBackgroundLayers(), value, state);
return;
case CSSPropertyBackgroundSize:
setOnFillLayers<CSSPropertyBackgroundSize>(
style->accessBackgroundLayers(), value, state);
return;
case CSSPropertyBaselineShift:
style->accessSVGStyle().setBaselineShift(BS_LENGTH);
style->accessSVGStyle().setBaselineShiftValue(
animatableValueToLength(value, state));
return;
case CSSPropertyBorderBottomColor:
style->setBorderBottomColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkBorderBottomColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyBorderBottomLeftRadius:
style->setBorderBottomLeftRadius(
animatableValueToLengthSize(value, state, ValueRangeNonNegative));
return;
case CSSPropertyBorderBottomRightRadius:
style->setBorderBottomRightRadius(
animatableValueToLengthSize(value, state, ValueRangeNonNegative));
return;
case CSSPropertyBorderBottomWidth:
style->setBorderBottomWidth(animatableLineWidthClamp<unsigned>(value));
return;
case CSSPropertyBorderImageOutset:
style->setBorderImageOutset(
animatableValueToBorderImageLengthBox(value, state));
return;
case CSSPropertyBorderImageSlice:
style->setBorderImageSlices(
animatableValueToLengthBox(toAnimatableLengthBoxAndBool(value)->box(),
state, ValueRangeNonNegative));
style->setBorderImageSlicesFill(
toAnimatableLengthBoxAndBool(value)->flag());
return;
case CSSPropertyBorderImageSource:
style->setBorderImageSource(
state.styleImage(property, *toAnimatableImage(value)->toCSSValue()));
return;
case CSSPropertyBorderImageWidth:
style->setBorderImageWidth(
animatableValueToBorderImageLengthBox(value, state));
return;
case CSSPropertyBorderLeftColor:
style->setBorderLeftColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkBorderLeftColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyBorderLeftWidth:
style->setBorderLeftWidth(animatableLineWidthClamp<unsigned>(value));
return;
case CSSPropertyBorderRightColor:
style->setBorderRightColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkBorderRightColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyBorderRightWidth:
style->setBorderRightWidth(animatableLineWidthClamp<unsigned>(value));
return;
case CSSPropertyBorderTopColor:
style->setBorderTopColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkBorderTopColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyBorderTopLeftRadius:
style->setBorderTopLeftRadius(
animatableValueToLengthSize(value, state, ValueRangeNonNegative));
return;
case CSSPropertyBorderTopRightRadius:
style->setBorderTopRightRadius(
animatableValueToLengthSize(value, state, ValueRangeNonNegative));
return;
case CSSPropertyBorderTopWidth:
style->setBorderTopWidth(animatableLineWidthClamp<unsigned>(value));
return;
case CSSPropertyBottom:
style->setBottom(animatableValueToLength(value, state));
return;
case CSSPropertyBoxShadow:
style->setBoxShadow(toAnimatableShadow(value)->getShadowList());
return;
case CSSPropertyClip:
style->setClip(animatableValueToLengthBox(value, state));
return;
case CSSPropertyColor:
style->setColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkColor(toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyFillOpacity:
style->setFillOpacity(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
return;
case CSSPropertyFill: {
const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
style->accessSVGStyle().setFillPaint(svgPaint->paintType(),
svgPaint->getColor(),
svgPaint->uri(), true, false);
style->accessSVGStyle().setFillPaint(
svgPaint->visitedLinkPaintType(), svgPaint->visitedLinkColor(),
svgPaint->visitedLinkURI(), false, true);
}
return;
case CSSPropertyFlexGrow:
style->setFlexGrow(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0));
return;
case CSSPropertyFlexShrink:
style->setFlexShrink(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0));
return;
case CSSPropertyFlexBasis:
style->setFlexBasis(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyFloodColor:
style->setFloodColor(toAnimatableColor(value)->getColor());
return;
case CSSPropertyFloodOpacity:
style->setFloodOpacity(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
return;
case CSSPropertyFontSize:
state.fontBuilder().setSize(animatableValueToFontSize(value));
return;
case CSSPropertyFontSizeAdjust:
state.fontBuilder().setSizeAdjust(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0));
return;
case CSSPropertyFontStretch:
state.fontBuilder().setStretch(animatableValueToFontStretch(value));
return;
case CSSPropertyFontWeight:
state.fontBuilder().setWeight(animatableValueToFontWeight(value));
return;
case CSSPropertyHeight:
style->setHeight(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyLeft:
style->setLeft(animatableValueToLength(value, state));
return;
case CSSPropertyLightingColor:
style->setLightingColor(toAnimatableColor(value)->getColor());
return;
case CSSPropertyLineHeight:
if (value->isLength())
style->setLineHeight(
animatableValueToLength(value, state, ValueRangeNonNegative));
else
style->setLineHeight(Length(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0), Percent));
return;
case CSSPropertyListStyleImage:
style->setListStyleImage(
state.styleImage(property, *toAnimatableImage(value)->toCSSValue()));
return;
case CSSPropertyLetterSpacing:
style->setLetterSpacing(
clampTo<float>(toAnimatableDouble(value)->toDouble()));
return;
case CSSPropertyMarginBottom:
style->setMarginBottom(animatableValueToLength(value, state));
return;
case CSSPropertyMarginLeft:
style->setMarginLeft(animatableValueToLength(value, state));
return;
case CSSPropertyMarginRight:
style->setMarginRight(animatableValueToLength(value, state));
return;
case CSSPropertyMarginTop:
style->setMarginTop(animatableValueToLength(value, state));
return;
case CSSPropertyMaxHeight:
style->setMaxHeight(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyMaxWidth:
style->setMaxWidth(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyMinHeight:
style->setMinHeight(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyMinWidth:
style->setMinWidth(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyObjectPosition:
style->setObjectPosition(animatableValueToLengthPoint(value, state));
return;
case CSSPropertyOpacity:
// Avoiding a value of 1 forces a layer to be created.
style->setOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0,
nextafterf(1, 0)));
return;
case CSSPropertyOrphans:
style->setOrphans(
clampTo<short>(round(toAnimatableDouble(value)->toDouble()), 1));
return;
case CSSPropertyOutlineColor:
style->setOutlineColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkOutlineColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyOutlineOffset:
style->setOutlineOffset(animatableValueClampTo<int>(value));
return;
case CSSPropertyOutlineWidth:
style->setOutlineWidth(animatableLineWidthClamp<unsigned short>(value));
return;
case CSSPropertyPaddingBottom:
style->setPaddingBottom(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyPaddingLeft:
style->setPaddingLeft(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyPaddingRight:
style->setPaddingRight(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyPaddingTop:
style->setPaddingTop(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyRight:
style->setRight(animatableValueToLength(value, state));
return;
case CSSPropertyStrokeWidth:
style->setStrokeWidth(
animatableValueToUnzoomedLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyStopColor:
style->setStopColor(toAnimatableColor(value)->getColor());
return;
case CSSPropertyStopOpacity:
style->setStopOpacity(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
return;
case CSSPropertyStrokeDasharray:
style->setStrokeDashArray(
toAnimatableStrokeDasharrayList(value)->toSVGDashArray(
style->effectiveZoom()));
return;
case CSSPropertyStrokeDashoffset:
style->setStrokeDashOffset(animatableValueToLength(value, state));
return;
case CSSPropertyStrokeMiterlimit:
style->setStrokeMiterLimit(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 1));
return;
case CSSPropertyStrokeOpacity:
style->setStrokeOpacity(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
return;
case CSSPropertyStroke: {
const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
style->accessSVGStyle().setStrokePaint(svgPaint->paintType(),
svgPaint->getColor(),
svgPaint->uri(), true, false);
style->accessSVGStyle().setStrokePaint(
svgPaint->visitedLinkPaintType(), svgPaint->visitedLinkColor(),
svgPaint->visitedLinkURI(), false, true);
}
return;
case CSSPropertyTextDecorationColor:
style->setTextDecorationColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkTextDecorationColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyTextIndent:
style->setTextIndent(animatableValueToLength(value, state));
return;
case CSSPropertyTextShadow:
style->setTextShadow(toAnimatableShadow(value)->getShadowList());
return;
case CSSPropertyTop:
style->setTop(animatableValueToLength(value, state));
return;
case CSSPropertyWebkitBorderHorizontalSpacing:
style->setHorizontalBorderSpacing(
animatableValueClampTo<unsigned short>(value));
return;
case CSSPropertyWebkitBorderVerticalSpacing:
style->setVerticalBorderSpacing(
animatableValueClampTo<unsigned short>(value));
return;
case CSSPropertyClipPath:
style->setClipPath(
toAnimatableClipPathOperation(value)->getClipPathOperation());
return;
case CSSPropertyColumnCount:
style->setColumnCount(clampTo<unsigned short>(
round(toAnimatableDouble(value)->toDouble()), 1));
return;
case CSSPropertyColumnGap:
style->setColumnGap(clampTo(toAnimatableDouble(value)->toDouble(), 0));
return;
case CSSPropertyColumnRuleColor:
style->setColumnRuleColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkColumnRuleColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyColumnWidth:
style->setColumnWidth(clampTo(toAnimatableDouble(value)->toDouble(),
std::numeric_limits<float>::epsilon()));
return;
case CSSPropertyColumnRuleWidth:
style->setColumnRuleWidth(
animatableLineWidthClamp<unsigned short>(value));
return;
case CSSPropertyFilter:
style->setFilter(toAnimatableFilterOperations(value)->operations());
return;
case CSSPropertyBackdropFilter:
style->setBackdropFilter(
toAnimatableFilterOperations(value)->operations());
return;
case CSSPropertyWebkitMaskBoxImageOutset:
style->setMaskBoxImageOutset(
animatableValueToBorderImageLengthBox(value, state));
return;
case CSSPropertyWebkitMaskBoxImageSlice:
style->setMaskBoxImageSlices(
animatableValueToLengthBox(toAnimatableLengthBoxAndBool(value)->box(),
state, ValueRangeNonNegative));
style->setMaskBoxImageSlicesFill(
toAnimatableLengthBoxAndBool(value)->flag());
return;
case CSSPropertyWebkitMaskBoxImageSource:
style->setMaskBoxImageSource(
state.styleImage(property, *toAnimatableImage(value)->toCSSValue()));
return;
case CSSPropertyWebkitMaskBoxImageWidth:
style->setMaskBoxImageWidth(
animatableValueToBorderImageLengthBox(value, state));
return;
case CSSPropertyWebkitMaskImage:
setOnFillLayers<CSSPropertyWebkitMaskImage>(style->accessMaskLayers(),
value, state);
return;
case CSSPropertyWebkitMaskPositionX:
setOnFillLayers<CSSPropertyWebkitMaskPositionX>(style->accessMaskLayers(),
value, state);
return;
case CSSPropertyWebkitMaskPositionY:
setOnFillLayers<CSSPropertyWebkitMaskPositionY>(style->accessMaskLayers(),
value, state);
return;
case CSSPropertyWebkitMaskSize:
setOnFillLayers<CSSPropertyWebkitMaskSize>(style->accessMaskLayers(),
value, state);
return;
case CSSPropertyPerspective:
style->setPerspective(
value->isDouble()
? clampTo<float>(toAnimatableDouble(value)->toDouble())
: 0);
return;
case CSSPropertyPerspectiveOrigin:
style->setPerspectiveOrigin(animatableValueToLengthPoint(value, state));
return;
case CSSPropertyShapeOutside:
style->setShapeOutside(toAnimatableShapeValue(value)->getShapeValue());
return;
case CSSPropertyShapeMargin:
style->setShapeMargin(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyShapeImageThreshold:
style->setShapeImageThreshold(
clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
return;
case CSSPropertyWebkitTextStrokeColor:
style->setTextStrokeColor(toAnimatableColor(value)->getColor());
style->setVisitedLinkTextStrokeColor(
toAnimatableColor(value)->visitedLinkColor());
return;
case CSSPropertyTransform: {
const TransformOperations& operations =
toAnimatableTransform(value)->transformOperations();
// FIXME: This normalization (handling of 'none') should be performed at
// input in AnimatableValueFactory.
if (operations.size() == 0) {
style->setTransform(TransformOperations(true));
return;
}
double sourceZoom = toAnimatableTransform(value)->zoom();
double destinationZoom = style->effectiveZoom();
style->setTransform(sourceZoom == destinationZoom
? operations
: operations.zoom(destinationZoom / sourceZoom));
return;
}
case CSSPropertyTranslate: {
TranslateTransformOperation* translate =
toTranslateTransformOperation(animatableValueToTransformOperation(
value, TransformOperation::Translate3D));
double sourceZoom = toAnimatableTransform(value)->zoom();
double destinationZoom = style->effectiveZoom();
style->setTranslate(
sourceZoom == destinationZoom
? translate
: translate->zoomTranslate(destinationZoom / sourceZoom));
return;
}
case CSSPropertyRotate: {
style->setRotate(
toRotateTransformOperation(animatableValueToTransformOperation(
value, TransformOperation::Rotate3D)));
return;
}
case CSSPropertyScale: {
style->setScale(
toScaleTransformOperation(animatableValueToTransformOperation(
value, TransformOperation::Scale3D)));
return;
}
case CSSPropertyTransformOrigin:
style->setTransformOrigin(animatableValueToTransformOrigin(value, state));
return;
case CSSPropertyOffsetAnchor:
style->setOffsetAnchor(animatableValueToLengthPoint(value, state));
return;
case CSSPropertyOffsetDistance:
style->setOffsetDistance(animatableValueToLength(value, state));
return;
case CSSPropertyOffsetPosition:
style->setOffsetPosition(animatableValueToLengthPoint(value, state));
return;
case CSSPropertyOffsetRotate:
case CSSPropertyOffsetRotation:
style->setOffsetRotation(StyleOffsetRotation(
toAnimatableDoubleAndBool(value)->toDouble(),
toAnimatableDoubleAndBool(value)->flag() ? OffsetRotationAuto
: OffsetRotationFixed));
return;
case CSSPropertyWebkitPerspectiveOriginX:
style->setPerspectiveOriginX(animatableValueToLength(value, state));
return;
case CSSPropertyWebkitPerspectiveOriginY:
style->setPerspectiveOriginY(animatableValueToLength(value, state));
return;
case CSSPropertyWebkitTransformOriginX:
style->setTransformOriginX(animatableValueToLength(value, state));
return;
case CSSPropertyWebkitTransformOriginY:
style->setTransformOriginY(animatableValueToLength(value, state));
return;
case CSSPropertyWebkitTransformOriginZ:
style->setTransformOriginZ(toAnimatableDouble(value)->toDouble());
return;
case CSSPropertyWidows:
style->setWidows(
clampTo<short>(round(toAnimatableDouble(value)->toDouble()), 1));
return;
case CSSPropertyWidth:
style->setWidth(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyWordSpacing:
style->setWordSpacing(
clampTo<float>(toAnimatableDouble(value)->toDouble()));
return;
case CSSPropertyVerticalAlign:
style->setVerticalAlignLength(animatableValueToLength(value, state));
return;
case CSSPropertyVisibility:
style->setVisibility(toAnimatableVisibility(value)->visibility());
return;
case CSSPropertyZIndex:
style->setZIndex(
clampTo<int>(round(toAnimatableDouble(value)->toDouble())));
return;
case CSSPropertyD:
style->setD(toAnimatablePath(value)->path());
return;
case CSSPropertyCx:
style->setCx(animatableValueToLength(value, state));
return;
case CSSPropertyCy:
style->setCy(animatableValueToLength(value, state));
return;
case CSSPropertyX:
style->setX(animatableValueToLength(value, state));
return;
case CSSPropertyY:
style->setY(animatableValueToLength(value, state));
return;
case CSSPropertyR:
style->setR(animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyRx:
style->setRx(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
case CSSPropertyRy:
style->setRy(
animatableValueToLength(value, state, ValueRangeNonNegative));
return;
default:
ASSERT_NOT_REACHED();
}
}
} // namespace blink
| 40.592637 | 80 | 0.696861 | [
"vector"
] |
c2c49967a2dbe0a25346df94a89c4d51be8efcea | 43,226 | cpp | C++ | gui/MainWindow.cpp | Heufneutje/MultiMC5 | 7d1dd2a32f95eacaaea7d808cd07faf99e425977 | [
"Apache-2.0"
] | 2 | 2016-03-29T07:43:32.000Z | 2019-05-31T14:38:04.000Z | gui/MainWindow.cpp | Heufneutje/MultiMC5 | 7d1dd2a32f95eacaaea7d808cd07faf99e425977 | [
"Apache-2.0"
] | null | null | null | gui/MainWindow.cpp | Heufneutje/MultiMC5 | 7d1dd2a32f95eacaaea7d808cd07faf99e425977 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2013-2014 MultiMC Contributors
*
* Authors: Andrew Okin
* Peterix
* Orochimarufan <orochimarufan.x3@gmail.com>
*
* 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 "MultiMC.h"
#include "BuildConfig.h"
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QMenu>
#include <QMessageBox>
#include <QInputDialog>
#include <QDesktopServices>
#include <QKeyEvent>
#include <QUrl>
#include <QDir>
#include <QFileInfo>
#include <QLabel>
#include <QToolButton>
#include <QWidgetAction>
#include <QProgressDialog>
#include <QShortcut>
#include "osutils.h"
#include "userutils.h"
#include "pathutils.h"
#include "gui/groupview/GroupView.h"
#include "gui/groupview/InstanceDelegate.h"
#include "gui/Platform.h"
#include "gui/widgets/LabeledToolButton.h"
#include "widgets/ServerStatus.h"
#include "gui/dialogs/NewInstanceDialog.h"
#include "gui/dialogs/ProgressDialog.h"
#include "gui/dialogs/AboutDialog.h"
#include "gui/dialogs/VersionSelectDialog.h"
#include "gui/dialogs/CustomMessageBox.h"
#include "gui/dialogs/LwjglSelectDialog.h"
#include "gui/dialogs/IconPickerDialog.h"
#include "gui/dialogs/CopyInstanceDialog.h"
#include "gui/dialogs/AccountSelectDialog.h"
#include "gui/dialogs/UpdateDialog.h"
#include "gui/dialogs/EditAccountDialog.h"
#include "gui/dialogs/NotificationDialog.h"
#include "gui/pages/global/MultiMCPage.h"
#include "gui/pages/global/ExternalToolsPage.h"
#include "gui/pages/global/AccountListPage.h"
#include "gui/pages/global/ProxyPage.h"
#include "gui/pages/global/JavaPage.h"
#include "gui/pages/global/MinecraftPage.h"
#include "gui/ConsoleWindow.h"
#include "pagedialog/PageDialog.h"
#include "logic/InstanceList.h"
#include "logic/minecraft/MinecraftVersionList.h"
#include "logic/LwjglVersionList.h"
#include "logic/icons/IconList.h"
#include "logic/java/JavaVersionList.h"
#include "logic/auth/flows/AuthenticateTask.h"
#include "logic/auth/flows/RefreshTask.h"
#include "logic/updater/DownloadUpdateTask.h"
#include "logic/news/NewsChecker.h"
#include "logic/status/StatusChecker.h"
#include "logic/net/URLConstants.h"
#include "logic/net/NetJob.h"
#include "logic/BaseInstance.h"
#include "logic/OneSixInstance.h"
#include "logic/InstanceFactory.h"
#include "logic/MinecraftProcess.h"
#include "logic/OneSixUpdate.h"
#include "logic/java/JavaUtils.h"
#include "logic/NagUtils.h"
#include "logic/SkinUtils.h"
#include "logic/LegacyInstance.h"
#include "logic/assets/AssetsUtils.h"
#include "logic/assets/AssetsMigrateTask.h"
#include <logic/updater/UpdateChecker.h>
#include <logic/updater/NotificationChecker.h>
#include <logic/tasks/ThreadTask.h>
#include "logic/tools/BaseProfiler.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
MultiMCPlatform::fixWM_CLASS(this);
ui->setupUi(this);
QString winTitle =
QString("MultiMC 5 - Version %1").arg(BuildConfig.printableVersionString());
if (!BuildConfig.BUILD_PLATFORM.isEmpty())
winTitle += " on " + BuildConfig.BUILD_PLATFORM;
setWindowTitle(winTitle);
// OSX magic.
setUnifiedTitleAndToolBarOnMac(true);
// Global shortcuts
{
// FIXME: This is kinda weird. and bad. We need some kind of managed shutdown.
auto q = new QShortcut(QKeySequence::Quit, this);
connect(q, SIGNAL(activated()), qApp, SLOT(quit()));
}
// The instance action toolbar customizations
{
// disabled until we have an instance selected
ui->instanceToolBar->setEnabled(false);
// the rename label is inside the rename tool button
renameButton = new LabeledToolButton();
renameButton->setText("Instance Name");
renameButton->setToolTip(ui->actionRenameInstance->toolTip());
connect(renameButton, SIGNAL(clicked(bool)), SLOT(on_actionRenameInstance_triggered()));
ui->instanceToolBar->insertWidget(ui->actionLaunchInstance, renameButton);
ui->instanceToolBar->insertSeparator(ui->actionLaunchInstance);
renameButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
}
// Add the news label to the news toolbar.
{
newsLabel = new QToolButton();
newsLabel->setIcon(QIcon::fromTheme("news"));
newsLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
newsLabel->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
ui->newsToolBar->insertWidget(ui->actionMoreNews, newsLabel);
QObject::connect(newsLabel, &QAbstractButton::clicked, this,
&MainWindow::newsButtonClicked);
QObject::connect(MMC->newsChecker().get(), &NewsChecker::newsLoaded, this,
&MainWindow::updateNewsLabel);
updateNewsLabel();
}
// Create the instance list widget
{
view = new GroupView(ui->centralWidget);
view->setSelectionMode(QAbstractItemView::SingleSelection);
// view->setCategoryDrawer(drawer);
// view->setCollapsibleBlocks(true);
// view->setViewMode(QListView::IconMode);
// view->setFlow(QListView::LeftToRight);
// view->setWordWrap(true);
// view->setMouseTracking(true);
// view->viewport()->setAttribute(Qt::WA_Hover);
auto delegate = new ListViewDelegate();
view->setItemDelegate(delegate);
// view->setSpacing(10);
// view->setUniformItemWidths(true);
// do not show ugly blue border on the mac
view->setAttribute(Qt::WA_MacShowFocusRect, false);
view->installEventFilter(this);
proxymodel = new InstanceProxyModel(this);
// proxymodel->setSortRole(KCategorizedSortFilterProxyModel::CategorySortRole);
// proxymodel->setFilterRole(KCategorizedSortFilterProxyModel::CategorySortRole);
// proxymodel->setDynamicSortFilter ( true );
// FIXME: instList should be global-ish, or at least not tied to the main window...
// maybe the application itself?
proxymodel->setSourceModel(MMC->instances().get());
proxymodel->sort(0);
view->setFrameShape(QFrame::NoFrame);
view->setModel(proxymodel);
view->setContextMenuPolicy(Qt::CustomContextMenu);
connect(view, SIGNAL(customContextMenuRequested(const QPoint &)), this,
SLOT(showInstanceContextMenu(const QPoint &)));
ui->horizontalLayout->addWidget(view);
}
// The cat background
{
bool cat_enable = MMC->settings()->get("TheCat").toBool();
ui->actionCAT->setChecked(cat_enable);
connect(ui->actionCAT, SIGNAL(toggled(bool)), SLOT(onCatToggled(bool)));
setCatBackground(cat_enable);
}
// start instance when double-clicked
connect(view, SIGNAL(doubleClicked(const QModelIndex &)), this,
SLOT(instanceActivated(const QModelIndex &)));
// track the selection -- update the instance toolbar
connect(view->selectionModel(),
SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this,
SLOT(instanceChanged(const QModelIndex &, const QModelIndex &)));
// track icon changes and update the toolbar!
connect(MMC->icons().get(), SIGNAL(iconUpdated(QString)), SLOT(iconUpdated(QString)));
// model reset -> selection is invalid. All the instance pointers are wrong.
// FIXME: stop using POINTERS everywhere
connect(MMC->instances().get(), SIGNAL(dataIsInvalid()), SLOT(selectionBad()));
m_statusLeft = new QLabel(tr("No instance selected"), this);
m_statusRight = new ServerStatus(this);
statusBar()->addPermanentWidget(m_statusLeft, 1);
statusBar()->addPermanentWidget(m_statusRight, 0);
// Add "manage accounts" button, right align
QWidget *spacer = new QWidget();
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->mainToolBar->addWidget(spacer);
accountMenu = new QMenu(this);
manageAccountsAction = new QAction(tr("Manage Accounts"), this);
manageAccountsAction->setCheckable(false);
connect(manageAccountsAction, SIGNAL(triggered(bool)), this,
SLOT(on_actionManageAccounts_triggered()));
repopulateAccountsMenu();
accountMenuButton = new QToolButton(this);
accountMenuButton->setText(tr("Accounts"));
accountMenuButton->setMenu(accountMenu);
accountMenuButton->setPopupMode(QToolButton::InstantPopup);
accountMenuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
accountMenuButton->setIcon(QIcon::fromTheme("noaccount"));
QWidgetAction *accountMenuButtonAction = new QWidgetAction(this);
accountMenuButtonAction->setDefaultWidget(accountMenuButton);
ui->mainToolBar->addAction(accountMenuButtonAction);
// set up global pages dialog
{
m_globalSettingsProvider = std::make_shared<GenericPageProvider>(tr("Settings"));
m_globalSettingsProvider->addPage<MultiMCPage>();
m_globalSettingsProvider->addPage<MinecraftPage>();
m_globalSettingsProvider->addPage<JavaPage>();
m_globalSettingsProvider->addPage<ProxyPage>();
m_globalSettingsProvider->addPage<ExternalToolsPage>();
m_globalSettingsProvider->addPage<AccountListPage>();
}
// Update the menu when the active account changes.
// Shouldn't have to use lambdas here like this, but if I don't, the compiler throws a fit.
// Template hell sucks...
connect(MMC->accounts().get(), &MojangAccountList::activeAccountChanged, [this]
{ activeAccountChanged(); });
connect(MMC->accounts().get(), &MojangAccountList::listChanged, [this]
{ repopulateAccountsMenu(); });
// Show initial account
activeAccountChanged();
auto accounts = MMC->accounts();
QList<CacheDownloadPtr> skin_dls;
for (int i = 0; i < accounts->count(); i++)
{
auto account = accounts->at(i);
if (account != nullptr)
{
for (auto profile : account->profiles())
{
auto meta = MMC->metacache()->resolveEntry("skins", profile.name + ".png");
auto action = CacheDownload::make(
QUrl("http://" + URLConstants::SKINS_BASE + profile.name + ".png"), meta);
skin_dls.append(action);
meta->stale = true;
}
}
}
if (!skin_dls.isEmpty())
{
auto job = new NetJob("Startup player skins download");
connect(job, SIGNAL(succeeded()), SLOT(skinJobFinished()));
connect(job, SIGNAL(failed()), SLOT(skinJobFinished()));
for (auto action : skin_dls)
job->addNetAction(action);
skin_download_job.reset(job);
job->start();
}
// run the things that load and download other things... FIXME: this is NOT the place
// FIXME: invisible actions in the background = NOPE.
{
if (!MMC->minecraftlist()->isLoaded())
{
m_versionLoadTask = MMC->minecraftlist()->getLoadTask();
startTask(m_versionLoadTask);
}
if (!MMC->lwjgllist()->isLoaded())
{
MMC->lwjgllist()->loadList();
}
MMC->newsChecker()->reloadNews();
updateNewsLabel();
// set up the updater object.
auto updater = MMC->updateChecker();
connect(updater.get(), &UpdateChecker::updateAvailable, this,
&MainWindow::updateAvailable);
connect(updater.get(), &UpdateChecker::noUpdateFound, this,
&MainWindow::updateNotAvailable);
// if automatic update checks are allowed, start one.
if (MMC->settings()->get("AutoUpdate").toBool())
{
auto updater = MMC->updateChecker();
updater->checkForUpdate(false);
}
connect(MMC->notificationChecker().get(),
&NotificationChecker::notificationCheckFinished, this,
&MainWindow::notificationsChanged);
}
setSelectedInstanceById(MMC->settings()->get("SelectedInstance").toString());
// removing this looks stupid
view->setFocus();
}
MainWindow::~MainWindow()
{
delete ui;
delete proxymodel;
}
void MainWindow::skinJobFinished()
{
activeAccountChanged();
skin_download_job.reset();
}
void MainWindow::showInstanceContextMenu(const QPoint &pos)
{
QList<QAction *> actions;
QAction *actionSep = new QAction("", this);
actionSep->setSeparator(true);
bool onInstance = view->indexAt(pos).isValid();
if (onInstance)
{
actions = ui->instanceToolBar->actions();
QAction *actionVoid = new QAction(m_selectedInstance->name(), this);
actionVoid->setEnabled(false);
QAction *actionRename = new QAction(tr("Rename"), this);
actionRename->setToolTip(ui->actionRenameInstance->toolTip());
QAction *actionCopyInstance = new QAction(tr("Copy instance"), this);
actionCopyInstance->setToolTip(ui->actionCopyInstance->toolTip());
connect(actionRename, SIGNAL(triggered(bool)),
SLOT(on_actionRenameInstance_triggered()));
connect(actionCopyInstance, SIGNAL(triggered(bool)),
SLOT(on_actionCopyInstance_triggered()));
actions.replace(1, actionRename);
actions.prepend(actionSep);
actions.prepend(actionVoid);
actions.append(actionCopyInstance);
}
else
{
QAction *actionVoid = new QAction(tr("MultiMC"), this);
actionVoid->setEnabled(false);
QAction *actionCreateInstance = new QAction(tr("Create instance"), this);
actionCreateInstance->setToolTip(ui->actionAddInstance->toolTip());
connect(actionCreateInstance, SIGNAL(triggered(bool)),
SLOT(on_actionAddInstance_triggered()));
actions.prepend(actionSep);
actions.prepend(actionVoid);
actions.append(actionCreateInstance);
}
QMenu myMenu;
myMenu.addActions(actions);
if (onInstance)
myMenu.setEnabled(m_selectedInstance->canLaunch());
myMenu.exec(view->mapToGlobal(pos));
}
void MainWindow::updateToolsMenu()
{
if (ui->actionLaunchInstance->menu())
{
ui->actionLaunchInstance->menu()->deleteLater();
}
QMenu *launchMenu = new QMenu(this);
QAction *normalLaunch = launchMenu->addAction(tr("Launch"));
connect(normalLaunch, &QAction::triggered, [this]()
{ doLaunch(); });
launchMenu->addSeparator()->setText(tr("Profilers"));
for (auto profiler : MMC->profilers().values())
{
QAction *profilerAction = launchMenu->addAction(profiler->name());
QString error;
if (!profiler->check(&error))
{
profilerAction->setDisabled(true);
profilerAction->setToolTip(
tr("Profiler not setup correctly. Go into settings, \"External Tools\"."));
}
else
{
connect(profilerAction, &QAction::triggered, [this, profiler]()
{ doLaunch(true, profiler.get()); });
}
}
launchMenu->addSeparator()->setText(tr("Tools"));
for (auto tool : MMC->tools().values())
{
QAction *toolAction = launchMenu->addAction(tool->name());
QString error;
if (!tool->check(&error))
{
toolAction->setDisabled(true);
toolAction->setToolTip(
tr("Tool not setup correctly. Go into settings, \"External Tools\"."));
}
else
{
connect(toolAction, &QAction::triggered, [this, tool]()
{ tool->createDetachedTool(m_selectedInstance, this)->run(); });
}
}
ui->actionLaunchInstance->setMenu(launchMenu);
}
void MainWindow::repopulateAccountsMenu()
{
accountMenu->clear();
std::shared_ptr<MojangAccountList> accounts = MMC->accounts();
MojangAccountPtr active_account = accounts->activeAccount();
QString active_username = "";
if (active_account != nullptr)
{
active_username = accounts->activeAccount()->username();
}
if (accounts->count() <= 0)
{
QAction *action = new QAction(tr("No accounts added!"), this);
action->setEnabled(false);
accountMenu->addAction(action);
accountMenu->addSeparator();
}
else
{
// TODO: Nicer way to iterate?
for (int i = 0; i < accounts->count(); i++)
{
MojangAccountPtr account = accounts->at(i);
// Styling hack
QAction *section = new QAction(account->username(), this);
section->setEnabled(false);
accountMenu->addAction(section);
for (auto profile : account->profiles())
{
QAction *action = new QAction(profile.name, this);
action->setData(account->username());
action->setCheckable(true);
if (active_username == account->username())
{
action->setChecked(true);
}
action->setIcon(SkinUtils::getFaceFromCache(profile.name));
accountMenu->addAction(action);
connect(action, SIGNAL(triggered(bool)), SLOT(changeActiveAccount()));
}
accountMenu->addSeparator();
}
}
QAction *action = new QAction(tr("No Default Account"), this);
action->setCheckable(true);
action->setIcon(QIcon::fromTheme("noaccount"));
action->setData("");
if (active_username.isEmpty())
{
action->setChecked(true);
}
accountMenu->addAction(action);
connect(action, SIGNAL(triggered(bool)), SLOT(changeActiveAccount()));
accountMenu->addSeparator();
accountMenu->addAction(manageAccountsAction);
}
/*
* Assumes the sender is a QAction
*/
void MainWindow::changeActiveAccount()
{
QAction *sAction = (QAction *)sender();
// Profile's associated Mojang username
// Will need to change when profiles are properly implemented
if (sAction->data().type() != QVariant::Type::String)
return;
QVariant data = sAction->data();
QString id = "";
if (!data.isNull())
{
id = data.toString();
}
MMC->accounts()->setActiveAccount(id);
activeAccountChanged();
}
void MainWindow::activeAccountChanged()
{
repopulateAccountsMenu();
MojangAccountPtr account = MMC->accounts()->activeAccount();
if (account != nullptr && account->username() != "")
{
const AccountProfile *profile = account->currentProfile();
if (profile != nullptr)
{
accountMenuButton->setIcon(SkinUtils::getFaceFromCache(profile->name));
return;
}
}
// Set the icon to the "no account" icon.
accountMenuButton->setIcon(QIcon::fromTheme("noaccount"));
}
bool MainWindow::eventFilter(QObject *obj, QEvent *ev)
{
if (obj == view)
{
if (ev->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
switch (keyEvent->key())
{
case Qt::Key_Enter:
case Qt::Key_Return:
on_actionLaunchInstance_triggered();
return true;
case Qt::Key_Delete:
on_actionDeleteInstance_triggered();
return true;
case Qt::Key_F5:
on_actionRefresh_triggered();
return true;
case Qt::Key_F2:
on_actionRenameInstance_triggered();
return true;
default:
break;
}
}
}
return QMainWindow::eventFilter(obj, ev);
}
void MainWindow::updateNewsLabel()
{
auto newsChecker = MMC->newsChecker();
if (newsChecker->isLoadingNews())
{
newsLabel->setText(tr("Loading news..."));
newsLabel->setEnabled(false);
}
else
{
QList<NewsEntryPtr> entries = newsChecker->getNewsEntries();
if (entries.length() > 0)
{
newsLabel->setText(entries[0]->title);
newsLabel->setEnabled(true);
}
else
{
newsLabel->setText(tr("No news available."));
newsLabel->setEnabled(false);
}
}
}
void MainWindow::updateAvailable(QString repo, QString versionName, int versionId)
{
UpdateDialog dlg;
UpdateAction action = (UpdateAction)dlg.exec();
switch (action)
{
case UPDATE_LATER:
QLOG_INFO() << "Update will be installed later.";
break;
case UPDATE_NOW:
downloadUpdates(repo, versionId);
break;
case UPDATE_ONEXIT:
downloadUpdates(repo, versionId, true);
break;
}
}
void MainWindow::updateNotAvailable()
{
UpdateDialog dlg(false);
dlg.exec();
}
QList<int> stringToIntList(const QString &string)
{
QStringList split = string.split(',', QString::SkipEmptyParts);
QList<int> out;
for (int i = 0; i < split.size(); ++i)
{
out.append(split.at(i).toInt());
}
return out;
}
QString intListToString(const QList<int> &list)
{
QStringList slist;
for (int i = 0; i < list.size(); ++i)
{
slist.append(QString::number(list.at(i)));
}
return slist.join(',');
}
void MainWindow::notificationsChanged()
{
QList<NotificationChecker::NotificationEntry> entries =
MMC->notificationChecker()->notificationEntries();
QList<int> shownNotifications =
stringToIntList(MMC->settings()->get("ShownNotifications").toString());
for (auto it = entries.begin(); it != entries.end(); ++it)
{
NotificationChecker::NotificationEntry entry = *it;
if (!shownNotifications.contains(entry.id) && entry.applies())
{
NotificationDialog dialog(entry, this);
if (dialog.exec() == NotificationDialog::DontShowAgain)
{
shownNotifications.append(entry.id);
}
}
}
MMC->settings()->set("ShownNotifications", intListToString(shownNotifications));
}
void MainWindow::downloadUpdates(QString repo, int versionId, bool installOnExit)
{
QLOG_INFO() << "Downloading updates.";
// TODO: If the user chooses to update on exit, we should download updates in the
// background.
// Doing so is a bit complicated, because we'd have to make sure it finished downloading
// before actually exiting MultiMC.
ProgressDialog updateDlg(this);
DownloadUpdateTask updateTask(repo, versionId, &updateDlg);
// If the task succeeds, install the updates.
if (updateDlg.exec(&updateTask))
{
UpdateFlags baseFlags = None;
if (BuildConfig.UPDATER_DRY_RUN)
baseFlags |= DryRun;
if (installOnExit)
MMC->installUpdates(updateTask.updateFilesDir(), baseFlags | OnExit);
else
MMC->installUpdates(updateTask.updateFilesDir(), baseFlags | RestartOnFinish);
}
}
void MainWindow::onCatToggled(bool state)
{
setCatBackground(state);
MMC->settings()->set("TheCat", state);
}
void MainWindow::setCatBackground(bool enabled)
{
if (enabled)
{
view->setStyleSheet("GroupView"
"{"
"background-image: url(:/backgrounds/kitteh);"
"background-attachment: fixed;"
"background-clip: padding;"
"background-position: top right;"
"background-repeat: none;"
"background-color:palette(base);"
"}");
}
else
{
view->setStyleSheet(QString());
}
}
void MainWindow::on_actionAddInstance_triggered()
{
#ifdef TEST_SEGV
// For further testing stuff.
int v = *((int *)-1);
#endif
if (!MMC->minecraftlist()->isLoaded() && m_versionLoadTask &&
m_versionLoadTask->isRunning())
{
QEventLoop waitLoop;
waitLoop.connect(m_versionLoadTask, SIGNAL(failed(QString)), SLOT(quit()));
waitLoop.connect(m_versionLoadTask, SIGNAL(succeeded()), SLOT(quit()));
waitLoop.exec();
}
NewInstanceDialog newInstDlg(this);
if (!newInstDlg.exec())
return;
InstancePtr newInstance;
QString instancesDir = MMC->settings()->get("InstanceDir").toString();
QString instDirName = DirNameFromString(newInstDlg.instName(), instancesDir);
QString instDir = PathCombine(instancesDir, instDirName);
auto &loader = InstanceFactory::get();
auto error = loader.createInstance(newInstance, newInstDlg.selectedVersion(), instDir);
QString errorMsg = tr("Failed to create instance %1: ").arg(instDirName);
switch (error)
{
case InstanceFactory::NoCreateError:
newInstance->setName(newInstDlg.instName());
newInstance->setIconKey(newInstDlg.iconKey());
MMC->instances()->add(InstancePtr(newInstance));
break;
case InstanceFactory::InstExists:
{
errorMsg += tr("An instance with the given directory name already exists.");
CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
return;
}
case InstanceFactory::CantCreateDir:
{
errorMsg += tr("Failed to create the instance directory.");
CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
return;
}
default:
{
errorMsg += tr("Unknown instance loader error %1").arg(error);
CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
return;
}
}
if (MMC->accounts()->anyAccountIsValid())
{
ProgressDialog loadDialog(this);
auto update = newInstance->doUpdate();
connect(update.get(), &Task::failed, [this](QString reason)
{
QString error = QString("Instance load failed: %1").arg(reason);
CustomMessageBox::selectable(this, tr("Error"), error, QMessageBox::Warning)
->show();
});
loadDialog.exec(update.get());
}
else
{
CustomMessageBox::selectable(
this, tr("Error"),
tr("MultiMC cannot download Minecraft or update instances unless you have at least "
"one account added.\nPlease add your Mojang or Minecraft account."),
QMessageBox::Warning)->show();
}
}
void MainWindow::on_actionCopyInstance_triggered()
{
if (!m_selectedInstance)
return;
CopyInstanceDialog copyInstDlg(m_selectedInstance, this);
if (!copyInstDlg.exec())
return;
QString instancesDir = MMC->settings()->get("InstanceDir").toString();
QString instDirName = DirNameFromString(copyInstDlg.instName(), instancesDir);
QString instDir = PathCombine(instancesDir, instDirName);
auto &loader = InstanceFactory::get();
InstancePtr newInstance;
auto error = loader.copyInstance(newInstance, m_selectedInstance, instDir);
QString errorMsg = tr("Failed to create instance %1: ").arg(instDirName);
switch (error)
{
case InstanceFactory::NoCreateError:
newInstance->setName(copyInstDlg.instName());
newInstance->setIconKey(copyInstDlg.iconKey());
MMC->instances()->add(newInstance);
return;
case InstanceFactory::InstExists:
{
errorMsg += tr("An instance with the given directory name already exists.");
CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
break;
}
case InstanceFactory::CantCreateDir:
{
errorMsg += tr("Failed to create the instance directory.");
CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
break;
}
default:
{
errorMsg += tr("Unknown instance loader error %1").arg(error);
CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
break;
}
}
}
void MainWindow::on_actionChangeInstIcon_triggered()
{
if (!m_selectedInstance)
return;
IconPickerDialog dlg(this);
dlg.exec(m_selectedInstance->iconKey());
if (dlg.result() == QDialog::Accepted)
{
m_selectedInstance->setIconKey(dlg.selectedIconKey);
auto ico = MMC->icons()->getBigIcon(dlg.selectedIconKey);
ui->actionChangeInstIcon->setIcon(ico);
}
}
void MainWindow::iconUpdated(QString icon)
{
if (icon == m_currentInstIcon)
{
ui->actionChangeInstIcon->setIcon(MMC->icons()->getBigIcon(m_currentInstIcon));
}
}
void MainWindow::updateInstanceToolIcon(QString new_icon)
{
m_currentInstIcon = new_icon;
ui->actionChangeInstIcon->setIcon(MMC->icons()->getBigIcon(m_currentInstIcon));
}
void MainWindow::setSelectedInstanceById(const QString &id)
{
if (id.isNull())
return;
const QModelIndex index = MMC->instances()->getInstanceIndexById(id);
if (index.isValid())
{
QModelIndex selectionIndex = proxymodel->mapFromSource(index);
view->selectionModel()->setCurrentIndex(selectionIndex, QItemSelectionModel::ClearAndSelect);
}
}
void MainWindow::on_actionChangeInstGroup_triggered()
{
if (!m_selectedInstance)
return;
bool ok = false;
QString name(m_selectedInstance->group());
auto groups = MMC->instances()->getGroups();
groups.insert(0, "");
groups.sort(Qt::CaseInsensitive);
int foo = groups.indexOf(name);
name = QInputDialog::getItem(this, tr("Group name"), tr("Enter a new group name."), groups,
foo, true, &ok);
name = name.simplified();
if (ok)
m_selectedInstance->setGroupPost(name);
}
void MainWindow::on_actionViewInstanceFolder_triggered()
{
QString str = MMC->settings()->get("InstanceDir").toString();
openDirInDefaultProgram(str);
}
void MainWindow::on_actionRefresh_triggered()
{
MMC->instances()->loadList();
}
void MainWindow::on_actionViewCentralModsFolder_triggered()
{
openDirInDefaultProgram(MMC->settings()->get("CentralModsDir").toString(), true);
}
void MainWindow::on_actionConfig_Folder_triggered()
{
if (m_selectedInstance)
{
QString str = m_selectedInstance->instanceConfigFolder();
openDirInDefaultProgram(QDir(str).absolutePath());
}
}
void MainWindow::on_actionCheckUpdate_triggered()
{
auto updater = MMC->updateChecker();
updater->checkForUpdate(true);
}
template <typename T>
void ShowPageDialog(T raw_provider, QWidget * parent, QString open_page = QString())
{
auto provider = std::dynamic_pointer_cast<BasePageProvider>(raw_provider);
if(!provider)
return;
PageDialog dlg(provider, open_page, parent);
dlg.exec();
}
void MainWindow::on_actionSettings_triggered()
{
ShowPageDialog(m_globalSettingsProvider, this, "global-settings");
// FIXME: quick HACK to make this work. improve, optimize.
proxymodel->invalidate();
proxymodel->sort(0);
updateToolsMenu();
}
void MainWindow::on_actionInstanceSettings_triggered()
{
ShowPageDialog(m_selectedInstance, this, "settings");
}
void MainWindow::on_actionEditInstNotes_triggered()
{
ShowPageDialog(m_selectedInstance, this, "notes");
}
void MainWindow::on_actionEditInstance_triggered()
{
ShowPageDialog(m_selectedInstance, this);
}
void MainWindow::on_actionScreenshots_triggered()
{
ShowPageDialog(m_selectedInstance, this, "screenshots");
}
void MainWindow::on_actionManageAccounts_triggered()
{
ShowPageDialog(m_globalSettingsProvider, this, "accounts");
}
void MainWindow::on_actionReportBug_triggered()
{
openWebPage(QUrl("https://github.com/MultiMC/MultiMC5/issues"));
}
void MainWindow::on_actionPatreon_triggered()
{
openWebPage(QUrl("http://www.patreon.com/multimc"));
}
void MainWindow::on_actionMoreNews_triggered()
{
openWebPage(QUrl("http://multimc.org/posts.html"));
}
void MainWindow::newsButtonClicked()
{
QList<NewsEntryPtr> entries = MMC->newsChecker()->getNewsEntries();
if (entries.count() > 0)
openWebPage(QUrl(entries[0]->link));
else
openWebPage(QUrl("http://multimc.org/posts.html"));
}
void MainWindow::on_actionAbout_triggered()
{
AboutDialog dialog(this);
dialog.exec();
}
void MainWindow::on_mainToolBar_visibilityChanged(bool)
{
// Don't allow hiding the main toolbar.
// This is the only way I could find to prevent it... :/
ui->mainToolBar->setVisible(true);
}
void MainWindow::on_actionDeleteInstance_triggered()
{
if (m_selectedInstance)
{
auto response = CustomMessageBox::selectable(
this, tr("CAREFUL"), tr("This is permanent! Are you sure?\nAbout to delete: ") +
m_selectedInstance->name(),
QMessageBox::Question, QMessageBox::Yes | QMessageBox::No)->exec();
if (response == QMessageBox::Yes)
{
m_selectedInstance->nuke();
}
}
}
void MainWindow::on_actionRenameInstance_triggered()
{
if (m_selectedInstance)
{
bool ok = false;
QString name(m_selectedInstance->name());
name =
QInputDialog::getText(this, tr("Instance name"), tr("Enter a new instance name."),
QLineEdit::Normal, name, &ok);
if (name.length() > 0)
{
if (ok && name.length())
{
m_selectedInstance->setName(name);
renameButton->setText(name);
}
}
}
}
void MainWindow::on_actionViewSelectedInstFolder_triggered()
{
if (m_selectedInstance)
{
QString str = m_selectedInstance->instanceRoot();
openDirInDefaultProgram(QDir(str).absolutePath());
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
// Save the window state and geometry.
MMC->settings()->set("MainWindowState", saveState().toBase64());
MMC->settings()->set("MainWindowGeometry", saveGeometry().toBase64());
QMainWindow::closeEvent(event);
QApplication::exit();
}
/*
void MainWindow::on_instanceView_customContextMenuRequested(const QPoint &pos)
{
QMenu *instContextMenu = new QMenu("Instance", this);
// Add the actions from the toolbar to the context menu.
instContextMenu->addActions(ui->instanceToolBar->actions());
instContextMenu->exec(view->mapToGlobal(pos));
}
*/
void MainWindow::instanceActivated(QModelIndex index)
{
if (!index.isValid())
return;
QString id = index.data(InstanceList::InstanceIDRole).toString();
InstancePtr inst = MMC->instances()->getInstanceById(id);
if (!inst)
return;
NagUtils::checkJVMArgs(inst->settings().get("JvmArgs").toString(), this);
doLaunch();
}
void MainWindow::on_actionLaunchInstance_triggered()
{
if (m_selectedInstance)
{
NagUtils::checkJVMArgs(m_selectedInstance->settings().get("JvmArgs").toString(), this);
doLaunch();
}
}
void MainWindow::on_actionLaunchInstanceOffline_triggered()
{
if (m_selectedInstance)
{
NagUtils::checkJVMArgs(m_selectedInstance->settings().get("JvmArgs").toString(), this);
doLaunch(false);
}
}
void MainWindow::doLaunch(bool online, BaseProfilerFactory *profiler)
{
if (!m_selectedInstance)
return;
// Find an account to use.
std::shared_ptr<MojangAccountList> accounts = MMC->accounts();
MojangAccountPtr account = accounts->activeAccount();
if (accounts->count() <= 0)
{
// Tell the user they need to log in at least one account in order to play.
auto reply = CustomMessageBox::selectable(
this, tr("No Accounts"),
tr("In order to play Minecraft, you must have at least one Mojang or Minecraft "
"account logged in to MultiMC."
"Would you like to open the account manager to add an account now?"),
QMessageBox::Information, QMessageBox::Yes | QMessageBox::No)->exec();
if (reply == QMessageBox::Yes)
{
// Open the account manager.
on_actionManageAccounts_triggered();
}
}
else if (account.get() == nullptr)
{
// If no default account is set, ask the user which one to use.
AccountSelectDialog selectDialog(tr("Which account would you like to use?"),
AccountSelectDialog::GlobalDefaultCheckbox, this);
selectDialog.exec();
// Launch the instance with the selected account.
account = selectDialog.selectedAccount();
// If the user said to use the account as default, do that.
if (selectDialog.useAsGlobalDefault() && account.get() != nullptr)
accounts->setActiveAccount(account->username());
}
// if no account is selected, we bail
if (!account.get())
return;
// we try empty password first :)
QString password;
// we loop until the user succeeds in logging in or gives up
bool tryagain = true;
// the failure. the default failure.
QString failReason = tr("Your account is currently not logged in. Please enter "
"your password to log in again.");
while (tryagain)
{
AuthSessionPtr session(new AuthSession());
session->wants_online = online;
auto task = account->login(session, password);
if (task)
{
// We'll need to validate the access token to make sure the account
// is still logged in.
ProgressDialog progDialog(this);
if (online)
progDialog.setSkipButton(true, tr("Play Offline"));
progDialog.exec(task.get());
if (!task->successful())
{
failReason = task->failReason();
}
}
switch (session->status)
{
case AuthSession::Undetermined:
{
QLOG_ERROR() << "Received undetermined session status during login. Bye.";
tryagain = false;
break;
}
case AuthSession::RequiresPassword:
{
EditAccountDialog passDialog(failReason, this, EditAccountDialog::PasswordField);
if (passDialog.exec() == QDialog::Accepted)
{
password = passDialog.password();
}
else
{
tryagain = false;
}
break;
}
case AuthSession::PlayableOffline:
{
// we ask the user for a player name
bool ok = false;
QString usedname = session->player_name;
QString name = QInputDialog::getText(this, tr("Player name"),
tr("Choose your offline mode player name."),
QLineEdit::Normal, session->player_name, &ok);
if (!ok)
{
tryagain = false;
break;
}
if (name.length())
{
usedname = name;
}
session->MakeOffline(usedname);
// offline flavored game from here :3
}
case AuthSession::PlayableOnline:
{
// update first if the server actually responded
if (session->auth_server_online)
{
updateInstance(m_selectedInstance, session, profiler);
}
else
{
launchInstance(m_selectedInstance, session, profiler);
}
tryagain = false;
}
}
}
}
void MainWindow::updateInstance(InstancePtr instance, AuthSessionPtr session,
BaseProfilerFactory *profiler)
{
auto updateTask = instance->doUpdate();
if (!updateTask)
{
launchInstance(instance, session, profiler);
return;
}
ProgressDialog tDialog(this);
connect(updateTask.get(), &Task::succeeded, [this, instance, session, profiler]
{ launchInstance(instance, session, profiler); });
connect(updateTask.get(), SIGNAL(failed(QString)), SLOT(onGameUpdateError(QString)));
tDialog.exec(updateTask.get());
}
void MainWindow::launchInstance(InstancePtr instance, AuthSessionPtr session,
BaseProfilerFactory *profiler)
{
Q_ASSERT_X(instance != NULL, "launchInstance", "instance is NULL");
Q_ASSERT_X(session.get() != nullptr, "launchInstance", "session is NULL");
QString launchScript;
if (!instance->prepareForLaunch(session, launchScript))
return;
MinecraftProcess *proc = new MinecraftProcess(instance);
proc->setLaunchScript(launchScript);
proc->setWorkdir(instance->minecraftRoot());
this->hide();
console = new ConsoleWindow(proc);
connect(console, SIGNAL(isClosing()), this, SLOT(instanceEnded()));
proc->setLogin(session);
proc->arm();
if (profiler)
{
QString error;
if (!profiler->check(&error))
{
QMessageBox::critical(this, tr("Error"),
tr("Couldn't start profiler: %1").arg(error));
proc->abort();
return;
}
BaseProfiler *profilerInstance = profiler->createProfiler(instance, this);
QProgressDialog dialog;
dialog.setMinimum(0);
dialog.setMaximum(0);
dialog.setValue(0);
dialog.setLabelText(tr("Waiting for profiler..."));
connect(&dialog, &QProgressDialog::canceled, profilerInstance,
&BaseProfiler::abortProfiling);
dialog.show();
connect(profilerInstance, &BaseProfiler::readyToLaunch,
[&dialog, this, proc](const QString & message)
{
dialog.accept();
QMessageBox msg;
msg.setText(tr("The launch of Minecraft itself is delayed until you press the "
"button. This is the right time to setup the profiler, as the "
"profiler server is running now.\n\n%1").arg(message));
msg.setWindowTitle(tr("Waiting"));
msg.setIcon(QMessageBox::Information);
msg.addButton(tr("Launch"), QMessageBox::AcceptRole);
msg.exec();
proc->launch();
});
connect(profilerInstance, &BaseProfiler::abortLaunch,
[&dialog, this, proc](const QString & message)
{
dialog.accept();
QMessageBox msg;
msg.setText(tr("Couldn't start the profiler: %1").arg(message));
msg.setWindowTitle(tr("Error"));
msg.setIcon(QMessageBox::Critical);
msg.addButton(QMessageBox::Ok);
msg.exec();
proc->abort();
});
profilerInstance->beginProfiling(proc);
dialog.exec();
}
else
{
proc->launch();
}
}
void MainWindow::onGameUpdateError(QString error)
{
CustomMessageBox::selectable(this, tr("Error updating instance"), error,
QMessageBox::Warning)->show();
}
void MainWindow::taskStart()
{
// Nothing to do here yet.
}
void MainWindow::taskEnd()
{
QObject *sender = QObject::sender();
if (sender == m_versionLoadTask)
m_versionLoadTask = NULL;
sender->deleteLater();
}
void MainWindow::startTask(Task *task)
{
connect(task, SIGNAL(started()), SLOT(taskStart()));
connect(task, SIGNAL(succeeded()), SLOT(taskEnd()));
connect(task, SIGNAL(failed(QString)), SLOT(taskEnd()));
task->start();
}
// BrowserDialog
void MainWindow::openWebPage(QUrl url)
{
QDesktopServices::openUrl(url);
}
void MainWindow::instanceChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
if(!current.isValid())
{
MMC->settings()->set("SelectedInstance", QString());
selectionBad();
return;
}
QString id = current.data(InstanceList::InstanceIDRole).toString();
m_selectedInstance = MMC->instances()->getInstanceById(id);
if ( m_selectedInstance )
{
ui->instanceToolBar->setEnabled(m_selectedInstance->canLaunch());
renameButton->setText(m_selectedInstance->name());
m_statusLeft->setText(m_selectedInstance->getStatusbarDescription());
updateInstanceToolIcon(m_selectedInstance->iconKey());
updateToolsMenu();
MMC->settings()->set("SelectedInstance", m_selectedInstance->id());
}
else
{
MMC->settings()->set("SelectedInstance", QString());
selectionBad();
return;
}
}
void MainWindow::selectionBad()
{
// start by reseting everything...
m_selectedInstance = nullptr;
statusBar()->clearMessage();
ui->instanceToolBar->setEnabled(false);
renameButton->setText(tr("Rename Instance"));
updateInstanceToolIcon("infinity");
// ...and then see if we can enable the previously selected instance
setSelectedInstanceById(MMC->settings()->get("SelectedInstance").toString());
}
void MainWindow::instanceEnded()
{
this->show();
}
void MainWindow::checkMigrateLegacyAssets()
{
int legacyAssets = AssetsUtils::findLegacyAssets();
if (legacyAssets > 0)
{
ProgressDialog migrateDlg(this);
AssetsMigrateTask migrateTask(legacyAssets, &migrateDlg);
{
ThreadTask threadTask(&migrateTask);
if (migrateDlg.exec(&threadTask))
{
QLOG_INFO() << "Assets migration task completed successfully";
}
else
{
QLOG_INFO() << "Assets migration task reported failure";
}
}
}
else
{
QLOG_INFO() << "Didn't find any legacy assets to migrate";
}
}
void MainWindow::checkSetDefaultJava()
{
const QString javaHack = "IntelHack";
bool askForJava = false;
do
{
QString currentHostName = QHostInfo::localHostName();
QString oldHostName = MMC->settings()->get("LastHostname").toString();
if (currentHostName != oldHostName)
{
MMC->settings()->set("LastHostname", currentHostName);
askForJava = true;
break;
}
QString currentJavaPath = MMC->settings()->get("JavaPath").toString();
if (currentJavaPath.isEmpty())
{
askForJava = true;
break;
}
#if defined Q_OS_WIN32
QString currentHack = MMC->settings()->get("JavaDetectionHack").toString();
if (currentHack != javaHack)
{
CustomMessageBox::selectable(
this, tr("Java detection forced"),
tr("Because of graphics performance issues caused by Intel drivers on Windows, "
"MultiMC java detection was forced. Please select a Java "
"version.<br/><br/>If you have custom java versions set for your instances, "
"make sure you use the 'javaw.exe' executable."),
QMessageBox::Warning)->exec();
askForJava = true;
break;
}
#endif
} while (0);
if (askForJava)
{
QLOG_DEBUG() << "Java path needs resetting, showing Java selection dialog...";
JavaVersionPtr java;
VersionSelectDialog vselect(MMC->javalist().get(), tr("Select a Java version"), this,
false);
vselect.setResizeOn(2);
vselect.exec();
if (vselect.selectedVersion())
java = std::dynamic_pointer_cast<JavaVersion>(vselect.selectedVersion());
else
{
CustomMessageBox::selectable(
this, tr("Invalid version selected"),
tr("You didn't select a valid Java version, so MultiMC will "
"select the default. "
"You can change this in the settings dialog."),
QMessageBox::Warning)->show();
JavaUtils ju;
java = ju.GetDefaultJava();
}
if (java)
{
MMC->settings()->set("JavaPath", java->path);
MMC->settings()->set("JavaDetectionHack", javaHack);
}
else
MMC->settings()->set("JavaPath", QString("java"));
}
}
void MainWindow::checkInstancePathForProblems()
{
QString instanceFolder = MMC->settings()->get("InstanceDir").toString();
if (checkProblemticPathJava(QDir(instanceFolder)))
{
QMessageBox warning;
warning.setText(tr(
"Your instance folder contains \'!\' and this is known to cause Java problems!"));
warning.setInformativeText(
tr("You have now three options: <br/>"
" - ignore this warning <br/>"
" - change the instance dir in the settings <br/>"
" - move this installation of MultiMC5 to a different folder"));
warning.setDefaultButton(QMessageBox::Ok);
warning.exec();
}
}
| 27.798071 | 95 | 0.717647 | [
"geometry",
"object",
"model"
] |
c2c77fe2f9aa4967811bc539eabf9a30b05012f3 | 2,547 | cpp | C++ | Engine/GUI/src/TextButton.cpp | xubury/FoggyEngine | 1af5b814e9c3946da678be3acf93cd4d89f01c80 | [
"BSD-3-Clause"
] | null | null | null | Engine/GUI/src/TextButton.cpp | xubury/FoggyEngine | 1af5b814e9c3946da678be3acf93cd4d89f01c80 | [
"BSD-3-Clause"
] | null | null | null | Engine/GUI/src/TextButton.cpp | xubury/FoggyEngine | 1af5b814e9c3946da678be3acf93cd4d89f01c80 | [
"BSD-3-Clause"
] | null | null | null | #include "GUI/TextButton.hpp"
#include <SFML/Graphics/RenderTarget.hpp>
#include "GUI/Configuration.hpp"
namespace foggy {
namespace gui {
TextButton::TextButton(const std::string &text, const sf::Color &fill,
const sf::Color &outline, float outline_thickness,
const sf::Font &font, const sf::Color &color,
Widget *parent)
: Button(parent), m_label(text, font, color, this) {
setFillColor(fill);
setOutlineColor(outline);
setOutlineThickness(outline_thickness);
}
void TextButton::setText(const std::string &text) { m_label.setText(text); }
void TextButton::setCharacterSize(uint32_t size) {
m_label.setCharacterSize(size);
}
void TextButton::setTextColor(const sf::Color &color) {
m_label.setTextColor(color);
}
void TextButton::setFillColor(const sf::Color &color) {
m_fill_color = color;
m_shape.setFillColor(color);
}
void TextButton::setOutlineColor(const sf::Color &color) {
m_outline_color = color;
m_shape.setOutlineColor(color);
}
void TextButton::setOutlineThickness(float thickness) {
m_outline_thickness = thickness;
m_shape.setOutlineThickness(thickness);
}
sf::Vector2f TextButton::getSize() const {
sf::FloatRect rect = m_shape.getGlobalBounds();
return sf::Vector2f(rect.width, rect.height);
}
void TextButton::updateShape() {
sf::Vector2f label_size = m_label.getSize();
float char_size = m_label.getCharacterSize();
m_shape.setSize(sf::Vector2f(label_size.x, char_size));
m_label.setPosition(0, 0);
Widget::updateShape();
}
void TextButton::draw(sf::RenderTarget &target, sf::RenderStates states) const {
sf::Vector2f outline(m_outline_thickness, m_outline_thickness);
states.transform.translate(m_pos + outline);
target.draw(m_shape, states);
target.draw(m_label, states);
}
void TextButton::onMouseEntered() {
m_shape.setOutlineColor(
sf::Color(m_outline_color.r * Configuration::Colors::lighting,
m_outline_color.g * Configuration::Colors::lighting,
m_outline_color.b * Configuration::Colors::lighting));
m_shape.setFillColor(
sf::Color(m_fill_color.r * Configuration::Colors::lighting,
m_fill_color.g * Configuration::Colors::lighting,
m_fill_color.b * Configuration::Colors::lighting));
}
void TextButton::onMouseLeft() {
m_shape.setOutlineColor(m_outline_color);
m_shape.setFillColor(m_fill_color);
}
} // namespace gui
} // namespace foggy | 31.060976 | 80 | 0.694935 | [
"transform"
] |
c2c7aa3e1de3cc1e2d997b8a8a81585aacafd4a8 | 12,080 | cpp | C++ | src/daemon-mgr.cpp | seafileltd/seadrive-gui | 5593e60c92d79b9c8fa7ac0bca661afdb2de3799 | [
"Apache-2.0"
] | null | null | null | src/daemon-mgr.cpp | seafileltd/seadrive-gui | 5593e60c92d79b9c8fa7ac0bca661afdb2de3799 | [
"Apache-2.0"
] | null | null | null | src/daemon-mgr.cpp | seafileltd/seadrive-gui | 5593e60c92d79b9c8fa7ac0bca661afdb2de3799 | [
"Apache-2.0"
] | null | null | null | #include <searpc-client.h>
#include <searpc-named-pipe-transport.h>
#if defined(_MSC_VER)
#include <windows.h>
#include <file-utils.h>
#else
#include <unistd.h>
#endif
#include <glib-object.h>
#include <cstdio>
#include <cstdlib>
#include <QLibrary>
#include <QTimer>
#include <QStringList>
#include <QString>
#include <QDebug>
#include <QDir>
#include <QCoreApplication>
#include <QSettings>
#include "utils/utils.h"
#include "utils/process.h"
#include "seadrive-gui.h"
#include "daemon-mgr.h"
#include "settings-mgr.h"
#include "rpc/rpc-client.h"
#include "utils/utils-win.h"
#include "open-local-helper.h"
#include "i18n.h"
#if defined(Q_OS_MAC)
#include "utils/utils-mac.h"
#endif
namespace {
const int kDaemonReadyCheckIntervalMilli = 2000;
const int kMaxDaemonReadyCheck = 15;
// When the daemon process is dead, we try to restart it every 5 seconds, at
// most 10 times. The drive letter would be released by dokany driver about
// after 15 seconds after the daemon is dead.
const int kDaemonRestartInternvalMSecs = 5000;
const int kDaemonRestartMaxRetries = 10;
#if defined(Q_OS_WIN32)
const char *kSeadriveSockName = "\\\\.\\pipe\\seadrive_";
const char *kSeadriveExecutable = "seadrive.exe";
const int kDLLMissingErrorCode = -1073741515;
const char *kOnlyCurrentSessionAccess = "OnlyCurrentSessionAccess";
#else
const char *kSeadriveSockName = "seadrive.sock";
const char *kSeadriveExecutable = "seadrive";
#endif
typedef enum {
DAEMON_INIT = 0,
DAEMON_STARTING,
DAEMON_CONNECTING,
DAEMON_CONNECTED,
DAEMON_DEAD,
SEADRIVE_EXITING,
MAX_STATE,
} DaemonState;
const char *DaemonStateStrs[] = {
"init",
"starting",
"connecting",
"connected",
"dead",
"seadrive_exiting"
};
const char *stateToStr(int state)
{
if (state < 0 || state >= MAX_STATE) {
return "";
}
return DaemonStateStrs[state];
}
} // namespace
DaemonManager::DaemonManager()
: seadrive_daemon_(nullptr),
searpc_pipe_client_(nullptr),
unmounted_(false)
{
current_state_ = DAEMON_INIT;
conn_daemon_timer_ = new QTimer(this);
connect(conn_daemon_timer_, SIGNAL(timeout()), this, SLOT(checkDaemonReady()));
first_start_ = true;
restart_retried_ = 0;
connect(qApp, SIGNAL(aboutToQuit()),
this, SLOT(seadriveExiting()));
}
DaemonManager::~DaemonManager() {
stopAllDaemon();
}
void DaemonManager::restartSeadriveDaemon()
{
if (current_state_ == SEADRIVE_EXITING) {
return;
}
qWarning("Trying to restart seadrive daemon");
startSeadriveDaemon();
}
void DaemonManager::startSeadriveDaemon()
{
if (!gui->isDevMode()) {
shutdown_process (kSeadriveExecutable);
}
if (!gui->settingsManager()->getCacheDir(¤t_cache_dir_))
current_cache_dir_ = QDir(gui->seadriveDataDir()).absolutePath();
#if defined(Q_OS_WIN32)
# if !defined(_MSC_VER)
QLibrary dokanlib("dokan1.dll");
if (!dokanlib.load()) {
qWarning("dokan1.dll could not be loaded");
gui->errorAndExit(tr("%1 failed to initialize").arg(getBrand()));
return;
} else {
dokanlib.unload();
}
#endif
searpc_pipe_client_ = searpc_create_named_pipe_client(
utils::win::getLocalPipeName(kSeadriveSockName).c_str());
#else
searpc_pipe_client_ = searpc_create_named_pipe_client(
toCStr(QDir(current_cache_dir_).filePath(kSeadriveSockName)));
#endif
transitionState(DAEMON_STARTING);
if (!gui->isDevMode()) {
seadrive_daemon_ = new QProcess(this);
connect(seadrive_daemon_, SIGNAL(started()), this, SLOT(onDaemonStarted()));
connect(seadrive_daemon_,
SIGNAL(finished(int, QProcess::ExitStatus)),
this,
SLOT(onDaemonFinished(int, QProcess::ExitStatus)));
seadrive_daemon_->start(RESOURCE_PATH(kSeadriveExecutable), collectSeaDriveArgs());
} else {
qWarning() << "dev mode enabled, you are supposed to launch seadrive daemon yourself";
transitionState(DAEMON_CONNECTING);
conn_daemon_timer_->start(kDaemonReadyCheckIntervalMilli);
}
}
QStringList DaemonManager::collectSeaDriveArgs()
{
QStringList args;
#if defined(Q_OS_WIN32)
QString only_current_session_access = gui->readPreconfigureExpandedString(kOnlyCurrentSessionAccess);
bool current_access = only_current_session_access == "1";
if (current_access) {
qWarning("enable only current seesion access");
args << "-u";
}
#endif
args << "-d" << current_cache_dir_;
args << "-l" << QDir(gui->logsDir()).absoluteFilePath("seadrive.log");
if (I18NHelper::getInstance()->isTargetLanguage("zh_CN")) {
args << "-L" << "zh_cn";
} else if (I18NHelper::getInstance()->isTargetLanguage("de_de")) {
args << "-L" << "de_de";
} else if (I18NHelper::getInstance()->isTargetLanguage("fr_fr")) {
args << "-L" << "fr_fr";
}
#if defined(Q_OS_WIN32)
#if defined(__MINGW32__)
QString drive_letter = QString(qgetenv("SEADRIVE_LETTER")).trimmed().toUpper().remove(":").remove("/");
qDebug("SEADRIVE_LETTER = %s", qgetenv("SEADRIVE_LETTER").data());
if (!drive_letter.isEmpty()) {
if (drive_letter.length() != 1 || drive_letter < QString("A") || drive_letter > QString("Z")) {
qWarning() << "invalid SEADRIVE_LETTER '" << drive_letter << "'";
drive_letter = "S";
}
} else {
drive_letter = gui->mountDir();
}
if (!drive_letter.endsWith(":")) {
drive_letter += ":";
}
args << drive_letter;
#elif defined (_MSC_VER)
QString seadrive_root = gui->seadriveRoot();
QString sync_root_path = QDir::toNativeSeparators(seadrive_root);
args << sync_root_path;
#endif
#else
args << "-f";
QString fuse_opts = qgetenv("SEADRIVE_FUSE_OPTS");
if (fuse_opts.isEmpty()) {
#if defined(Q_OS_MAC)
diskUtilUnmount();
SettingsManager *mgr = gui->settingsManager();
QString mount_dir = gui->mountDir();
args << mount_dir;
#if 0
if (mgr->getSearchEnabled())
fuse_opts += QString(" -o volname=%1,allow_other,local").arg(getBrand());
else
fuse_opts += QString(" -o volname=%1,noappledouble").arg(getBrand());
#endif
args << "-o";
QString mount_options = QString("volname=%1,auto_xattr").arg(getBrand());
args << mount_options;
#elif defined(Q_OS_LINUX)
QStringList umount_arguments;
umount_arguments << "-u" << gui->mountDir();
QProcess::execute("fusermount", umount_arguments);
QString mount_dir = gui->mountDir();
args << mount_dir;
#endif
} else {
args << fuse_opts.split(" ");
}
#endif
auto stream = qWarning() << "starting seadrive daemon:" << kSeadriveExecutable;
foreach (const QString& arg, args) {
stream << arg;
}
return args;
}
void DaemonManager::seadriveExiting()
{
transitionState(SEADRIVE_EXITING);
}
void DaemonManager::onDaemonStarted()
{
qDebug("seadrive daemon is now running, checking if the service is ready");
conn_daemon_timer_->start(kDaemonReadyCheckIntervalMilli);
transitionState(DAEMON_CONNECTING);
OpenLocalHelper::instance()->checkPendingOpenLocalRequest();
}
void DaemonManager::checkDaemonReady()
{
QString str;
static int retried = 0;
if (searpc_named_pipe_client_connect(searpc_pipe_client_) == 0) {
retried = 0;
SearpcClient *rpc_client = searpc_client_with_named_pipe_transport(
searpc_pipe_client_, "seadrive-rpcserver");
searpc_free_client_with_pipe_transport(rpc_client);
qDebug("seadrive daemon is ready");
conn_daemon_timer_->stop();
// TODO: Instead of only connecting to the rpc server, we should make a
// real rpc call here so we can guarantee the daemon is ready to answer
// rpc requests.
g_usleep(1000000);
transitionState(DAEMON_CONNECTED);
restart_retried_ = 0;
if (first_start_) {
first_start_ = false;
emit daemonStarted();
} else {
emit daemonRestarted();
}
#if defined(Q_OS_MAC)
if (!utils::mac::addFinderFavoriteDir(gui->mountDir())) {
qWarning("failed to add mount dir to Finder favorites");
}
// We must wait seadrive volume is mounted, i.e. when seadrive
// daemon becomes ready, before we turn on spotlight on the
// seadrive volume.
utils::mac::enableSpotlightOnVolume(gui->mountDir());
#endif
return;
}
qDebug("seadrive daemon is not ready");
if (++retried > kMaxDaemonReadyCheck) {
qWarning("seadrive rpc is not ready after %d retry, abort", retried);
gui->errorAndExit(tr("%1 failed to initialize").arg(getBrand()));
}
}
void DaemonManager::stopAllDaemon()
{
qWarning("[Daemon Mgr] stopping seadrive daemon");
if (conn_daemon_timer_) {
conn_daemon_timer_->stop();
conn_daemon_timer_ = nullptr;
}
if (!gui->isDevMode() && seadrive_daemon_) {
#if defined(_MSC_VER)
if (!gui->rpcClient()->exitSeadriveDaemon()) {
qWarning("failed to exit seadrive daemon");
}
#elif defined(Q_OS_LINUX)
// https://forum.seafile.com/t/seadrive-transport-endpoint-is-not-connected/13240/5
seadrive_daemon_->terminate();
#else
seadrive_daemon_->kill();
#endif
seadrive_daemon_->waitForFinished(1500);
conn_daemon_timer_ = nullptr;
}
}
void DaemonManager::doUnmount() {
if (unmounted_) {
return;
}
unmounted_ = true;
if (gui->rpcClient() && gui->rpcClient()->isConnected()) {
qWarning("Unmounting before exit");
gui->rpcClient()->unmount();
} else {
qWarning("Not unmounting because rpc client not ready.");
}
diskUtilUnmount();
}
void DaemonManager::diskUtilUnmount() {
#if defined(Q_OS_MAC)
QStringList diskutil_args;
// Programs like MS word would prevent the disk from unmounting,
// so we have to use "force" here
diskutil_args << "unmount" << "force" << gui->mountDir();
if (QProcess::execute("diskutil", diskutil_args) != 0) {
qWarning("failed to run \"diskutil umount %s\"", toCStr(gui->mountDir()));
} else {
qWarning("diskutil umounted successfully");
}
#endif
}
void DaemonManager::onDaemonFinished(int exit_code, QProcess::ExitStatus exit_status)
{
#if defined(Q_OS_WIN32)
if (exit_code == kDLLMissingErrorCode) {
qWarning("seadrive exited because DLL is missing, aborting");
conn_daemon_timer_->stop();
gui->errorAndExit(tr("%1 failed to initialize").arg(getBrand()));
return;
}
#endif
qWarning("Seadrive daemon process %s with code %d ",
exit_status == QProcess::CrashExit ? "crashed" : "exited normally",
exit_code);
if (current_state_ == DAEMON_CONNECTING) {
conn_daemon_timer_->stop();
scheduleRestartDaemon();
} else if (current_state_ != SEADRIVE_EXITING) {
transitionState(DAEMON_DEAD);
emit daemonDead();
scheduleRestartDaemon();
}
}
void DaemonManager::scheduleRestartDaemon()
{
// When the daemon crashes when we first start seadrive, we should
// not retry too many times, because during the retry nothing
// would be shown to the user and would confuse him.
int max_retry = 2;
if (gui->rpcClient() && gui->rpcClient()->isConnected()) {
max_retry = kDaemonRestartMaxRetries;
}
if (++restart_retried_ >= max_retry) {
qWarning("reaching max tries of restarting seadrive daemon, aborting");
gui->errorAndExit(tr("%1 exited unexpectedly").arg(getBrand()));
return;
}
QTimer::singleShot(kDaemonRestartInternvalMSecs, this, SLOT(restartSeadriveDaemon()));
}
void DaemonManager::transitionState(int new_state)
{
qDebug("daemon mgr: %s => %s", stateToStr(current_state_), stateToStr(new_state));
current_state_ = new_state;
}
| 29.753695 | 107 | 0.658444 | [
"object"
] |
c2c853efda0993c0f08e39cf3b6c738cc39def7e | 6,474 | cpp | C++ | branch/old_angsys/angsys_beta2/source/angsys/angsys.shared/source/streams/binary_buffer_output_stream.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta2/source/angsys/angsys.shared/source/streams/binary_buffer_output_stream.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta2/source/angsys/angsys.shared/source/streams/binary_buffer_output_stream.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | /*********************************************************************************************************************/
/* File Name: binary_buffer_output_stream.cpp */
/* Author: Ing. Jesus Rocha <chuyangel.rm@gmail.com>, July 2016. */
/* Copyright (C) Angsys, - All Rights Reserved */
/* Confidential Information of Angsys. Not for disclosure or distribution without the author's prior written */
/* consent. This file contains code, techniques and know-how which is confidential and proprietary to Jesus Rocha */
/* */
/*********************************************************************************************************************/
#include "pch.h"
#include "ang/streams.hpp"
using namespace ang;
using namespace ang::streams;
binary_buffer_output_stream::binary_buffer_output_stream()
: _buffer(null)
, _cursor(0)
{
}
binary_buffer_output_stream::binary_buffer_output_stream(binary_buffer_output_stream* stream)
: binary_buffer_output_stream()
{
if (stream)
_buffer = stream->_buffer;
}
binary_buffer_output_stream::binary_buffer_output_stream(ibuffer_t buff)
: binary_buffer_output_stream()
{
_buffer = buff;
}
binary_buffer_output_stream::~binary_buffer_output_stream()
{
_buffer = null;
_cursor = 0;
}
ANG_IMPLEMENT_CLASSNAME(ang::streams::binary_buffer_output_stream);
ANG_IMPLEMENT_OBJECTNAME(ang::streams::binary_buffer_output_stream);
bool binary_buffer_output_stream::is_kind_of(type_name_t type)const
{
return (type == type_of<binary_buffer_output_stream>())
|| object::is_kind_of(type)
|| (type == type_of<ibinary_output_stream>());
}
bool binary_buffer_output_stream::is_inherited_of(type_name_t type)
{
return (type == type_of<binary_buffer_output_stream>())
|| object::is_inherited_of(type)
|| (type == type_of<ibinary_output_stream>());
}
bool binary_buffer_output_stream::query_object(type_name_t type, unknown_ptr_t out)
{
if (out == null)
return false;
if (type == type_of<binary_buffer_output_stream>())
{
*out = this;
return true;
}
else if (object::query_object(type, out))
{
return true;
}
else if (type == type_of<ibinary_output_stream>())
{
*out = static_cast<ibinary_output_stream*>(this);
return true;
}
else if (type == type_of<ibuffer>())
{
*out = buffer();
return true;
}
return false;
}
text::encoding_t binary_buffer_output_stream::format()const
{
return text::encoding::binary;
}
bool binary_buffer_output_stream::is_valid()const
{
return _buffer.get() != null;
}
stream_index_t binary_buffer_output_stream::position()const
{
return _cursor;
}
stream_size_t binary_buffer_output_stream::stream_size()const
{
return _buffer.get() ? _buffer->buffer_size() : 0U;
}
bool binary_buffer_output_stream::move_to(stream_index_t size, stream_reference_t ref)
{
if (!is_valid())
return false;
auto curSize = stream_size();
if (curSize == 0)
return false;
stream_index_t maxPos = curSize;
switch (ref)
{
default:break;
case ang::streams::stream_reference::begin:
if (size < 0)
_cursor = 0;
else
{
if (size > maxPos)
_cursor = maxPos;
else
_cursor = size;
}
break;
case ang::streams::stream_reference::current:
if (size < 0)
{
if ((_cursor - size) <= 0)
_cursor = 0;
else
_cursor -= size;
}
else
{
if ((_cursor + size) > maxPos)
_cursor = maxPos;
else
_cursor += size;
}
break;
case ang::streams::stream_reference::end:
if (size > 0)
_cursor = maxPos;
else
{
if (size >= maxPos)
_cursor = 0;
else
_cursor = maxPos - size;
}
break;
}
return true;
}
bool binary_buffer_output_stream::forward(stream_index_t size)
{
auto curSize = stream_size();
stream_index_t maxPos = curSize;
if ((_cursor + size) > maxPos)
_cursor = maxPos;
else
_cursor += size;
return true;
}
bool binary_buffer_output_stream::backward(stream_index_t size)
{
auto curSize = stream_size();
stream_index_t maxPos = curSize;
if ((_cursor - size) <= 0)
_cursor = 0;
else
_cursor -= size;
return true;
}
ibuffer* binary_buffer_output_stream::buffer()const
{
return _buffer.get();
}
bool binary_buffer_output_stream::attach(ibuffer* buff)
{
_buffer = buff;
_cursor = 0;
return true;
}
bool binary_buffer_output_stream::can_move_to(stream_index_t size, stream_reference_t ref)
{
if (!is_valid())
return false;
auto curSize = stream_size();
if (curSize == 0)
return false;
stream_index_t maxPos = curSize;
switch (ref)
{
default:break;
case ang::streams::stream_reference::begin:
if (size < 0)
return false;
else
{
if (size > maxPos)
return _buffer->realloc_buffer((wsize)size);
else
return true;
}
case ang::streams::stream_reference::current:
if (size < 0)
{
if ((_cursor - size) <= 0)
return false;
else
return true;
}
else
{
if ((_cursor + size) > maxPos)
return _buffer->realloc_buffer((wsize)(_cursor + size));
else
return true;
}
case ang::streams::stream_reference::end:
if (size > 0)
return _buffer->realloc_buffer((wsize)(maxPos + size));
else
{
if ((maxPos + size) < 0)
return false;
else
return true;
}
}
return false;
}
bool binary_buffer_output_stream::can_forward(stream_index_t size)
{
stream_index_t maxPos = stream_size();
if ((_cursor + size) > maxPos)
return _buffer->realloc_buffer((wsize)(_cursor + size));
else
return true;
return false;
}
bool binary_buffer_output_stream::can_backward(stream_index_t size)
{
stream_index_t maxPos = stream_size();
if ((_cursor - size) <= 0)
return false;
else
return true;
}
pointer binary_buffer_output_stream::pointer_at(stream_index_t idx)
{
if (!can_move_to(idx, stream_reference::begin))
return null;
if (_buffer.get())
return pointer(wsize(_buffer->buffer_ptr()) + idx);
return null;
}
wsize binary_buffer_output_stream::write(pointer ptr, wsize sz)
{
if (!can_forward(sz))
return 0;
memcpy(pointer_at(position()), ptr, sz);
forward(sz);
return sz;
}
wsize binary_buffer_output_stream::write(pointer ptr, wsize sz, text::text_format_t)
{
if (!can_forward(sz))
return 0;
memcpy(pointer_at(position()), ptr, sz);
forward(sz);
return sz;
} | 21.724832 | 119 | 0.644887 | [
"object"
] |
c2cbd032f406d69e9cd72628407fda7f411775f9 | 3,701 | cc | C++ | k2/python/host/csrc/fsa.cc | Jarvan-Wang/k2 | 7f164ecb804d15006fd30e8564d80e0fa212f011 | [
"Apache-2.0"
] | 491 | 2020-09-17T09:05:05.000Z | 2022-03-31T13:38:18.000Z | k2/python/host/csrc/fsa.cc | Jarvan-Wang/k2 | 7f164ecb804d15006fd30e8564d80e0fa212f011 | [
"Apache-2.0"
] | 600 | 2020-09-17T13:55:06.000Z | 2022-03-30T23:23:40.000Z | k2/python/host/csrc/fsa.cc | Jarvan-Wang/k2 | 7f164ecb804d15006fd30e8564d80e0fa212f011 | [
"Apache-2.0"
] | 121 | 2020-09-17T15:44:56.000Z | 2022-03-23T13:22:52.000Z | // k2/python/host/csrc/fsa.cc
// Copyright (c) 2020 Mobvoi Inc. (authors: Fangjun Kuang)
// Xiaomi Corporation (authors: Haowen Qiu)
// See ../../../LICENSE for clarification regarding multiple authors
#include "k2/python/host/csrc/fsa.h"
#include <memory>
#include <sstream>
#include "k2/csrc/host/fsa.h"
#include "k2/python/host/csrc/tensor.h"
namespace k2host {
// DLPackFsa initializes Fsa with `cap_indexes` and `cap_data` which are
// DLManagedTensors.
class DLPackFsa : public Fsa {
public:
DLPackFsa(py::capsule cap_indexes, py::capsule cap_data)
: indexes_tensor_(new Tensor(cap_indexes)),
data_tensor_(new Tensor(cap_data)) {
K2_CHECK_EQ(indexes_tensor_->dtype(), kInt32Type);
K2_CHECK_EQ(indexes_tensor_->NumDim(), 1);
K2_CHECK_GE(indexes_tensor_->Shape(0), 1);
K2_CHECK_EQ(indexes_tensor_->Stride(0), 1);
K2_CHECK_EQ(data_tensor_->dtype(), kInt32Type);
K2_CHECK_EQ(data_tensor_->NumDim(), 2);
K2_CHECK_GE(data_tensor_->Shape(0), 0); // num-elements
K2_CHECK_EQ(data_tensor_->Shape(1) * data_tensor_->BytesPerElement(),
sizeof(Arc));
K2_CHECK_EQ(data_tensor_->Stride(0) * data_tensor_->BytesPerElement(),
sizeof(Arc));
K2_CHECK_EQ(data_tensor_->Stride(1), 1);
int32_t size1 = indexes_tensor_->Shape(0) - 1;
int32_t size2 = data_tensor_->Shape(0);
this->Init(size1, size2, indexes_tensor_->Data<int32_t>(),
data_tensor_->Data<Arc>());
}
private:
std::unique_ptr<Tensor> indexes_tensor_;
std::unique_ptr<Tensor> data_tensor_;
};
} // namespace k2host
void PybindArc(py::module &m) {
using PyClass = k2host::Arc;
py::class_<PyClass>(m, "_Arc")
.def(py::init<>())
.def(py::init<int32_t, int32_t, int32_t, float>(), py::arg("src_state"),
py::arg("dest_state"), py::arg("label"), py::arg("weight"))
.def_readwrite("src_state", &PyClass::src_state)
.def_readwrite("dest_state", &PyClass::dest_state)
.def_readwrite("label", &PyClass::label)
.def_readwrite("weight", &PyClass::weight)
.def("__str__", [](const PyClass &self) {
std::ostringstream os;
os << self;
return os.str();
});
}
void PybindFsa(py::module &m) {
// The following wrapper is only used by pybind11 internally
// so that it knows `k2host::DLPackFsa` is a subclass of `k2host::Fsa`.
py::class_<k2host::Fsa>(m, "_Fsa");
using PyClass = k2host::DLPackFsa;
using Parent = k2host::Fsa;
py::class_<PyClass, Parent>(m, "DLPackFsa")
.def(py::init<py::capsule, py::capsule>(), py::arg("indexes"),
py::arg("data"))
.def(
"get_base", [](PyClass &self) -> Parent * { return &self; },
py::return_value_policy::reference_internal)
.def("empty", &PyClass::Empty)
.def_readonly("size1", &PyClass::size1)
.def_readonly("size2", &PyClass::size2)
.def(
"get_indexes",
[](const PyClass &self, int32_t i) {
if (i > self.size1) // note indexes.size == size1+1
throw py::index_error();
return self.indexes[i];
},
"just for test purpose to check if k2host::Fsa and the "
"underlying tensor are sharing memory.")
.def(
"get_data",
[](const PyClass &self, int32_t i) {
if (i >= self.size2) throw py::index_error();
return self.data[self.indexes[0] + i];
},
"just for test purpose to check if k2host::Fsa and the "
"underlying tensor are sharing memory.")
.def("num_states", &PyClass::NumStates)
.def("final_state", &PyClass::FinalState);
}
| 35.247619 | 78 | 0.619562 | [
"shape"
] |
c2cc220f651a628532bc5ea199bc83424ac5d182 | 2,050 | cpp | C++ | src/iniparse/IniValue.cpp | valmat/RocksServer | e00436ec9147641731c60da7d4643ecfb61217ac | [
"BSD-3-Clause"
] | 24 | 2015-02-03T08:48:52.000Z | 2021-10-03T23:57:13.000Z | src/iniparse/IniValue.cpp | valmat/RocksServer | e00436ec9147641731c60da7d4643ecfb61217ac | [
"BSD-3-Clause"
] | null | null | null | src/iniparse/IniValue.cpp | valmat/RocksServer | e00436ec9147641731c60da7d4643ecfb61217ac | [
"BSD-3-Clause"
] | 5 | 2015-07-10T15:40:53.000Z | 2019-12-06T11:57:35.000Z | /**
* IniValue.cpp
*
* Class IniValue designed for extracting values from ini entries
*
* @author valmat <ufabiz@gmail.com>
* @github https://github.com/valmat/rocksserver
*/
#include "RocksServer.h"
namespace RocksServer {
/**
* Casting to integer types
*/
IniValue<std::string>::operator IniValue<uint64_t> () const {return std::strtoull(_value.c_str(), nullptr, 10);}
IniValue<std::string>::operator IniValue<uint32_t> () const {return std::strtoul(_value.c_str(), nullptr, 10);}
IniValue<std::string>::operator IniValue<uint16_t> () const {return std::strtoul(_value.c_str(), nullptr, 10);}
IniValue<std::string>::operator IniValue<uint8_t> () const {return std::strtoul(_value.c_str(), nullptr, 10);}
IniValue<std::string>::operator IniValue<int64_t> () const {return std::stoll(_value);}
IniValue<std::string>::operator IniValue<int32_t> () const {return std::stol(_value);}
IniValue<std::string>::operator IniValue<int16_t> () const {return std::stoi(_value);}
IniValue<std::string>::operator IniValue<int8_t> () const {return std::stoi(_value);}
/**
* Cast to a EvLogger::Level
*/
IniValue<std::string>::operator IniValue<EvLogger::Level> () const
{
if("debug" == _value) return EvLogger::Level::debug;
if("msg" == _value) return EvLogger::Level::msg;
if("warn" == _value) return EvLogger::Level::warn;
if("error" == _value) return EvLogger::Level::error;
if("fatal" == _value) return EvLogger::Level::fatal;
return EvLogger::Level::none;
}
/**
* Cast to a bool
*/
IniValue<std::string>::operator IniValue<bool> () const
{
std::string v = _value;
std::transform(v.begin(), v.end(), v.begin(), (int (*)(int))std::tolower);
return ("true" == v || "1" == v || "on" == v);
}
/**
* Cast to a const char *
*/
IniValue<std::string>::operator IniValue<const char *> () const
{
return _value.c_str();
}
}
| 34.745763 | 116 | 0.611707 | [
"transform"
] |
c2cc6fc18127b718fd0225991839972a2e9f6b09 | 53,179 | cpp | C++ | 3rdparty/webkit/Source/JavaScriptCore/jit/JITOpcodes.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | 3rdparty/webkit/Source/JavaScriptCore/jit/JITOpcodes.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | 3rdparty/webkit/Source/JavaScriptCore/jit/JITOpcodes.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | /*
* Copyright (C) 2009-2018 Apple Inc. All rights reserved.
* Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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"
#if ENABLE(JIT)
#include "JIT.h"
#include "BasicBlockLocation.h"
#include "BytecodeStructs.h"
#include "Exception.h"
#include "Heap.h"
#include "InterpreterInlines.h"
#include "JITInlines.h"
#include "JSArray.h"
#include "JSCast.h"
#include "JSFunction.h"
#include "JSPropertyNameEnumerator.h"
#include "LinkBuffer.h"
#include "MaxFrameExtentForSlowPathCall.h"
#include "SlowPathCall.h"
#include "SuperSampler.h"
#include "ThunkGenerators.h"
#include "TypeLocation.h"
#include "TypeProfilerLog.h"
#include "VirtualRegister.h"
#include "Watchdog.h"
namespace JSC {
#if USE(JSVALUE64)
void JIT::emit_op_mov(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int src = currentInstruction[2].u.operand;
emitGetVirtualRegister(src, regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_end(Instruction* currentInstruction)
{
RELEASE_ASSERT(returnValueGPR != callFrameRegister);
emitGetVirtualRegister(currentInstruction[1].u.operand, returnValueGPR);
emitRestoreCalleeSaves();
emitFunctionEpilogue();
ret();
}
void JIT::emit_op_jmp(Instruction* currentInstruction)
{
unsigned target = currentInstruction[1].u.operand;
addJump(jump(), target);
}
void JIT::emit_op_new_object(Instruction* currentInstruction)
{
Structure* structure = currentInstruction[3].u.objectAllocationProfile->structure();
size_t allocationSize = JSFinalObject::allocationSize(structure->inlineCapacity());
Allocator allocator = subspaceFor<JSFinalObject>(*m_vm)->allocatorForNonVirtual(allocationSize, AllocatorForMode::AllocatorIfExists);
RegisterID resultReg = regT0;
RegisterID allocatorReg = regT1;
RegisterID scratchReg = regT2;
if (!allocator)
addSlowCase(jump());
else {
JumpList slowCases;
auto butterfly = TrustedImmPtr(nullptr);
auto mask = TrustedImm32(0);
emitAllocateJSObject(resultReg, JITAllocator::constant(allocator), allocatorReg, TrustedImmPtr(structure), butterfly, mask, scratchReg, slowCases);
emitInitializeInlineStorage(resultReg, structure->inlineCapacity());
addSlowCase(slowCases);
emitPutVirtualRegister(currentInstruction[1].u.operand);
}
}
void JIT::emitSlow_op_new_object(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
{
linkAllSlowCases(iter);
int dst = currentInstruction[1].u.operand;
Structure* structure = currentInstruction[3].u.objectAllocationProfile->structure();
callOperation(operationNewObject, structure);
emitStoreCell(dst, returnValueGPR);
}
void JIT::emit_op_overrides_has_instance(Instruction* currentInstruction)
{
auto& bytecode = *reinterpret_cast<OpOverridesHasInstance*>(currentInstruction);
int dst = bytecode.dst();
int constructor = bytecode.constructor();
int hasInstanceValue = bytecode.hasInstanceValue();
emitGetVirtualRegister(hasInstanceValue, regT0);
// We don't jump if we know what Symbol.hasInstance would do.
Jump customhasInstanceValue = branchPtr(NotEqual, regT0, TrustedImmPtr(m_codeBlock->globalObject()->functionProtoHasInstanceSymbolFunction()));
emitGetVirtualRegister(constructor, regT0);
// Check that constructor 'ImplementsDefaultHasInstance' i.e. the object is not a C-API user nor a bound function.
test8(Zero, Address(regT0, JSCell::typeInfoFlagsOffset()), TrustedImm32(ImplementsDefaultHasInstance), regT0);
emitTagBool(regT0);
Jump done = jump();
customhasInstanceValue.link(this);
move(TrustedImm32(ValueTrue), regT0);
done.link(this);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_instanceof(Instruction* currentInstruction)
{
auto& bytecode = *reinterpret_cast<OpInstanceof*>(currentInstruction);
int dst = bytecode.dst();
int value = bytecode.value();
int proto = bytecode.prototype();
// Load the operands (baseVal, proto, and value respectively) into registers.
// We use regT0 for baseVal since we will be done with this first, and we can then use it for the result.
emitGetVirtualRegister(value, regT2);
emitGetVirtualRegister(proto, regT1);
// Check that proto are cells. baseVal must be a cell - this is checked by the get_by_id for Symbol.hasInstance.
emitJumpSlowCaseIfNotJSCell(regT2, value);
emitJumpSlowCaseIfNotJSCell(regT1, proto);
// Check that prototype is an object
addSlowCase(emitJumpIfCellNotObject(regT1));
// Optimistically load the result true, and start looping.
// Initially, regT1 still contains proto and regT2 still contains value.
// As we loop regT2 will be updated with its prototype, recursively walking the prototype chain.
move(TrustedImm64(JSValue::encode(jsBoolean(true))), regT0);
Label loop(this);
addSlowCase(branch8(Equal, Address(regT2, JSCell::typeInfoTypeOffset()), TrustedImm32(ProxyObjectType)));
// Load the prototype of the object in regT2. If this is equal to regT1 - WIN!
// Otherwise, check if we've hit null - if we have then drop out of the loop, if not go again.
emitLoadStructure(*vm(), regT2, regT4, regT3);
load64(Address(regT4, Structure::prototypeOffset()), regT4);
auto hasMonoProto = branchTest64(NonZero, regT4);
load64(Address(regT2, offsetRelativeToBase(knownPolyProtoOffset)), regT4);
hasMonoProto.link(this);
move(regT4, regT2);
Jump isInstance = branchPtr(Equal, regT2, regT1);
emitJumpIfJSCell(regT2).linkTo(loop, this);
// We get here either by dropping out of the loop, or if value was not an Object. Result is false.
move(TrustedImm64(JSValue::encode(jsBoolean(false))), regT0);
// isInstance jumps right down to here, to skip setting the result to false (it has already set true).
isInstance.link(this);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_instanceof_custom(Instruction*)
{
// This always goes to slow path since we expect it to be rare.
addSlowCase(jump());
}
void JIT::emit_op_is_empty(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int value = currentInstruction[2].u.operand;
emitGetVirtualRegister(value, regT0);
compare64(Equal, regT0, TrustedImm32(JSValue::encode(JSValue())), regT0);
emitTagBool(regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_is_undefined(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int value = currentInstruction[2].u.operand;
emitGetVirtualRegister(value, regT0);
Jump isCell = emitJumpIfJSCell(regT0);
compare64(Equal, regT0, TrustedImm32(ValueUndefined), regT0);
Jump done = jump();
isCell.link(this);
Jump isMasqueradesAsUndefined = branchTest8(NonZero, Address(regT0, JSCell::typeInfoFlagsOffset()), TrustedImm32(MasqueradesAsUndefined));
move(TrustedImm32(0), regT0);
Jump notMasqueradesAsUndefined = jump();
isMasqueradesAsUndefined.link(this);
emitLoadStructure(*vm(), regT0, regT1, regT2);
move(TrustedImmPtr(m_codeBlock->globalObject()), regT0);
loadPtr(Address(regT1, Structure::globalObjectOffset()), regT1);
comparePtr(Equal, regT0, regT1, regT0);
notMasqueradesAsUndefined.link(this);
done.link(this);
emitTagBool(regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_is_boolean(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int value = currentInstruction[2].u.operand;
emitGetVirtualRegister(value, regT0);
xor64(TrustedImm32(static_cast<int32_t>(ValueFalse)), regT0);
test64(Zero, regT0, TrustedImm32(static_cast<int32_t>(~1)), regT0);
emitTagBool(regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_is_number(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int value = currentInstruction[2].u.operand;
emitGetVirtualRegister(value, regT0);
test64(NonZero, regT0, tagTypeNumberRegister, regT0);
emitTagBool(regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_is_cell_with_type(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int value = currentInstruction[2].u.operand;
int type = currentInstruction[3].u.operand;
emitGetVirtualRegister(value, regT0);
Jump isNotCell = emitJumpIfNotJSCell(regT0);
compare8(Equal, Address(regT0, JSCell::typeInfoTypeOffset()), TrustedImm32(type), regT0);
emitTagBool(regT0);
Jump done = jump();
isNotCell.link(this);
move(TrustedImm32(ValueFalse), regT0);
done.link(this);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_is_object(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int value = currentInstruction[2].u.operand;
emitGetVirtualRegister(value, regT0);
Jump isNotCell = emitJumpIfNotJSCell(regT0);
compare8(AboveOrEqual, Address(regT0, JSCell::typeInfoTypeOffset()), TrustedImm32(ObjectType), regT0);
emitTagBool(regT0);
Jump done = jump();
isNotCell.link(this);
move(TrustedImm32(ValueFalse), regT0);
done.link(this);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_ret(Instruction* currentInstruction)
{
ASSERT(callFrameRegister != regT1);
ASSERT(regT1 != returnValueGPR);
ASSERT(returnValueGPR != callFrameRegister);
// Return the result in %eax.
emitGetVirtualRegister(currentInstruction[1].u.operand, returnValueGPR);
checkStackPointerAlignment();
emitRestoreCalleeSaves();
emitFunctionEpilogue();
ret();
}
void JIT::emit_op_to_primitive(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int src = currentInstruction[2].u.operand;
emitGetVirtualRegister(src, regT0);
Jump isImm = emitJumpIfNotJSCell(regT0);
addSlowCase(emitJumpIfCellObject(regT0));
isImm.link(this);
if (dst != src)
emitPutVirtualRegister(dst);
}
void JIT::emit_op_set_function_name(Instruction* currentInstruction)
{
emitGetVirtualRegister(currentInstruction[1].u.operand, regT0);
emitGetVirtualRegister(currentInstruction[2].u.operand, regT1);
callOperation(operationSetFunctionName, regT0, regT1);
}
void JIT::emit_op_not(Instruction* currentInstruction)
{
emitGetVirtualRegister(currentInstruction[2].u.operand, regT0);
// Invert against JSValue(false); if the value was tagged as a boolean, then all bits will be
// clear other than the low bit (which will be 0 or 1 for false or true inputs respectively).
// Then invert against JSValue(true), which will add the tag back in, and flip the low bit.
xor64(TrustedImm32(static_cast<int32_t>(ValueFalse)), regT0);
addSlowCase(branchTestPtr(NonZero, regT0, TrustedImm32(static_cast<int32_t>(~1))));
xor64(TrustedImm32(static_cast<int32_t>(ValueTrue)), regT0);
emitPutVirtualRegister(currentInstruction[1].u.operand);
}
void JIT::emit_op_jfalse(Instruction* currentInstruction)
{
unsigned target = currentInstruction[2].u.operand;
GPRReg value = regT0;
GPRReg result = regT1;
GPRReg scratch = regT2;
bool shouldCheckMasqueradesAsUndefined = true;
emitGetVirtualRegister(currentInstruction[1].u.operand, value);
emitConvertValueToBoolean(*vm(), JSValueRegs(value), result, scratch, fpRegT0, fpRegT1, shouldCheckMasqueradesAsUndefined, m_codeBlock->globalObject());
addJump(branchTest32(Zero, result), target);
}
void JIT::emit_op_jeq_null(Instruction* currentInstruction)
{
int src = currentInstruction[1].u.operand;
unsigned target = currentInstruction[2].u.operand;
emitGetVirtualRegister(src, regT0);
Jump isImmediate = emitJumpIfNotJSCell(regT0);
// First, handle JSCell cases - check MasqueradesAsUndefined bit on the structure.
Jump isNotMasqueradesAsUndefined = branchTest8(Zero, Address(regT0, JSCell::typeInfoFlagsOffset()), TrustedImm32(MasqueradesAsUndefined));
emitLoadStructure(*vm(), regT0, regT2, regT1);
move(TrustedImmPtr(m_codeBlock->globalObject()), regT0);
addJump(branchPtr(Equal, Address(regT2, Structure::globalObjectOffset()), regT0), target);
Jump masqueradesGlobalObjectIsForeign = jump();
// Now handle the immediate cases - undefined & null
isImmediate.link(this);
and64(TrustedImm32(~TagBitUndefined), regT0);
addJump(branch64(Equal, regT0, TrustedImm64(JSValue::encode(jsNull()))), target);
isNotMasqueradesAsUndefined.link(this);
masqueradesGlobalObjectIsForeign.link(this);
};
void JIT::emit_op_jneq_null(Instruction* currentInstruction)
{
int src = currentInstruction[1].u.operand;
unsigned target = currentInstruction[2].u.operand;
emitGetVirtualRegister(src, regT0);
Jump isImmediate = emitJumpIfNotJSCell(regT0);
// First, handle JSCell cases - check MasqueradesAsUndefined bit on the structure.
addJump(branchTest8(Zero, Address(regT0, JSCell::typeInfoFlagsOffset()), TrustedImm32(MasqueradesAsUndefined)), target);
emitLoadStructure(*vm(), regT0, regT2, regT1);
move(TrustedImmPtr(m_codeBlock->globalObject()), regT0);
addJump(branchPtr(NotEqual, Address(regT2, Structure::globalObjectOffset()), regT0), target);
Jump wasNotImmediate = jump();
// Now handle the immediate cases - undefined & null
isImmediate.link(this);
and64(TrustedImm32(~TagBitUndefined), regT0);
addJump(branch64(NotEqual, regT0, TrustedImm64(JSValue::encode(jsNull()))), target);
wasNotImmediate.link(this);
}
void JIT::emit_op_jneq_ptr(Instruction* currentInstruction)
{
int src = currentInstruction[1].u.operand;
Special::Pointer ptr = currentInstruction[2].u.specialPointer;
unsigned target = currentInstruction[3].u.operand;
emitGetVirtualRegister(src, regT0);
CCallHelpers::Jump equal = branchPtr(Equal, regT0, TrustedImmPtr(actualPointerFor(m_codeBlock, ptr)));
store32(TrustedImm32(1), ¤tInstruction[4].u.operand);
addJump(jump(), target);
equal.link(this);
}
void JIT::emit_op_eq(Instruction* currentInstruction)
{
emitGetVirtualRegisters(currentInstruction[2].u.operand, regT0, currentInstruction[3].u.operand, regT1);
emitJumpSlowCaseIfNotInt(regT0, regT1, regT2);
compare32(Equal, regT1, regT0, regT0);
emitTagBool(regT0);
emitPutVirtualRegister(currentInstruction[1].u.operand);
}
void JIT::emit_op_jtrue(Instruction* currentInstruction)
{
unsigned target = currentInstruction[2].u.operand;
GPRReg value = regT0;
GPRReg result = regT1;
GPRReg scratch = regT2;
bool shouldCheckMasqueradesAsUndefined = true;
emitGetVirtualRegister(currentInstruction[1].u.operand, value);
emitConvertValueToBoolean(*vm(), JSValueRegs(value), result, scratch, fpRegT0, fpRegT1, shouldCheckMasqueradesAsUndefined, m_codeBlock->globalObject());
addJump(branchTest32(NonZero, result), target);
}
void JIT::emit_op_neq(Instruction* currentInstruction)
{
emitGetVirtualRegisters(currentInstruction[2].u.operand, regT0, currentInstruction[3].u.operand, regT1);
emitJumpSlowCaseIfNotInt(regT0, regT1, regT2);
compare32(NotEqual, regT1, regT0, regT0);
emitTagBool(regT0);
emitPutVirtualRegister(currentInstruction[1].u.operand);
}
void JIT::emit_op_throw(Instruction* currentInstruction)
{
ASSERT(regT0 == returnValueGPR);
copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
emitGetVirtualRegister(currentInstruction[1].u.operand, regT0);
callOperationNoExceptionCheck(operationThrow, regT0);
jumpToExceptionHandler(*vm());
}
void JIT::compileOpStrictEq(Instruction* currentInstruction, CompileOpStrictEqType type)
{
int dst = currentInstruction[1].u.operand;
int src1 = currentInstruction[2].u.operand;
int src2 = currentInstruction[3].u.operand;
emitGetVirtualRegisters(src1, regT0, src2, regT1);
// Jump slow if both are cells (to cover strings).
move(regT0, regT2);
or64(regT1, regT2);
addSlowCase(emitJumpIfJSCell(regT2));
// Jump slow if either is a double. First test if it's an integer, which is fine, and then test
// if it's a double.
Jump leftOK = emitJumpIfInt(regT0);
addSlowCase(emitJumpIfNumber(regT0));
leftOK.link(this);
Jump rightOK = emitJumpIfInt(regT1);
addSlowCase(emitJumpIfNumber(regT1));
rightOK.link(this);
if (type == OpStrictEq)
compare64(Equal, regT1, regT0, regT0);
else
compare64(NotEqual, regT1, regT0, regT0);
emitTagBool(regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_stricteq(Instruction* currentInstruction)
{
compileOpStrictEq(currentInstruction, OpStrictEq);
}
void JIT::emit_op_nstricteq(Instruction* currentInstruction)
{
compileOpStrictEq(currentInstruction, OpNStrictEq);
}
void JIT::emit_op_to_number(Instruction* currentInstruction)
{
int dstVReg = currentInstruction[1].u.operand;
int srcVReg = currentInstruction[2].u.operand;
emitGetVirtualRegister(srcVReg, regT0);
addSlowCase(emitJumpIfNotNumber(regT0));
emitValueProfilingSite();
if (srcVReg != dstVReg)
emitPutVirtualRegister(dstVReg);
}
void JIT::emit_op_to_string(Instruction* currentInstruction)
{
int srcVReg = currentInstruction[2].u.operand;
emitGetVirtualRegister(srcVReg, regT0);
addSlowCase(emitJumpIfNotJSCell(regT0));
addSlowCase(branch8(NotEqual, Address(regT0, JSCell::typeInfoTypeOffset()), TrustedImm32(StringType)));
emitPutVirtualRegister(currentInstruction[1].u.operand);
}
void JIT::emit_op_to_object(Instruction* currentInstruction)
{
int dstVReg = currentInstruction[1].u.operand;
int srcVReg = currentInstruction[2].u.operand;
emitGetVirtualRegister(srcVReg, regT0);
addSlowCase(emitJumpIfNotJSCell(regT0));
addSlowCase(branch8(Below, Address(regT0, JSCell::typeInfoTypeOffset()), TrustedImm32(ObjectType)));
emitValueProfilingSite();
if (srcVReg != dstVReg)
emitPutVirtualRegister(dstVReg);
}
void JIT::emit_op_catch(Instruction* currentInstruction)
{
restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
move(TrustedImmPtr(m_vm), regT3);
load64(Address(regT3, VM::callFrameForCatchOffset()), callFrameRegister);
storePtr(TrustedImmPtr(nullptr), Address(regT3, VM::callFrameForCatchOffset()));
addPtr(TrustedImm32(stackPointerOffsetFor(codeBlock()) * sizeof(Register)), callFrameRegister, stackPointerRegister);
callOperationNoExceptionCheck(operationCheckIfExceptionIsUncatchableAndNotifyProfiler);
Jump isCatchableException = branchTest32(Zero, returnValueGPR);
jumpToExceptionHandler(*vm());
isCatchableException.link(this);
move(TrustedImmPtr(m_vm), regT3);
load64(Address(regT3, VM::exceptionOffset()), regT0);
store64(TrustedImm64(JSValue::encode(JSValue())), Address(regT3, VM::exceptionOffset()));
emitPutVirtualRegister(currentInstruction[1].u.operand);
load64(Address(regT0, Exception::valueOffset()), regT0);
emitPutVirtualRegister(currentInstruction[2].u.operand);
#if ENABLE(DFG_JIT)
// FIXME: consider inline caching the process of doing OSR entry, including
// argument type proofs, storing locals to the buffer, etc
// https://bugs.webkit.org/show_bug.cgi?id=175598
ValueProfileAndOperandBuffer* buffer = static_cast<ValueProfileAndOperandBuffer*>(currentInstruction[3].u.pointer);
if (buffer || !shouldEmitProfiling())
callOperation(operationTryOSREnterAtCatch, m_bytecodeOffset);
else
callOperation(operationTryOSREnterAtCatchAndValueProfile, m_bytecodeOffset);
auto skipOSREntry = branchTestPtr(Zero, returnValueGPR);
emitRestoreCalleeSaves();
jump(returnValueGPR);
skipOSREntry.link(this);
if (buffer && shouldEmitProfiling()) {
buffer->forEach([&] (ValueProfileAndOperand& profile) {
JSValueRegs regs(regT0);
emitGetVirtualRegister(profile.m_operand, regs);
emitValueProfilingSite(profile.m_profile);
});
}
#endif // ENABLE(DFG_JIT)
}
void JIT::emit_op_identity_with_profile(Instruction*)
{
// We don't need to do anything here...
}
void JIT::emit_op_get_parent_scope(Instruction* currentInstruction)
{
int currentScope = currentInstruction[2].u.operand;
emitGetVirtualRegister(currentScope, regT0);
loadPtr(Address(regT0, JSScope::offsetOfNext()), regT0);
emitStoreCell(currentInstruction[1].u.operand, regT0);
}
void JIT::emit_op_switch_imm(Instruction* currentInstruction)
{
size_t tableIndex = currentInstruction[1].u.operand;
unsigned defaultOffset = currentInstruction[2].u.operand;
unsigned scrutinee = currentInstruction[3].u.operand;
// create jump table for switch destinations, track this switch statement.
SimpleJumpTable* jumpTable = &m_codeBlock->switchJumpTable(tableIndex);
m_switches.append(SwitchRecord(jumpTable, m_bytecodeOffset, defaultOffset, SwitchRecord::Immediate));
jumpTable->ensureCTITable();
emitGetVirtualRegister(scrutinee, regT0);
callOperation(operationSwitchImmWithUnknownKeyType, regT0, tableIndex);
jump(returnValueGPR);
}
void JIT::emit_op_switch_char(Instruction* currentInstruction)
{
size_t tableIndex = currentInstruction[1].u.operand;
unsigned defaultOffset = currentInstruction[2].u.operand;
unsigned scrutinee = currentInstruction[3].u.operand;
// create jump table for switch destinations, track this switch statement.
SimpleJumpTable* jumpTable = &m_codeBlock->switchJumpTable(tableIndex);
m_switches.append(SwitchRecord(jumpTable, m_bytecodeOffset, defaultOffset, SwitchRecord::Character));
jumpTable->ensureCTITable();
emitGetVirtualRegister(scrutinee, regT0);
callOperation(operationSwitchCharWithUnknownKeyType, regT0, tableIndex);
jump(returnValueGPR);
}
void JIT::emit_op_switch_string(Instruction* currentInstruction)
{
size_t tableIndex = currentInstruction[1].u.operand;
unsigned defaultOffset = currentInstruction[2].u.operand;
unsigned scrutinee = currentInstruction[3].u.operand;
// create jump table for switch destinations, track this switch statement.
StringJumpTable* jumpTable = &m_codeBlock->stringSwitchJumpTable(tableIndex);
m_switches.append(SwitchRecord(jumpTable, m_bytecodeOffset, defaultOffset));
emitGetVirtualRegister(scrutinee, regT0);
callOperation(operationSwitchStringWithUnknownKeyType, regT0, tableIndex);
jump(returnValueGPR);
}
void JIT::emit_op_debug(Instruction* currentInstruction)
{
load32(codeBlock()->debuggerRequestsAddress(), regT0);
Jump noDebuggerRequests = branchTest32(Zero, regT0);
callOperation(operationDebug, currentInstruction[1].u.operand);
noDebuggerRequests.link(this);
}
void JIT::emit_op_eq_null(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int src1 = currentInstruction[2].u.operand;
emitGetVirtualRegister(src1, regT0);
Jump isImmediate = emitJumpIfNotJSCell(regT0);
Jump isMasqueradesAsUndefined = branchTest8(NonZero, Address(regT0, JSCell::typeInfoFlagsOffset()), TrustedImm32(MasqueradesAsUndefined));
move(TrustedImm32(0), regT0);
Jump wasNotMasqueradesAsUndefined = jump();
isMasqueradesAsUndefined.link(this);
emitLoadStructure(*vm(), regT0, regT2, regT1);
move(TrustedImmPtr(m_codeBlock->globalObject()), regT0);
loadPtr(Address(regT2, Structure::globalObjectOffset()), regT2);
comparePtr(Equal, regT0, regT2, regT0);
Jump wasNotImmediate = jump();
isImmediate.link(this);
and64(TrustedImm32(~TagBitUndefined), regT0);
compare64(Equal, regT0, TrustedImm32(ValueNull), regT0);
wasNotImmediate.link(this);
wasNotMasqueradesAsUndefined.link(this);
emitTagBool(regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_neq_null(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int src1 = currentInstruction[2].u.operand;
emitGetVirtualRegister(src1, regT0);
Jump isImmediate = emitJumpIfNotJSCell(regT0);
Jump isMasqueradesAsUndefined = branchTest8(NonZero, Address(regT0, JSCell::typeInfoFlagsOffset()), TrustedImm32(MasqueradesAsUndefined));
move(TrustedImm32(1), regT0);
Jump wasNotMasqueradesAsUndefined = jump();
isMasqueradesAsUndefined.link(this);
emitLoadStructure(*vm(), regT0, regT2, regT1);
move(TrustedImmPtr(m_codeBlock->globalObject()), regT0);
loadPtr(Address(regT2, Structure::globalObjectOffset()), regT2);
comparePtr(NotEqual, regT0, regT2, regT0);
Jump wasNotImmediate = jump();
isImmediate.link(this);
and64(TrustedImm32(~TagBitUndefined), regT0);
compare64(NotEqual, regT0, TrustedImm32(ValueNull), regT0);
wasNotImmediate.link(this);
wasNotMasqueradesAsUndefined.link(this);
emitTagBool(regT0);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_enter(Instruction*)
{
// Even though CTI doesn't use them, we initialize our constant
// registers to zap stale pointers, to avoid unnecessarily prolonging
// object lifetime and increasing GC pressure.
size_t count = m_codeBlock->m_numVars;
for (size_t j = CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters(); j < count; ++j)
emitInitRegister(virtualRegisterForLocal(j).offset());
emitWriteBarrier(m_codeBlock);
emitEnterOptimizationCheck();
}
void JIT::emit_op_get_scope(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
emitGetFromCallFrameHeaderPtr(CallFrameSlot::callee, regT0);
loadPtr(Address(regT0, JSFunction::offsetOfScopeChain()), regT0);
emitStoreCell(dst, regT0);
}
void JIT::emit_op_to_this(Instruction* currentInstruction)
{
WriteBarrierBase<Structure>* cachedStructure = ¤tInstruction[2].u.structure;
emitGetVirtualRegister(currentInstruction[1].u.operand, regT1);
emitJumpSlowCaseIfNotJSCell(regT1);
addSlowCase(branch8(NotEqual, Address(regT1, JSCell::typeInfoTypeOffset()), TrustedImm32(FinalObjectType)));
loadPtr(cachedStructure, regT2);
addSlowCase(branchTestPtr(Zero, regT2));
load32(Address(regT2, Structure::structureIDOffset()), regT2);
addSlowCase(branch32(NotEqual, Address(regT1, JSCell::structureIDOffset()), regT2));
}
void JIT::emit_op_create_this(Instruction* currentInstruction)
{
int callee = currentInstruction[2].u.operand;
WriteBarrierBase<JSCell>* cachedFunction = ¤tInstruction[4].u.jsCell;
RegisterID calleeReg = regT0;
RegisterID rareDataReg = regT4;
RegisterID resultReg = regT0;
RegisterID allocatorReg = regT1;
RegisterID structureReg = regT2;
RegisterID cachedFunctionReg = regT4;
RegisterID scratchReg = regT3;
emitGetVirtualRegister(callee, calleeReg);
addSlowCase(branch8(NotEqual, Address(calleeReg, JSCell::typeInfoTypeOffset()), TrustedImm32(JSFunctionType)));
loadPtr(Address(calleeReg, JSFunction::offsetOfRareData()), rareDataReg);
addSlowCase(branchTestPtr(Zero, rareDataReg));
xorPtr(TrustedImmPtr(JSFunctionPoison::key()), rareDataReg);
load32(Address(rareDataReg, FunctionRareData::offsetOfObjectAllocationProfile() + ObjectAllocationProfile::offsetOfAllocator()), allocatorReg);
loadPtr(Address(rareDataReg, FunctionRareData::offsetOfObjectAllocationProfile() + ObjectAllocationProfile::offsetOfStructure()), structureReg);
addSlowCase(branch32(Equal, allocatorReg, TrustedImm32(Allocator().offset())));
loadPtr(cachedFunction, cachedFunctionReg);
Jump hasSeenMultipleCallees = branchPtr(Equal, cachedFunctionReg, TrustedImmPtr(JSCell::seenMultipleCalleeObjects()));
addSlowCase(branchPtr(NotEqual, calleeReg, cachedFunctionReg));
hasSeenMultipleCallees.link(this);
JumpList slowCases;
auto butterfly = TrustedImmPtr(nullptr);
auto mask = TrustedImm32(0);
emitAllocateJSObject(resultReg, JITAllocator::variable(), allocatorReg, structureReg, butterfly, mask, scratchReg, slowCases);
emitGetVirtualRegister(callee, scratchReg);
loadPtr(Address(scratchReg, JSFunction::offsetOfRareData()), scratchReg);
xorPtr(TrustedImmPtr(JSFunctionPoison::key()), scratchReg);
load32(Address(scratchReg, FunctionRareData::offsetOfObjectAllocationProfile() + ObjectAllocationProfile::offsetOfInlineCapacity()), scratchReg);
emitInitializeInlineStorage(resultReg, scratchReg);
addSlowCase(slowCases);
emitPutVirtualRegister(currentInstruction[1].u.operand);
}
void JIT::emit_op_check_tdz(Instruction* currentInstruction)
{
emitGetVirtualRegister(currentInstruction[1].u.operand, regT0);
addSlowCase(branchTest64(Zero, regT0));
}
// Slow cases
void JIT::emitSlow_op_eq(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
{
linkAllSlowCases(iter);
callOperation(operationCompareEq, regT0, regT1);
emitTagBool(returnValueGPR);
emitPutVirtualRegister(currentInstruction[1].u.operand, returnValueGPR);
}
void JIT::emitSlow_op_neq(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
{
linkAllSlowCases(iter);
callOperation(operationCompareEq, regT0, regT1);
xor32(TrustedImm32(0x1), regT0);
emitTagBool(returnValueGPR);
emitPutVirtualRegister(currentInstruction[1].u.operand, returnValueGPR);
}
void JIT::emitSlow_op_instanceof(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
{
linkAllSlowCases(iter);
auto& bytecode = *reinterpret_cast<OpInstanceof*>(currentInstruction);
int dst = bytecode.dst();
int value = bytecode.value();
int proto = bytecode.prototype();
emitGetVirtualRegister(value, regT0);
emitGetVirtualRegister(proto, regT1);
callOperation(operationInstanceOf, dst, regT0, regT1);
}
void JIT::emitSlow_op_instanceof_custom(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
{
linkAllSlowCases(iter);
auto& bytecode = *reinterpret_cast<OpInstanceofCustom*>(currentInstruction);
int dst = bytecode.dst();
int value = bytecode.value();
int constructor = bytecode.constructor();
int hasInstanceValue = bytecode.hasInstanceValue();
emitGetVirtualRegister(value, regT0);
emitGetVirtualRegister(constructor, regT1);
emitGetVirtualRegister(hasInstanceValue, regT2);
callOperation(operationInstanceOfCustom, regT0, regT1, regT2);
emitTagBool(returnValueGPR);
emitPutVirtualRegister(dst, returnValueGPR);
}
#endif // USE(JSVALUE64)
void JIT::emit_op_loop_hint(Instruction*)
{
// Emit the JIT optimization check:
if (canBeOptimized()) {
addSlowCase(branchAdd32(PositiveOrZero, TrustedImm32(Options::executionCounterIncrementForLoop()),
AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter())));
}
}
void JIT::emitSlow_op_loop_hint(Instruction*, Vector<SlowCaseEntry>::iterator& iter)
{
#if ENABLE(DFG_JIT)
// Emit the slow path for the JIT optimization check:
if (canBeOptimized()) {
linkAllSlowCases(iter);
copyCalleeSavesFromFrameOrRegisterToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
callOperation(operationOptimize, m_bytecodeOffset);
Jump noOptimizedEntry = branchTestPtr(Zero, returnValueGPR);
if (!ASSERT_DISABLED) {
Jump ok = branchPtr(MacroAssembler::Above, returnValueGPR, TrustedImmPtr(bitwise_cast<void*>(static_cast<intptr_t>(1000))));
abortWithReason(JITUnreasonableLoopHintJumpTarget);
ok.link(this);
}
jump(returnValueGPR);
noOptimizedEntry.link(this);
emitJumpSlowToHot(jump(), OPCODE_LENGTH(op_loop_hint));
}
#else
UNUSED_PARAM(iter);
#endif
}
void JIT::emit_op_check_traps(Instruction*)
{
addSlowCase(branchTest8(NonZero, AbsoluteAddress(m_vm->needTrapHandlingAddress())));
}
void JIT::emit_op_nop(Instruction*)
{
}
void JIT::emit_op_super_sampler_begin(Instruction*)
{
add32(TrustedImm32(1), AbsoluteAddress(bitwise_cast<void*>(&g_superSamplerCount)));
}
void JIT::emit_op_super_sampler_end(Instruction*)
{
sub32(TrustedImm32(1), AbsoluteAddress(bitwise_cast<void*>(&g_superSamplerCount)));
}
void JIT::emitSlow_op_check_traps(Instruction*, Vector<SlowCaseEntry>::iterator& iter)
{
linkAllSlowCases(iter);
callOperation(operationHandleTraps);
}
void JIT::emit_op_new_regexp(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
callOperation(operationNewRegexp, m_codeBlock->regexp(currentInstruction[2].u.operand));
emitStoreCell(dst, returnValueGPR);
}
void JIT::emitNewFuncCommon(Instruction* currentInstruction)
{
Jump lazyJump;
int dst = currentInstruction[1].u.operand;
#if USE(JSVALUE64)
emitGetVirtualRegister(currentInstruction[2].u.operand, regT0);
#else
emitLoadPayload(currentInstruction[2].u.operand, regT0);
#endif
FunctionExecutable* funcExec = m_codeBlock->functionDecl(currentInstruction[3].u.operand);
OpcodeID opcodeID = Interpreter::getOpcodeID(currentInstruction->u.opcode);
if (opcodeID == op_new_func)
callOperation(operationNewFunction, dst, regT0, funcExec);
else if (opcodeID == op_new_generator_func)
callOperation(operationNewGeneratorFunction, dst, regT0, funcExec);
else if (opcodeID == op_new_async_func)
callOperation(operationNewAsyncFunction, dst, regT0, funcExec);
else {
ASSERT(opcodeID == op_new_async_generator_func);
callOperation(operationNewAsyncGeneratorFunction, dst, regT0, funcExec);
}
}
void JIT::emit_op_new_func(Instruction* currentInstruction)
{
emitNewFuncCommon(currentInstruction);
}
void JIT::emit_op_new_generator_func(Instruction* currentInstruction)
{
emitNewFuncCommon(currentInstruction);
}
void JIT::emit_op_new_async_generator_func(Instruction* currentInstruction)
{
emitNewFuncCommon(currentInstruction);
}
void JIT::emit_op_new_async_func(Instruction* currentInstruction)
{
emitNewFuncCommon(currentInstruction);
}
void JIT::emitNewFuncExprCommon(Instruction* currentInstruction)
{
Jump notUndefinedScope;
int dst = currentInstruction[1].u.operand;
#if USE(JSVALUE64)
emitGetVirtualRegister(currentInstruction[2].u.operand, regT0);
notUndefinedScope = branch64(NotEqual, regT0, TrustedImm64(JSValue::encode(jsUndefined())));
store64(TrustedImm64(JSValue::encode(jsUndefined())), Address(callFrameRegister, sizeof(Register) * dst));
#else
emitLoadPayload(currentInstruction[2].u.operand, regT0);
notUndefinedScope = branch32(NotEqual, tagFor(currentInstruction[2].u.operand), TrustedImm32(JSValue::UndefinedTag));
emitStore(dst, jsUndefined());
#endif
Jump done = jump();
notUndefinedScope.link(this);
FunctionExecutable* function = m_codeBlock->functionExpr(currentInstruction[3].u.operand);
OpcodeID opcodeID = Interpreter::getOpcodeID(currentInstruction->u.opcode);
if (opcodeID == op_new_func_exp)
callOperation(operationNewFunction, dst, regT0, function);
else if (opcodeID == op_new_generator_func_exp)
callOperation(operationNewGeneratorFunction, dst, regT0, function);
else if (opcodeID == op_new_async_func_exp)
callOperation(operationNewAsyncFunction, dst, regT0, function);
else {
ASSERT(opcodeID == op_new_async_generator_func_exp);
callOperation(operationNewAsyncGeneratorFunction, dst, regT0, function);
}
done.link(this);
}
void JIT::emit_op_new_func_exp(Instruction* currentInstruction)
{
emitNewFuncExprCommon(currentInstruction);
}
void JIT::emit_op_new_generator_func_exp(Instruction* currentInstruction)
{
emitNewFuncExprCommon(currentInstruction);
}
void JIT::emit_op_new_async_func_exp(Instruction* currentInstruction)
{
emitNewFuncExprCommon(currentInstruction);
}
void JIT::emit_op_new_async_generator_func_exp(Instruction* currentInstruction)
{
emitNewFuncExprCommon(currentInstruction);
}
void JIT::emit_op_new_array(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int valuesIndex = currentInstruction[2].u.operand;
int size = currentInstruction[3].u.operand;
addPtr(TrustedImm32(valuesIndex * sizeof(Register)), callFrameRegister, regT0);
callOperation(operationNewArrayWithProfile, dst,
currentInstruction[4].u.arrayAllocationProfile, regT0, size);
}
void JIT::emit_op_new_array_with_size(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int sizeIndex = currentInstruction[2].u.operand;
#if USE(JSVALUE64)
emitGetVirtualRegister(sizeIndex, regT0);
callOperation(operationNewArrayWithSizeAndProfile, dst,
currentInstruction[3].u.arrayAllocationProfile, regT0);
#else
emitLoad(sizeIndex, regT1, regT0);
callOperation(operationNewArrayWithSizeAndProfile, dst,
currentInstruction[3].u.arrayAllocationProfile, regT1, regT0);
#endif
}
#if USE(JSVALUE64)
void JIT::emit_op_has_structure_property(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int base = currentInstruction[2].u.operand;
int enumerator = currentInstruction[4].u.operand;
emitGetVirtualRegister(base, regT0);
emitGetVirtualRegister(enumerator, regT1);
emitJumpSlowCaseIfNotJSCell(regT0, base);
load32(Address(regT0, JSCell::structureIDOffset()), regT0);
addSlowCase(branch32(NotEqual, regT0, Address(regT1, JSPropertyNameEnumerator::cachedStructureIDOffset())));
move(TrustedImm64(JSValue::encode(jsBoolean(true))), regT0);
emitPutVirtualRegister(dst);
}
void JIT::privateCompileHasIndexedProperty(ByValInfo* byValInfo, ReturnAddressPtr returnAddress, JITArrayMode arrayMode)
{
Instruction* currentInstruction = m_codeBlock->instructions().begin() + byValInfo->bytecodeIndex;
PatchableJump badType;
// FIXME: Add support for other types like TypedArrays and Arguments.
// See https://bugs.webkit.org/show_bug.cgi?id=135033 and https://bugs.webkit.org/show_bug.cgi?id=135034.
JumpList slowCases = emitLoadForArrayMode(currentInstruction, arrayMode, badType);
move(TrustedImm64(JSValue::encode(jsBoolean(true))), regT0);
Jump done = jump();
LinkBuffer patchBuffer(*this, m_codeBlock);
patchBuffer.link(badType, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(returnAddress.value())).labelAtOffset(byValInfo->returnAddressToSlowPath));
patchBuffer.link(slowCases, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(returnAddress.value())).labelAtOffset(byValInfo->returnAddressToSlowPath));
patchBuffer.link(done, byValInfo->badTypeJump.labelAtOffset(byValInfo->badTypeJumpToDone));
byValInfo->stubRoutine = FINALIZE_CODE_FOR_STUB(
m_codeBlock, patchBuffer,
"Baseline has_indexed_property stub for %s, return point %p", toCString(*m_codeBlock).data(), returnAddress.value());
MacroAssembler::repatchJump(byValInfo->badTypeJump, CodeLocationLabel(byValInfo->stubRoutine->code().code()));
MacroAssembler::repatchCall(CodeLocationCall(MacroAssemblerCodePtr(returnAddress)), FunctionPtr(operationHasIndexedPropertyGeneric));
}
void JIT::emit_op_has_indexed_property(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int base = currentInstruction[2].u.operand;
int property = currentInstruction[3].u.operand;
ArrayProfile* profile = currentInstruction[4].u.arrayProfile;
ByValInfo* byValInfo = m_codeBlock->addByValInfo();
emitGetVirtualRegisters(base, regT0, property, regT1);
// This is technically incorrect - we're zero-extending an int32. On the hot path this doesn't matter.
// We check the value as if it was a uint32 against the m_vectorLength - which will always fail if
// number was signed since m_vectorLength is always less than intmax (since the total allocation
// size is always less than 4Gb). As such zero extending will have been correct (and extending the value
// to 64-bits is necessary since it's used in the address calculation. We zero extend rather than sign
// extending since it makes it easier to re-tag the value in the slow case.
zeroExtend32ToPtr(regT1, regT1);
emitJumpSlowCaseIfNotJSCell(regT0, base);
emitArrayProfilingSiteWithCell(regT0, regT2, profile);
and32(TrustedImm32(IndexingShapeMask), regT2);
JITArrayMode mode = chooseArrayMode(profile);
PatchableJump badType;
// FIXME: Add support for other types like TypedArrays and Arguments.
// See https://bugs.webkit.org/show_bug.cgi?id=135033 and https://bugs.webkit.org/show_bug.cgi?id=135034.
JumpList slowCases = emitLoadForArrayMode(currentInstruction, mode, badType);
move(TrustedImm64(JSValue::encode(jsBoolean(true))), regT0);
addSlowCase(badType);
addSlowCase(slowCases);
Label done = label();
emitPutVirtualRegister(dst);
Label nextHotPath = label();
m_byValCompilationInfo.append(ByValCompilationInfo(byValInfo, m_bytecodeOffset, PatchableJump(), badType, mode, profile, done, nextHotPath));
}
void JIT::emitSlow_op_has_indexed_property(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
{
linkAllSlowCases(iter);
int dst = currentInstruction[1].u.operand;
int base = currentInstruction[2].u.operand;
int property = currentInstruction[3].u.operand;
ByValInfo* byValInfo = m_byValCompilationInfo[m_byValInstructionIndex].byValInfo;
Label slowPath = label();
emitGetVirtualRegister(base, regT0);
emitGetVirtualRegister(property, regT1);
Call call = callOperation(operationHasIndexedPropertyDefault, dst, regT0, regT1, byValInfo);
m_byValCompilationInfo[m_byValInstructionIndex].slowPathTarget = slowPath;
m_byValCompilationInfo[m_byValInstructionIndex].returnAddress = call;
m_byValInstructionIndex++;
}
void JIT::emit_op_get_direct_pname(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int base = currentInstruction[2].u.operand;
int index = currentInstruction[4].u.operand;
int enumerator = currentInstruction[5].u.operand;
// Check that base is a cell
emitGetVirtualRegister(base, regT0);
emitJumpSlowCaseIfNotJSCell(regT0, base);
// Check the structure
emitGetVirtualRegister(enumerator, regT2);
load32(Address(regT0, JSCell::structureIDOffset()), regT1);
addSlowCase(branch32(NotEqual, regT1, Address(regT2, JSPropertyNameEnumerator::cachedStructureIDOffset())));
// Compute the offset
emitGetVirtualRegister(index, regT1);
// If index is less than the enumerator's cached inline storage, then it's an inline access
Jump outOfLineAccess = branch32(AboveOrEqual, regT1, Address(regT2, JSPropertyNameEnumerator::cachedInlineCapacityOffset()));
addPtr(TrustedImm32(JSObject::offsetOfInlineStorage()), regT0);
signExtend32ToPtr(regT1, regT1);
load64(BaseIndex(regT0, regT1, TimesEight), regT0);
Jump done = jump();
// Otherwise it's out of line
outOfLineAccess.link(this);
loadPtr(Address(regT0, JSObject::butterflyOffset()), regT0);
sub32(Address(regT2, JSPropertyNameEnumerator::cachedInlineCapacityOffset()), regT1);
neg32(regT1);
signExtend32ToPtr(regT1, regT1);
int32_t offsetOfFirstProperty = static_cast<int32_t>(offsetInButterfly(firstOutOfLineOffset)) * sizeof(EncodedJSValue);
load64(BaseIndex(regT0, regT1, TimesEight, offsetOfFirstProperty), regT0);
done.link(this);
emitValueProfilingSite();
emitPutVirtualRegister(dst, regT0);
}
void JIT::emit_op_enumerator_structure_pname(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int enumerator = currentInstruction[2].u.operand;
int index = currentInstruction[3].u.operand;
emitGetVirtualRegister(index, regT0);
emitGetVirtualRegister(enumerator, regT1);
Jump inBounds = branch32(Below, regT0, Address(regT1, JSPropertyNameEnumerator::endStructurePropertyIndexOffset()));
move(TrustedImm64(JSValue::encode(jsNull())), regT0);
Jump done = jump();
inBounds.link(this);
loadPtr(Address(regT1, JSPropertyNameEnumerator::cachedPropertyNamesVectorOffset()), regT1);
signExtend32ToPtr(regT0, regT0);
load64(BaseIndex(regT1, regT0, TimesEight), regT0);
done.link(this);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_enumerator_generic_pname(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int enumerator = currentInstruction[2].u.operand;
int index = currentInstruction[3].u.operand;
emitGetVirtualRegister(index, regT0);
emitGetVirtualRegister(enumerator, regT1);
Jump inBounds = branch32(Below, regT0, Address(regT1, JSPropertyNameEnumerator::endGenericPropertyIndexOffset()));
move(TrustedImm64(JSValue::encode(jsNull())), regT0);
Jump done = jump();
inBounds.link(this);
loadPtr(Address(regT1, JSPropertyNameEnumerator::cachedPropertyNamesVectorOffset()), regT1);
signExtend32ToPtr(regT0, regT0);
load64(BaseIndex(regT1, regT0, TimesEight), regT0);
done.link(this);
emitPutVirtualRegister(dst);
}
void JIT::emit_op_profile_type(Instruction* currentInstruction)
{
TypeLocation* cachedTypeLocation = currentInstruction[2].u.location;
int valueToProfile = currentInstruction[1].u.operand;
emitGetVirtualRegister(valueToProfile, regT0);
JumpList jumpToEnd;
jumpToEnd.append(branchTest64(Zero, regT0));
// Compile in a predictive type check, if possible, to see if we can skip writing to the log.
// These typechecks are inlined to match those of the 64-bit JSValue type checks.
if (cachedTypeLocation->m_lastSeenType == TypeUndefined)
jumpToEnd.append(branch64(Equal, regT0, TrustedImm64(JSValue::encode(jsUndefined()))));
else if (cachedTypeLocation->m_lastSeenType == TypeNull)
jumpToEnd.append(branch64(Equal, regT0, TrustedImm64(JSValue::encode(jsNull()))));
else if (cachedTypeLocation->m_lastSeenType == TypeBoolean) {
move(regT0, regT1);
and64(TrustedImm32(~1), regT1);
jumpToEnd.append(branch64(Equal, regT1, TrustedImm64(ValueFalse)));
} else if (cachedTypeLocation->m_lastSeenType == TypeAnyInt)
jumpToEnd.append(emitJumpIfInt(regT0));
else if (cachedTypeLocation->m_lastSeenType == TypeNumber)
jumpToEnd.append(emitJumpIfNumber(regT0));
else if (cachedTypeLocation->m_lastSeenType == TypeString) {
Jump isNotCell = emitJumpIfNotJSCell(regT0);
jumpToEnd.append(branch8(Equal, Address(regT0, JSCell::typeInfoTypeOffset()), TrustedImm32(StringType)));
isNotCell.link(this);
}
// Load the type profiling log into T2.
TypeProfilerLog* cachedTypeProfilerLog = m_vm->typeProfilerLog();
move(TrustedImmPtr(cachedTypeProfilerLog), regT2);
// Load the next log entry into T1.
loadPtr(Address(regT2, TypeProfilerLog::currentLogEntryOffset()), regT1);
// Store the JSValue onto the log entry.
store64(regT0, Address(regT1, TypeProfilerLog::LogEntry::valueOffset()));
// Store the structureID of the cell if T0 is a cell, otherwise, store 0 on the log entry.
Jump notCell = emitJumpIfNotJSCell(regT0);
load32(Address(regT0, JSCell::structureIDOffset()), regT0);
store32(regT0, Address(regT1, TypeProfilerLog::LogEntry::structureIDOffset()));
Jump skipIsCell = jump();
notCell.link(this);
store32(TrustedImm32(0), Address(regT1, TypeProfilerLog::LogEntry::structureIDOffset()));
skipIsCell.link(this);
// Store the typeLocation on the log entry.
move(TrustedImmPtr(cachedTypeLocation), regT0);
store64(regT0, Address(regT1, TypeProfilerLog::LogEntry::locationOffset()));
// Increment the current log entry.
addPtr(TrustedImm32(sizeof(TypeProfilerLog::LogEntry)), regT1);
store64(regT1, Address(regT2, TypeProfilerLog::currentLogEntryOffset()));
Jump skipClearLog = branchPtr(NotEqual, regT1, TrustedImmPtr(cachedTypeProfilerLog->logEndPtr()));
// Clear the log if we're at the end of the log.
callOperation(operationProcessTypeProfilerLog);
skipClearLog.link(this);
jumpToEnd.link(this);
}
void JIT::emit_op_log_shadow_chicken_prologue(Instruction* currentInstruction)
{
updateTopCallFrame();
static_assert(nonArgGPR0 != regT0 && nonArgGPR0 != regT2, "we will have problems if this is true.");
GPRReg shadowPacketReg = regT0;
GPRReg scratch1Reg = nonArgGPR0; // This must be a non-argument register.
GPRReg scratch2Reg = regT2;
ensureShadowChickenPacket(*vm(), shadowPacketReg, scratch1Reg, scratch2Reg);
emitGetVirtualRegister(currentInstruction[1].u.operand, regT3);
logShadowChickenProloguePacket(shadowPacketReg, scratch1Reg, regT3);
}
void JIT::emit_op_log_shadow_chicken_tail(Instruction* currentInstruction)
{
updateTopCallFrame();
static_assert(nonArgGPR0 != regT0 && nonArgGPR0 != regT2, "we will have problems if this is true.");
GPRReg shadowPacketReg = regT0;
GPRReg scratch1Reg = nonArgGPR0; // This must be a non-argument register.
GPRReg scratch2Reg = regT2;
ensureShadowChickenPacket(*vm(), shadowPacketReg, scratch1Reg, scratch2Reg);
emitGetVirtualRegister(currentInstruction[1].u.operand, regT2);
emitGetVirtualRegister(currentInstruction[2].u.operand, regT3);
logShadowChickenTailPacket(shadowPacketReg, JSValueRegs(regT2), regT3, m_codeBlock, CallSiteIndex(m_bytecodeOffset));
}
#endif // USE(JSVALUE64)
void JIT::emit_op_profile_control_flow(Instruction* currentInstruction)
{
BasicBlockLocation* basicBlockLocation = currentInstruction[1].u.basicBlockLocation;
#if USE(JSVALUE64)
basicBlockLocation->emitExecuteCode(*this);
#else
basicBlockLocation->emitExecuteCode(*this, regT0);
#endif
}
void JIT::emit_op_argument_count(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
load32(payloadFor(CallFrameSlot::argumentCount), regT0);
sub32(TrustedImm32(1), regT0);
JSValueRegs result = JSValueRegs::withTwoAvailableRegs(regT0, regT1);
boxInt32(regT0, result);
emitPutVirtualRegister(dst, result);
}
void JIT::emit_op_get_rest_length(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
unsigned numParamsToSkip = currentInstruction[2].u.unsignedValue;
load32(payloadFor(CallFrameSlot::argumentCount), regT0);
sub32(TrustedImm32(1), regT0);
Jump zeroLength = branch32(LessThanOrEqual, regT0, Imm32(numParamsToSkip));
sub32(Imm32(numParamsToSkip), regT0);
#if USE(JSVALUE64)
boxInt32(regT0, JSValueRegs(regT0));
#endif
Jump done = jump();
zeroLength.link(this);
#if USE(JSVALUE64)
move(TrustedImm64(JSValue::encode(jsNumber(0))), regT0);
#else
move(TrustedImm32(0), regT0);
#endif
done.link(this);
#if USE(JSVALUE64)
emitPutVirtualRegister(dst, regT0);
#else
move(TrustedImm32(JSValue::Int32Tag), regT1);
emitPutVirtualRegister(dst, JSValueRegs(regT1, regT0));
#endif
}
void JIT::emit_op_get_argument(Instruction* currentInstruction)
{
int dst = currentInstruction[1].u.operand;
int index = currentInstruction[2].u.operand;
#if USE(JSVALUE64)
JSValueRegs resultRegs(regT0);
#else
JSValueRegs resultRegs(regT1, regT0);
#endif
load32(payloadFor(CallFrameSlot::argumentCount), regT2);
Jump argumentOutOfBounds = branch32(LessThanOrEqual, regT2, TrustedImm32(index));
loadValue(addressFor(CallFrameSlot::thisArgument + index), resultRegs);
Jump done = jump();
argumentOutOfBounds.link(this);
moveValue(jsUndefined(), resultRegs);
done.link(this);
emitValueProfilingSite();
emitPutVirtualRegister(dst, resultRegs);
}
} // namespace JSC
#endif // ENABLE(JIT)
| 37.822902 | 176 | 0.748171 | [
"object",
"vector"
] |
c2d0bd2af6e23b6a57a570602b1b465df687bca4 | 5,604 | cpp | C++ | src/opencl/device_cl.cpp | hermanw/dehash | ee837f0deb521e33207562dbc75abb3334ee7f25 | [
"MIT"
] | null | null | null | src/opencl/device_cl.cpp | hermanw/dehash | ee837f0deb521e33207562dbc75abb3334ee7f25 | [
"MIT"
] | null | null | null | src/opencl/device_cl.cpp | hermanw/dehash | ee837f0deb521e33207562dbc75abb3334ee7f25 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <vector>
#include <cstring>
#include "device_cl.h"
#include "compute_cl.h"
void _CheckCLError(cl_int error, int line)
{
if (error != CL_SUCCESS)
{
std::cout << "OpenCL call failed with error " << error << " @" << line << std::endl;
exit(1);
}
}
#define CheckCLError(error) _CheckCLError(error, __LINE__);
void DeviceCl::init(Cfg &cfg)
{
m_cfg = &cfg;
// build options string
std::ostringstream options;
options << "-D DEVICE_FUNC_PREFIX=static";
options << " -D DATA_LENGTH=" << cfg.length;
std::vector<std::string> XYZ = {"X", "Y", "Z"};
for(int i = 0; i < cfg.gpu_sections.size(); i++)
{
auto &ds = cfg.gpu_sections[i];
options << " -D " << XYZ[i] << "_INDEX=" << ds.index;
options << " -D " << XYZ[i] << "_LENGTH=" << ds.length;
options << " -D " << XYZ[i] << "_TYPE=" << ds.type;
}
const cl_context_properties contextProperties[] =
{
CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform_id),
0, 0};
cl_uint num_devices = 0;
clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, 0, nullptr,
&num_devices);
cl_device_id *devices = new cl_device_id[num_devices];
clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, num_devices,
devices, nullptr);
cl_int error = CL_SUCCESS;
context = clCreateContext(contextProperties, num_devices,
devices, nullptr, nullptr, &error);
CheckCLError(error);
size_t lengths[1] = {strlen(compute_cl)};
const char *sources[1] = {compute_cl};
program = clCreateProgramWithSource(context, 1, sources, lengths, &error);
CheckCLError(error);
// program = CreateProgram("kernels/compute.cl", context);
CheckCLError(clBuildProgram(program, num_devices, devices, options.str().c_str(), nullptr, nullptr));
kernel = clCreateKernel(program, "compute", &error);
CheckCLError(error);
#if CL_VERSION_2_0
queue = clCreateCommandQueueWithProperties(context, device_id,
0, &error);
#else
queue = clCreateCommandQueue(context, device_id,
0, &error);
#endif
CheckCLError(error);
delete[] devices;
}
DeviceCl::~DeviceCl()
{
if(count_buffer)clReleaseMemObject(count_buffer);
if(input_buffer)clReleaseMemObject(input_buffer);
if(output_buffer)clReleaseMemObject(output_buffer);
if(hash_buffer)clReleaseMemObject(hash_buffer);
if(number_buffer)clReleaseMemObject(number_buffer);
if(helper_buffer)clReleaseMemObject(helper_buffer);
if(queue)clReleaseCommandQueue(queue);
if(kernel)clReleaseKernel(kernel);
if(program)clReleaseProgram(program);
if(context)clReleaseContext(context);
}
void DeviceCl::create_buffers(
int input_buffer_size,
void *p_hash, int hash_buffer_size, int hash_length,
void *p_number, int number_buffer_size,
void *p_helper, int helper_buffer_size)
{
cl_int error = CL_SUCCESS;
int count = 0;
count_buffer = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int), &count, &error);
CheckCLError(error);
clSetKernelArg(kernel, 0, sizeof(cl_mem), &count_buffer);
input_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, input_buffer_size, 0, &error);
CheckCLError(error);
clSetKernelArg(kernel, 1, sizeof(cl_mem), &input_buffer);
output_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, hash_buffer_size * input_buffer_size, 0, &error);
CheckCLError(error);
clSetKernelArg(kernel, 2, sizeof(cl_mem), &output_buffer);
hash_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, hash_buffer_size * hash_length, p_hash, &error);
CheckCLError(error);
clSetKernelArg(kernel, 3, sizeof(cl_mem), &hash_buffer);
number_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, number_buffer_size, p_number, &error);
CheckCLError(error);
clSetKernelArg(kernel, 4, sizeof(cl_mem), &number_buffer);
helper_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, helper_buffer_size, p_helper, &error);
CheckCLError(error);
clSetKernelArg(kernel, 5, sizeof(cl_mem), &helper_buffer);
}
void DeviceCl::submit(void *p_input, int input_buffer_size, int hash_buffer_size)
{
clSetKernelArg(kernel, 6, sizeof(int), &hash_buffer_size);
CheckCLError(clEnqueueWriteBuffer(queue, input_buffer, CL_TRUE, 0,
input_buffer_size,
p_input,
0, nullptr, nullptr));
}
int DeviceCl::run()
{
CheckCLError(clEnqueueNDRangeKernel(queue, kernel, 3,
nullptr,
m_cfg->kernel_work_size,
nullptr,
0, nullptr, nullptr));
int count = 0;
CheckCLError(clEnqueueReadBuffer(queue, count_buffer, CL_TRUE, 0,
sizeof(int),
&count,
0, nullptr, nullptr));
return count;
}
void DeviceCl::read_results(void* p_output, int length)
{
CheckCLError(clEnqueueReadBuffer(queue, output_buffer, CL_TRUE, 0,
length,
p_output,
0, nullptr, nullptr));
} | 36.38961 | 131 | 0.625446 | [
"vector"
] |
c2d330084a5e195139993596062ef0b1fc804df4 | 1,306 | cpp | C++ | AtCoderBeginnersSelection/ABC049C/main_.cpp | ryokohbato/AtCoder | 1e5379dde57549f987ef8ab628230ad5fa1b60b8 | [
"MIT"
] | null | null | null | AtCoderBeginnersSelection/ABC049C/main_.cpp | ryokohbato/AtCoder | 1e5379dde57549f987ef8ab628230ad5fa1b60b8 | [
"MIT"
] | null | null | null | AtCoderBeginnersSelection/ABC049C/main_.cpp | ryokohbato/AtCoder | 1e5379dde57549f987ef8ab628230ad5fa1b60b8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool isEraseLikeStrOK(string str) {
if (str == "") return true;
try {
if (str.substr(0, 3) == "ere") {
str = str.substr(2);
}
else if (str.substr(0, 3) != "era") {
return false;
}
while(str.substr(0, 5) == "erase") {
if (str.substr(0, 6) == "eraser") {
str = str.substr(6);
}
else {
str = str.substr(5);
}
}
if (str == "") {
return true;
}
return false;
}
catch (exception e)
{
return false;
}
}
int main() {
string s;
cin >> s;
vector<int> eraseLikeStrIndex(s.size() / 5);
int addCount = 0;
while(s.find("dream") != -1) {
eraseLikeStrIndex.at(addCount) = s.find("dream");
addCount++;
}
vector<string> eraseLikeStrList(addCount);
for (int i = 0; i < addCount; i++) {
if (i == addCount - 1) {
eraseLikeStrList.at(i) = s.substr(eraseLikeStrIndex.at(i) + 5);
}
else {
eraseLikeStrList.at(i) = s.substr(eraseLikeStrIndex.at(i) + 5, eraseLikeStrIndex.at(i + 1) - eraseLikeStrIndex.at(i) - 5);
}
}
for (int i = 0; i < addCount; i++) {
if (isEraseLikeStrOK(eraseLikeStrList.at(i)) == false) {
cout << "NO" << endl;
return 0;
}
}
cout << "YES" << endl;
return 0;
}
| 19.205882 | 128 | 0.525268 | [
"vector"
] |
12483fc0a6c9029883889254fab276f12ab02898 | 2,443 | hpp | C++ | libstark/src/common/Algebra/MultiVarPoly.hpp | ddsvetlov/libSTARK | 38aeda615864346dc1ff4c290e0d0d12ea324dfb | [
"MIT"
] | 399 | 2018-02-28T17:11:54.000Z | 2022-03-24T07:41:39.000Z | libstark/src/common/Algebra/MultiVarPoly.hpp | ddsvetlov/libSTARK | 38aeda615864346dc1ff4c290e0d0d12ea324dfb | [
"MIT"
] | 18 | 2018-03-02T14:53:53.000Z | 2022-02-14T21:30:03.000Z | libstark/src/common/Algebra/MultiVarPoly.hpp | ddsvetlov/libSTARK | 38aeda615864346dc1ff4c290e0d0d12ea324dfb | [
"MIT"
] | 90 | 2018-03-01T01:18:44.000Z | 2022-02-23T00:28:50.000Z | /**MultiVarPoly.hpp - simple implementation of Multivariate Polynomial as a vector of monomials*/
#include <algebraLib/FieldElement.hpp>
#include <algebraLib/PolynomialDegree.hpp>
#include <algebraLib/PolynomialInterface.hpp>
using namespace std;
namespace Algebra{
struct MultiVarMonomial
{
FieldElement coeff;
vector<long> vars;
};
class MultiVarPoly : public PolynomialInterface{
public:
//generates the zero polynomial
MultiVarPoly() :monomials(){}
//adds monomial to polynomial. If monomial exists with different coefficient adds the new coefficient to existing monomial
//Warning:Assumes monomial always contains variables in same order.
void AddMonomial(MultiVarMonomial M){
for (auto it = monomials.begin(); it != monomials.end(); it++){
if ((*it).vars == M.vars){
(*it).coeff += M.coeff;
return;
}
}
monomials.push_back(M);
}
//adds monomial to polynomial with coeff 1, assuming this monomial does not yet appear. If monomial already exists does nothing.
void AddMonomial(vector<long> M){
for (auto it = monomials.begin(); it != monomials.end(); it++){
if ((*it).vars == M)
return;
}
MultiVarMonomial A = {one(), M};
monomials.push_back(A);
}
FieldElement eval(const vector<FieldElement>& x)const{
FieldElement res = zero();
for (const auto& prod : monomials){
FieldElement prod_res = prod.coeff;
for (const auto& varId : prod.vars){
prod_res *= x[varId];
}
res += prod_res;
}
return res;
}
PolynomialDegree getDegreeBound(const vector<PolynomialDegree>& inputDegrees)const{
PolynomialDegree deg(-1);
for (const auto& prod : monomials){
PolynomialDegree prodDeg(0);
for (const auto& varId : prod.vars){
prodDeg = degreeOfProduct(prodDeg,inputDegrees[varId]);
}
deg = max(deg, prodDeg);
}
return deg;
}
int getNonNegativeDegree()const{
int deg = 0;
for (const auto& prod : monomials){
int prodDeg = 0;
for (const auto& varId : prod.vars){
prodDeg = prodDeg + 1;
}
deg = max(deg, prodDeg);
}
return deg;
}
unique_ptr<PolynomialInterface> clone()const{
return unique_ptr<PolynomialInterface>(new MultiVarPoly(*this));
}
bool isEffectiveInput(const size_t varId)const{
for (const auto& prod : monomials){
for (const auto& varId_ : prod.vars){
if (varId_ == varId)return true;
}
}
return false;
}
private:
vector<MultiVarMonomial> monomials;
};
}
| 23.718447 | 129 | 0.688088 | [
"vector"
] |
124ec8c6581ad43b15756b462d0f1e3a8348d58e | 2,041 | cpp | C++ | using_urdf/src/publisher.cpp | steinzwerink/rviz | 5cbe5f72f7f2d846e41bfedcf4c8a70a32697300 | [
"MIT"
] | null | null | null | using_urdf/src/publisher.cpp | steinzwerink/rviz | 5cbe5f72f7f2d846e41bfedcf4c8a70a32697300 | [
"MIT"
] | null | null | null | using_urdf/src/publisher.cpp | steinzwerink/rviz | 5cbe5f72f7f2d846e41bfedcf4c8a70a32697300 | [
"MIT"
] | null | null | null | #include "using_urdf/publisher.h"
#include <std_msgs/String.h>
publisher::Publisher::Publisher()
{
}
publisher::Publisher::~Publisher()
{
}
std::string publisher::Publisher::convertMessage(pose::pose p)
{
std::string l;
l = p.pose_name;
return l;
}
int main(int argc, char **argv)
{
publisher::Publisher pub;
ros::init(argc, argv, "Publisher");
ros::NodeHandle n;
ros::Publisher pose_pub =
n.advertise<std_msgs::String>("/robot_control", 1000);
ros::Rate loop_rate(1);
int count = 0;
pose::pose p1("#2 P1150 #3 P2500 #4 P1900 T2000 ", 2);
pose::pose p2("#6 P1800 #7 P1800 T1000 ", 1);
pose::pose p3("#2 P1350 #3 P1500 #4 P1100 T12000 ", 12);
pose::pose p4("#6 P1750 #7 P1750 T1000 ", 1);
pose::pose p5("#1 P1000 T1000 ", 1);
pose::pose p6("#2 P1150 #3 P2500 #4 P1900 T2000 ", 2);
pose::pose p7("#1 P1000 #2 P1150 #3 P2500 #4 P1900 T2000 ", 2);
pose::pose p8("#1 P1600 #2 P1150 #3 P2500 #4 P1900 T15000 ", 15);
pose::pose p9("#1 P1500 #2 P1150 #3 P2500 #4 P1900 T2000 ", 2);
pose::pose p10("#1 P1500 #2 P1350 #3 P2500 #4 P1900 T2000 ", 2);
pose::pose p11("#1 P2000 #2 P1350 #3 P2500 #4 P1900 T2000 ", 2);
pose::pose p12("#1 P2000 #2 P1150 #3 P2500 #4 P1900 T2000 ", 2);
pose::pose p13("#1 P1530 #2 P1150 #3 P2500 #4 P1900 T30000 ", 30);
pose::pose p14("#1 P2000 T1000 ", 1);
pose::pose p15("#2 P1500 #3 P2100 #4 P1500 T2000 ", 2);
pose::pose p16("#1 P1500 T1000 ", 1);
pose::pose p17("#6 P500 #7 P500 T1000 ", 1);
std::vector<pose::pose> movement = {p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17};
ros::Duration(6).sleep();
while (ros::ok())
{
for (const auto &p : movement)
{
std_msgs::String msg;
msg.data = p.pose_name;
pose_pub.publish(msg);
ros::Duration(p.duration).sleep();
ros::spinOnce();
loop_rate.sleep();
++count;
}
//break;
}
return 0;
}
| 29.57971 | 116 | 0.568839 | [
"vector"
] |
124fae4e0ad5f21c7a216bae6a1ee3fbb9b3628f | 2,480 | hpp | C++ | include/private/coherence/component/util/QueueProcessor.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | include/private/coherence/component/util/QueueProcessor.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | include/private/coherence/component/util/QueueProcessor.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_QUEUE_PROCESSOR_HPP
#define COH_QUEUE_PROCESSOR_HPP
#include "coherence/lang.ns"
#include "coherence/util/Queue.hpp"
#include "private/coherence/component/util/Daemon.hpp"
COH_OPEN_NAMESPACE3(coherence,component,util)
using coherence::util::Queue;
/**
* This is a Daemon component that waits for items to process from a Queue.
* Whenever the Queue contains an item, the onNotify event occurs. It is
* expected that sub-classes will process onNotify as follows:
* <code>
* Object o;
* while ((o = getQueue().removeNoWait()) != null)
* { // process the item
* // ..
* }
* </code>
* <p>
* The Queue is used as the synchronization point for the daemon.
*
* @author nsa 01.18.08
*/
class COH_EXPORT QueueProcessor
: public class_spec<QueueProcessor,
extends<Daemon> >
{
// ----- constructor ----------------------------------------------------
protected:
/**
* Create a new QueueProcessor.
*/
QueueProcessor();
private:
/**
* Blocked copy constructor.
*/
QueueProcessor(const QueueProcessor&);
// ----- QueueProcessor interface ---------------------------------------
public:
/**
* Return the queue for this QueueProcessor.
*
* @return the queue for this QueueProcessor
*/
virtual Queue::Handle getQueue();
protected:
/**
* Instantiate a new queue instance.
*
* @return a new queue instance
*/
virtual Queue::Handle instantiateQueue() const;
private:
/**
* Set the Queue.
*/
virtual void setQueue(Queue::Handle hQueue);
// ----- Daemon interface -----------------------------------------------
public:
/**
* {@inheritDoc}
*/
virtual bool isNotification() const;
// ----- Object interface -----------------------------------------------
protected:
/**
* {@inheritDoc}
*/
virtual void onInit();
// ----- data members ---------------------------------------------------
protected:
/**
* The queue for this QueueProcessor
*/
FinalHandle<Queue> f_hQueue;
};
COH_CLOSE_NAMESPACE3
#endif // COH_QUEUE_PROCESSOR_HPP
| 22.142857 | 77 | 0.5375 | [
"object"
] |
1258f0c4673d0e4f966fe2ddf2a31cc6bfe53bde | 1,223 | cpp | C++ | src/process.cpp | Brendacg616/CppND-System-Monitor-Project-Updated | f7e8adda54718654518c83062777bd94de0af32b | [
"MIT"
] | null | null | null | src/process.cpp | Brendacg616/CppND-System-Monitor-Project-Updated | f7e8adda54718654518c83062777bd94de0af32b | [
"MIT"
] | null | null | null | src/process.cpp | Brendacg616/CppND-System-Monitor-Project-Updated | f7e8adda54718654518c83062777bd94de0af32b | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include "process.h"
#include "linux_parser.h"
using std::string;
using std::to_string;
using std::vector;
Process::Process(int pid):pid_(pid)
{
user_ = LinuxParser::User(pid);
command_ = LinuxParser::Command(pid);
}
int Process::Pid() { return pid_; }
float Process::CpuUtilization() const{
long uptime = LinuxParser::UpTime();
auto proc_data = LinuxParser::CpuUtilization(pid_);
float cpu_usage {0.0};
long utime = proc_data[0];
long stime = proc_data[1];
long starttime = proc_data[4];
long total_time = utime + stime;
long seconds = uptime - (starttime / sysconf(_SC_CLK_TCK));
cpu_usage = ((1.0 *total_time / sysconf(_SC_CLK_TCK))/seconds);
return cpu_usage;
}
string Process::Command() { return command_; }
string Process::Ram() { return LinuxParser::Ram(pid_); }
string Process::User() { return user_; }
long int Process::UpTime() {return LinuxParser::UpTime(pid_); }
bool Process::operator<(Process const& a) const {
bool less_than = CpuUtilization() < a.CpuUtilization();
return less_than;
}
bool Process::Compare (Process &a, Process &b) {return b<a;}
| 24.959184 | 67 | 0.686836 | [
"vector"
] |
125ce951f0e14be885d29ccfea51ffa83b72c30e | 2,187 | cpp | C++ | lib/MNISTFashion/MNISTLoader.cpp | connorosburn/MNIST-Fashion-Classifier | 0438de8ce6a8351304cfbe187e25f13e1917784e | [
"MIT"
] | 4 | 2020-04-04T22:42:13.000Z | 2020-04-07T23:20:58.000Z | lib/MNISTFashion/MNISTLoader.cpp | connorosburn/MNIST-Fashion-Classifier | 0438de8ce6a8351304cfbe187e25f13e1917784e | [
"MIT"
] | null | null | null | lib/MNISTFashion/MNISTLoader.cpp | connorosburn/MNIST-Fashion-Classifier | 0438de8ce6a8351304cfbe187e25f13e1917784e | [
"MIT"
] | null | null | null | #include "MNISTLoader.hpp"
#include <fstream>
#include <iostream>
const std::vector<DataPair>& MNISTLoader::trainingData() {
if(training.empty()) {
training = loadData("lib/MNISTFashion/train-images-idx3-ubyte", "lib/MNISTFashion/train-labels-idx1-ubyte");
}
return training;
}
const std::vector<DataPair>& MNISTLoader::testData() {
if(test.empty()) {
test = loadData("lib/MNISTFashion/t10k-images-idx3-ubyte", "lib/MNISTFashion/t10k-labels-idx1-ubyte");
}
return test;
}
std::vector<DataPair> MNISTLoader::loadData(std::string imageFileName, std::string labelFileName) {
uint32_t imageHolder;
std::ifstream imageFile;
imageFile.open(imageFileName, std::ios::binary | std::ios::in);
//reads past magic number
imageFile.read(reinterpret_cast<char*>(&imageHolder), 4);
//reads the number of examples
imageFile.read(reinterpret_cast<char*>(&imageHolder), 4);
uint32_t labelHolder;
std::ifstream labelFile;
labelFile.open(labelFileName, std::ios::binary | std::ios::in);
//reads past magic number
labelFile.read(reinterpret_cast<char*>(&labelHolder), 4);
//reads the number of examples
labelFile.read(reinterpret_cast<char*>(&labelHolder), 4);
int imageCount = ntohl(imageHolder);
int labelCount = ntohl(labelHolder);
if(imageCount != labelCount) {
throw "image and label counts must be the same";
}
//skips past the row and column counts
uint64_t garbage;
imageFile.read(reinterpret_cast<char*>(&garbage), 8);
std::vector<DataPair> data;
for(int i = 0; i < imageCount; i++) {
std::vector<std::vector<double>> image;
for(int y = 0; y < 28; y++) {
image.emplace_back();
for(int x = 0; x < 28; x++) {
unsigned char pixel;
imageFile.read(reinterpret_cast<char*>(&pixel), 1);
image.back().emplace_back(static_cast<double>(static_cast<int>(pixel))/ 255.0);
}
}
unsigned char label;
labelFile.read(reinterpret_cast<char*>(&label), 1);
data.emplace_back(static_cast<int>(label), image);
}
return data;
} | 34.171875 | 116 | 0.643347 | [
"vector"
] |
125e59aa5f3618e12ec2f49de73b140448dda29b | 10,535 | cpp | C++ | src/qt/qtbase/src/gui/kernel/qstylehints.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/gui/kernel/qstylehints.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/gui/kernel/qstylehints.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qstylehints.h>
#include <qpa/qplatformintegration.h>
#include <qpa/qplatformtheme.h>
#include <private/qguiapplication_p.h>
QT_BEGIN_NAMESPACE
static inline QVariant hint(QPlatformIntegration::StyleHint h)
{
return QGuiApplicationPrivate::platformIntegration()->styleHint(h);
}
static inline QVariant themeableHint(QPlatformTheme::ThemeHint th,
QPlatformIntegration::StyleHint ih)
{
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
const QVariant themeHint = theme->themeHint(th);
if (themeHint.isValid())
return themeHint;
}
return QGuiApplicationPrivate::platformIntegration()->styleHint(ih);
}
class QStyleHintsPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QStyleHints)
public:
inline QStyleHintsPrivate()
: m_mouseDoubleClickInterval(-1)
, m_startDragDistance(-1)
, m_startDragTime(-1)
, m_keyboardInputInterval(-1)
, m_cursorFlashTime(-1)
{}
int m_mouseDoubleClickInterval;
int m_startDragDistance;
int m_startDragTime;
int m_keyboardInputInterval;
int m_cursorFlashTime;
};
/*!
\class QStyleHints
\since 5.0
\brief The QStyleHints class contains platform specific hints and settings.
\inmodule QtGui
An object of this class, obtained from QGuiApplication, provides access to certain global
user interface parameters of the current platform.
Access is read only; typically the platform itself provides the user a way to tune these
parameters.
Access to these parameters are useful when implementing custom user interface components, in that
they allow the components to exhibit the same behaviour and feel as other components.
\sa QGuiApplication::styleHints()
*/
QStyleHints::QStyleHints()
: QObject(*new QStyleHintsPrivate(), 0)
{
}
/*!
Sets the \a mouseDoubleClickInterval.
\internal
\sa mouseDoubleClickInterval()
\since 5.3
*/
void QStyleHints::setMouseDoubleClickInterval(int mouseDoubleClickInterval)
{
Q_D(QStyleHints);
d->m_mouseDoubleClickInterval = mouseDoubleClickInterval;
}
/*!
Returns the time limit in milliseconds that distinguishes a double click
from two consecutive mouse clicks.
*/
int QStyleHints::mouseDoubleClickInterval() const
{
Q_D(const QStyleHints);
return d->m_mouseDoubleClickInterval >= 0 ?
d->m_mouseDoubleClickInterval :
themeableHint(QPlatformTheme::MouseDoubleClickInterval, QPlatformIntegration::MouseDoubleClickInterval).toInt();
}
/*!
Returns the time limit in milliseconds that activates
a press and hold.
\since 5.3
*/
int QStyleHints::mousePressAndHoldInterval() const
{
return themeableHint(QPlatformTheme::MousePressAndHoldInterval, QPlatformIntegration::MousePressAndHoldInterval).toInt();
}
/*!
Sets the \a startDragDistance.
\internal
\sa startDragDistance()
\since 5.3
*/
void QStyleHints::setStartDragDistance(int startDragDistance)
{
Q_D(QStyleHints);
d->m_startDragDistance = startDragDistance;
}
/*!
Returns the distance, in pixels, that the mouse must be moved with a button
held down before a drag and drop operation will begin.
If you support drag and drop in your application, and want to start a drag
and drop operation after the user has moved the cursor a certain distance
with a button held down, you should use this property's value as the
minimum distance required.
For example, if the mouse position of the click is stored in \c startPos
and the current position (e.g. in the mouse move event) is \c currentPos,
you can find out if a drag should be started with code like this:
\snippet code/src_gui_kernel_qapplication.cpp 6
\sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop}
*/
int QStyleHints::startDragDistance() const
{
Q_D(const QStyleHints);
return d->m_startDragDistance >= 0 ?
d->m_startDragDistance :
themeableHint(QPlatformTheme::StartDragDistance, QPlatformIntegration::StartDragDistance).toInt();
}
/*!
Sets the \a startDragDragTime.
\internal
\sa startDragTime()
\since 5.3
*/
void QStyleHints::setStartDragTime(int startDragTime)
{
Q_D(QStyleHints);
d->m_startDragTime = startDragTime;
}
/*!
Returns the time, in milliseconds, that a mouse button must be held down
before a drag and drop operation will begin.
If you support drag and drop in your application, and want to start a drag
and drop operation after the user has held down a mouse button for a
certain amount of time, you should use this property's value as the delay.
\sa startDragDistance(), {Drag and Drop}
*/
int QStyleHints::startDragTime() const
{
Q_D(const QStyleHints);
return d->m_startDragTime >= 0 ?
d->m_startDragTime :
themeableHint(QPlatformTheme::StartDragTime, QPlatformIntegration::StartDragTime).toInt();
}
/*!
Returns the limit for the velocity, in pixels per second, that the mouse may
be moved, with a button held down, for a drag and drop operation to begin.
A value of 0 means there is no such limit.
\sa startDragDistance(), {Drag and Drop}
*/
int QStyleHints::startDragVelocity() const
{
return themeableHint(QPlatformTheme::StartDragVelocity, QPlatformIntegration::StartDragVelocity).toInt();
}
/*!
Sets the \a keyboardInputInterval.
\internal
\sa keyboardInputInterval()
\since 5.3
*/
void QStyleHints::setKeyboardInputInterval(int keyboardInputInterval)
{
Q_D(QStyleHints);
d->m_keyboardInputInterval = keyboardInputInterval;
}
/*!
Returns the time limit, in milliseconds, that distinguishes a key press
from two consecutive key presses.
*/
int QStyleHints::keyboardInputInterval() const
{
Q_D(const QStyleHints);
return d->m_keyboardInputInterval >= 0 ?
d->m_keyboardInputInterval :
themeableHint(QPlatformTheme::KeyboardInputInterval, QPlatformIntegration::KeyboardInputInterval).toInt();
}
/*!
Returns the rate, in events per second, in which additional repeated key
presses will automatically be generated if a key is being held down.
*/
int QStyleHints::keyboardAutoRepeatRate() const
{
return themeableHint(QPlatformTheme::KeyboardAutoRepeatRate, QPlatformIntegration::KeyboardAutoRepeatRate).toInt();
}
/*!
Sets the \a cursorFlashTime.
\internal
\sa cursorFlashTime()
\since 5.3
*/
void QStyleHints::setCursorFlashTime(int cursorFlashTime)
{
Q_D(QStyleHints);
d->m_cursorFlashTime = cursorFlashTime;
}
/*!
Returns the text cursor's flash (blink) time in milliseconds.
The flash time is the time used to display, invert and restore the
caret display. Usually the text cursor is displayed for half the cursor
flash time, then hidden for the same amount of time.
*/
int QStyleHints::cursorFlashTime() const
{
Q_D(const QStyleHints);
return d->m_cursorFlashTime >= 0 ?
d->m_cursorFlashTime :
themeableHint(QPlatformTheme::CursorFlashTime, QPlatformIntegration::CursorFlashTime).toInt();
}
/*!
Returns \c true if the platform defaults to windows being fullscreen,
otherwise \c false.
\note The platform may still choose to show certain windows non-fullscreen,
such as popups or dialogs. This method only returns the default behavior.
\sa QWindow::show()
*/
bool QStyleHints::showIsFullScreen() const
{
return hint(QPlatformIntegration::ShowIsFullScreen).toBool();
}
/*!
Returns the time, in milliseconds, a typed letter is displayed unshrouded
in a text input field in password mode.
*/
int QStyleHints::passwordMaskDelay() const
{
return themeableHint(QPlatformTheme::PasswordMaskDelay, QPlatformIntegration::PasswordMaskDelay).toInt();
}
/*!
Returns the character used to mask the characters typed into text input
fields in password mode.
*/
QChar QStyleHints::passwordMaskCharacter() const
{
return themeableHint(QPlatformTheme::PasswordMaskCharacter, QPlatformIntegration::PasswordMaskCharacter).toChar();
}
/*!
Returns the gamma value used in font smoothing.
*/
qreal QStyleHints::fontSmoothingGamma() const
{
return hint(QPlatformIntegration::FontSmoothingGamma).toReal();
}
/*!
Returns \c true if right-to-left writing direction is enabled,
otherwise \c false.
*/
bool QStyleHints::useRtlExtensions() const
{
return hint(QPlatformIntegration::UseRtlExtensions).toBool();
}
/*!
Returns \c true if focus objects (line edits etc) should receive
input focus after a touch/mouse release. This is normal behavior on
touch platforms. On desktop platforms, the standard is to set
focus already on touch/mouse press.
*/
bool QStyleHints::setFocusOnTouchRelease() const
{
return hint(QPlatformIntegration::SetFocusOnTouchRelease).toBool();
}
QT_END_NAMESPACE
| 31.636637 | 125 | 0.723588 | [
"object"
] |
1260826465a216f976e99dc992caacaa924aa0c9 | 613 | cpp | C++ | vm/builtin/methodvisibility.cpp | marnen/rubinius | 05b3f9789d01bada0604a7f09921c956bc9487e7 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T16:58:14.000Z | 2016-05-08T16:58:14.000Z | vm/builtin/methodvisibility.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | vm/builtin/methodvisibility.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | #include "vm/vm.hpp"
#include "vm/object_utils.hpp"
#include "builtin/methodvisibility.hpp"
#include "builtin/symbol.hpp"
namespace rubinius {
MethodVisibility* MethodVisibility::create(STATE) {
return (MethodVisibility*)state->new_object(G(cmethod_vis));
}
void MethodVisibility::Info::show(STATE, Object* self, int level) {
MethodVisibility* mv = as<MethodVisibility>(self);
class_header(state, self);
indent_attribute(++level, "visibility"); mv->visibility()->show(state, level);
indent_attribute(level, "method"); mv->method()->show(state, level);
close_body(level);
}
};
| 27.863636 | 82 | 0.711256 | [
"object"
] |
1260fa9e1e62464f2aac96aabd9641a7ca0d1d08 | 62,688 | cpp | C++ | src/spectrast/SpectraSTCreateParams.cpp | lkszmn/spectrast | f028aafcea5045e3cb5837c337f4fa90c90993f3 | [
"Zlib",
"MIT"
] | null | null | null | src/spectrast/SpectraSTCreateParams.cpp | lkszmn/spectrast | f028aafcea5045e3cb5837c337f4fa90c90993f3 | [
"Zlib",
"MIT"
] | null | null | null | src/spectrast/SpectraSTCreateParams.cpp | lkszmn/spectrast | f028aafcea5045e3cb5837c337f4fa90c90993f3 | [
"Zlib",
"MIT"
] | 3 | 2019-10-30T13:08:05.000Z | 2022-02-22T19:16:31.000Z | #include "SpectraSTCreateParams.hpp"
#include "SpectraSTLog.hpp"
#include "SpectraSTConstants.hpp"
#include "FileUtils.hpp"
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdlib.h>
/*
Program : Spectrast
Author : Henry Lam <hlam@systemsbiology.org>
Date : 03.06.06
Copyright (C) 2006 Henry Lam
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
Henry Lam
Institute for Systems Biology
401 Terry Avenue North
Seattle, WA 98109 USA
hlam@systemsbiology.org
Institute for Systems Biology, hereby disclaims all copyright interest
in Spectrast written by Henry Lam.
*/
/* Class: SpectraSTCreateParams
*
* Manages the create parameters.
*
*/
using namespace std;
extern bool g_quiet;
extern SpectraSTLog* g_log;
// constructor
SpectraSTCreateParams::SpectraSTCreateParams() :
m_options() {
setDefault();
}
// copy constructor
SpectraSTCreateParams::SpectraSTCreateParams(SpectraSTCreateParams& s) {
(*this) = s;
}
// assignment operator
SpectraSTCreateParams& SpectraSTCreateParams::operator=(SpectraSTCreateParams& s) {
this->paramsFileName = s.paramsFileName;
this->outputFileName = s.outputFileName;
this->binaryFormat = s.binaryFormat;
this->reannotatePeaks = s.reannotatePeaks;
this->remark = s.remark;
this->writeDtaFiles = s.writeDtaFiles;
this->writeMgfFile = s.writeMgfFile;
this->writePAIdent = s.writePAIdent;
this->filterCriteria = s.filterCriteria;
this->useProbTable = s.useProbTable;
this->useProteinList = s.useProteinList;
this->printMRMTable = s.printMRMTable;
this->minimumMRMQ3MZ = s.minimumMRMQ3MZ;
this->maximumMRMQ3MZ = s.maximumMRMQ3MZ;
this->removeDecoyProteins = s.removeDecoyProteins;
this->minimumProbabilityToInclude = s.minimumProbabilityToInclude;
this->maximumFDRToInclude = s.maximumFDRToInclude;
this->rawSpectraNoiseThreshold = s.rawSpectraNoiseThreshold;
this->rawSpectraMaxDynamicRange = s.rawSpectraMaxDynamicRange;
this->setDeamidatedNXST = s.setDeamidatedNXST;
this->datasetName = s.datasetName;
this->addMzXMLFileToDatasetName = s.addMzXMLFileToDatasetName;
this->minimumDeltaCnToInclude = s.minimumDeltaCnToInclude;
this->minimumNumAAToInclude = s.minimumNumAAToInclude;
this->minimumNumPeaksToInclude = s.minimumNumPeaksToInclude;
this->maximumMassDiffToInclude = s.maximumMassDiffToInclude;
this->centroidPeaks = s.centroidPeaks;
this->setFragmentation = s.setFragmentation;
this->skipRawAnnotation = s.skipRawAnnotation;
this->evaluatePhosphoSiteAssignment = s.evaluatePhosphoSiteAssignment;
this->keepRawIntensities = s.keepRawIntensities;
this->bracketSpectra = s.bracketSpectra;
this->mergeBracket = s.mergeBracket;
this->combineAction = s.combineAction;
this->buildAction = s.buildAction;
this->plotSpectra = s.plotSpectra;
this->reduceSpectrum = s.reduceSpectrum;
this->minimumNumReplicates = s.minimumNumReplicates;
this->peakQuorum = s.peakQuorum;
this->maximumNumReplicates = s.maximumNumReplicates;
this->maximumNumPeaksUsed = s.maximumNumPeaksUsed;
this->removeDissimilarReplicates = s.removeDissimilarReplicates;
this->replicateWeight = s.replicateWeight;
this->maximumNumPeaksKept = s.maximumNumPeaksKept;
this->recordRawSpectra = s.recordRawSpectra;
this->useBayesianDenoiser = s.useBayesianDenoiser;
this->trainBayesianDenoiser = s.trainBayesianDenoiser;
this->denoiserMinimumSignalProb = s.denoiserMinimumSignalProb;
this->denoiserParamFile = s.denoiserParamFile;
this->qualityLevelRemove = s.qualityLevelRemove;
this->qualityLevelMark = s.qualityLevelMark;
this->qualityPenalizeSingletons = s.qualityPenalizeSingletons;
this->qualityImmuneProbThreshold = s.qualityImmuneProbThreshold;
this->qualityImmuneMultipleEngines = s.qualityImmuneMultipleEngines;
this->decoyConcatenate = s.decoyConcatenate;
this->decoySizeRatio = s.decoySizeRatio;
this->decoyPrecursorSwap = s.decoyPrecursorSwap;
this->normalizeRTWithLandmarks = s.normalizeRTWithLandmarks;
this->normalizeRTLinearRegression = s.normalizeRTLinearRegression;
this->allowableModTokens = s.allowableModTokens;
this->refreshDatabase = s.refreshDatabase;
this->refreshDeleteUnmapped = s.refreshDeleteUnmapped;
this->refreshDeleteMultimapped = s.refreshDeleteMultimapped;
this->refreshTrypticOnly = s.refreshTrypticOnly;
this->unidentifiedClusterIndividualRun = s.unidentifiedClusterIndividualRun;
this->unidentifiedClusterMinimumDot = s.unidentifiedClusterMinimumDot;
this->unidentifiedRemoveSinglyCharged = s.unidentifiedRemoveSinglyCharged;
this->unidentifiedMinimumNumPeaksToInclude = s.unidentifiedMinimumNumPeaksToInclude;
this->unidentifiedSingletonXreaThreshold = s.unidentifiedSingletonXreaThreshold;
this->m_options.clear();
for (vector<string>::iterator i = s.m_options.begin(); i != s.m_options.end(); i++) {
this->m_options.push_back(*i);
}
return (*this);
}
// destructor
SpectraSTCreateParams::~SpectraSTCreateParams() {
}
// finalizeOptions - go through the options stored in m_options and actually set them.
void SpectraSTCreateParams::finalizeOptions() {
for (vector<string>::iterator i = m_options.begin(); i != m_options.end(); i++) {
double f = -1.0;
int k = 0;
bool valid = false;
string extension;
char optionType = (*i)[0];
string optionValue = (*i).length() > 1 ? (*i).substr(1) : "";
// all the command line options. note that if the option F (read from params file) is specified,
// it should be the first option to be processed (see addOption() method). this way, the options
// set in the params file can be overridden by other command line options.
switch (optionType) {
// GENERAL
case 'F' :
if (optionValue.empty()) {
// no params file name specified. use default
paramsFileName = DEFAULT_CREATE_PARAMS_FILE;
readFromFile();
valid = true;
} else {
// fixpath(optionValue);
paramsFileName = optionValue;
readFromFile();
valid = true;
}
if (!g_quiet) {
cout << "Create parameter file loaded: \"" << paramsFileName << "\"." << endl;
}
break;
case 'N' :
if (!optionValue.empty()) {
// fixpath(optionValue);
outputFileName = optionValue;
valid = true;
}
break;
case 'm' :
if (!optionValue.empty()) {
remark = optionValue;
valid = true;
}
break;
case 'f' :
if (!optionValue.empty()) {
filterCriteria = optionValue;
valid = true;
}
break;
case 'T' :
if (!optionValue.empty()) {
// fixpath(optionValue);
useProbTable = optionValue;
makeFullPath(useProbTable);
valid = true;
} else {
valid = false;
}
break;
case 'O' :
if (!optionValue.empty()) {
// fixpath(optionValue);
useProteinList = optionValue;
makeFullPath(useProteinList);
valid = true;
} else {
valid = false;
}
break;
case 'M' :
if (optionValue.empty()) {
printMRMTable = "DEFAULT";
valid = true;
} else if (optionValue == "!") {
printMRMTable = "";
valid = true;
} else {
printMRMTable = optionValue;
valid = true;
}
break;
// PEPXML
case 'n' :
if (!optionValue.empty()) {
datasetName = optionValue;
valid = true;
}
break;
case 'o' :
if (optionValue.empty()) {
addMzXMLFileToDatasetName = true;
valid = true;
} else if (optionValue == "!") {
addMzXMLFileToDatasetName = false;
valid = true;
}
break;
case 'P' :
f = atof(optionValue.c_str());
if (f >= 0.0 && f <= 1.000001) {
minimumProbabilityToInclude = f;
valid = true;
}
break;
case 'q' :
f = atof(optionValue.c_str());
if (f >= 0.0 && f <= 1.0) {
maximumFDRToInclude = f;
valid = true;
}
break;
case 'g' :
if (optionValue.empty()) {
setDeamidatedNXST = true;
valid = true;
} else if (optionValue == "!") {
setDeamidatedNXST = false;
valid = true;
}
break;
case 'I' :
if (!optionValue.empty()) {
setFragmentation = optionValue;
valid = true;
}
break;
// LIBRARY MANIPULATION
case 'J' :
if (optionValue[0] == 'U') {
combineAction = "UNION";
valid = true;
} else if (optionValue[0] == 'I') {
combineAction = "INTERSECT";
valid = true;
} else if (optionValue[0] == 'S') {
combineAction = "SUBTRACT";
valid = true;
} else if (optionValue[0] == 'H') {
combineAction = "SUBTRACT_HOMOLOGS";
valid = true;
} else if (optionValue[0] == 'A') {
combineAction = "APPEND";
valid = true;
}
break;
case 'A' :
if (optionValue[0] == 'B') {
buildAction = "BEST_REPLICATE";
valid = true;
} else if (optionValue[0] == 'C') {
buildAction = "CONSENSUS";
valid = true;
} else if (optionValue[0] == 'Q') {
buildAction = "QUALITY_FILTER";
valid = true;
} else if (optionValue[0] == 'D') {
buildAction = "DECOY";
valid = true;
} else if (optionValue[0] == 'N') {
buildAction = "SORT_BY_NREPS";
valid = true;
} else if (optionValue[0] == 'M') {
buildAction = "USER_SPECIFIED_MODS";
valid = true;
} else if (optionValue[0] == 'S') {
buildAction = "SIMILARITY_CLUSTERING";
valid = true;
} else if (optionValue[0] == 'E') {
buildAction = "SEMI_EMPIRICAL_SPLIB";
valid = true;
}
break;
case 'Q' :
k = atoi(optionValue.c_str());
if (k >= 1) {
reduceSpectrum = k;
valid = true;
}
break;
// CONSENSUS
case 'r' :
k = atoi(optionValue.c_str());
if (k > 0) {
minimumNumReplicates = k;
valid = true;
}
break;
// QUALITY FILTER
case 'L' :
k = atoi(optionValue.c_str());
if (k >= 0 && k <= 5) {
qualityLevelRemove = k;
valid = true;
}
break;
case 'l' :
k = atoi(optionValue.c_str());
if (k >= 0 && k <= 5) {
qualityLevelMark = k;
valid = true;
}
break;
// DECOY
case 'c' :
if (optionValue.empty()) {
decoyConcatenate = true;
valid = true;
} else if (optionValue == "!") {
decoyConcatenate = false;
valid = true;
}
break;
case 'y' :
k = atoi(optionValue.c_str());
if (k >= 0) {
decoySizeRatio = k;
valid = true;
}
break;
// REFRESH PROTEIN MAPPINGS
case 'u' :
if (optionValue.empty()) {
refreshDeleteUnmapped = true;
valid = true;
} else if (optionValue == "!") {
refreshDeleteUnmapped = false;
valid = true;
}
break;
case 'd' :
if (optionValue.empty()) {
refreshDeleteMultimapped = true;
valid = true;
} else if (optionValue == "!") {
refreshDeleteMultimapped = false;
valid = true;
}
break;
case 'D' :
if (!optionValue.empty()) {
// fixpath(optionValue);
refreshDatabase = optionValue;
makeFullPath(refreshDatabase);
valid = true;
} else {
valid = false;
}
break;
case 'x' :
allowableModTokens = optionValue;
valid = true;
break;
case '_' :
finalizeAdvancedOption(optionValue);
valid = true;
break;
case 'a' :
case 'b' :
// case 'D' :
case 't' :
case 'v' :
// case 'u' :
case 's' :
case 'j' :
case 'z' :
case 'w' :
case 'k' :
case 'p' :
// case 'd' :
case '1' :
case 'i' :
case 'e' :
if (!g_quiet) {
cout << "Option \"-c" << optionType << "\" is deprecated. Ignored. ";
cout << "Type \"spectrast -c_\" to see if an equivalent advanced option is available." << endl;
}
valid = true;
break;
default :
if (!g_quiet) cout << "Option \"-c" << optionType << "\" is undefined. Ignored. ";
valid = true;
break;
}
if (!valid && !g_quiet) {
cout << "Invalid value for the \"-c" << optionType << "\" in the command line. Ignored." << endl;
}
}
}
void SpectraSTCreateParams::finalizeAdvancedOption(string option) {
if (option.length() < 3) {
cout << "Advanced option \"-c_" << option << " is undefined. Ignored." << endl;
return;
}
double f = -1.0;
int k = 0;
bool valid = false;
string optionType = option.substr(0, 3);
string optionValue = option.substr(3);
if (optionType == "ANN") {
if (optionValue.empty()) {
reannotatePeaks = true;
valid = true;
} else if (optionValue == "!") {
reannotatePeaks = false;
valid = true;
}
} else if (optionType == "BIN") {
if (optionValue.empty()) {
binaryFormat = true;
valid = true;
} else if (optionValue == "!") {
binaryFormat = false;
valid = true;
}
} else if (optionType == "DTA") {
if (optionValue.empty()) {
writeDtaFiles = true;
valid = true;
} else if (optionValue == "!") {
writeDtaFiles = false;
valid = true;
}
} else if (optionType == "MGF") {
if (optionValue.empty()) {
writeMgfFile = true;
valid = true;
} else if (optionValue == "!") {
writeMgfFile = false;
valid = false;
}
} else if (optionType == "PAI") {
if (optionValue.empty()) {
writePAIdent = true;
valid = true;
} else if (optionValue == "!") {
writePAIdent = false;
valid = false;
}
} else if (optionType == "Q3L") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0) {
minimumMRMQ3MZ = f;
valid = true;
}
}
} else if (optionType == "Q3H") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0) {
maximumMRMQ3MZ = f;
valid = true;
}
}
} else if (optionType == "RDY") {
removeDecoyProteins = optionValue;
valid = true;
} else if (optionType == "RNT") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0) {
rawSpectraNoiseThreshold = f;
valid = true;
}
}
} else if (optionType == "RDR") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 1.0) {
rawSpectraMaxDynamicRange = f;
valid = true;
}
}
} else if (optionType == "DCN") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0) {
minimumDeltaCnToInclude = f;
valid = true;
}
}
} else if (optionType == "NAA") {
if (!optionValue.empty()) {
k = atoi(optionValue.c_str());
if (k >= 0) {
minimumNumAAToInclude = k;
valid = true;
}
}
} else if (optionType == "NPK") {
if (!optionValue.empty()) {
k = atoi(optionValue.c_str());
if (k >= 0) {
minimumNumPeaksToInclude = k;
valid = true;
}
}
} else if (optionType == "MDF") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0) {
maximumMassDiffToInclude = f;
valid = true;
}
}
} else if (optionType == "RWI") {
if (optionValue.empty()) {
keepRawIntensities = true;
valid = true;
} else if (optionValue == "!") {
keepRawIntensities = false;
valid = true;
}
} else if (optionType == "BRK") {
if (optionValue.empty()) {
bracketSpectra = true;
valid = true;
} else if (optionValue == "!") {
bracketSpectra = false;
valid = true;
}
} else if (optionType == "BRM") {
if (optionValue.empty()) {
mergeBracket = true;
valid = true;
} else if (optionValue == "!") {
mergeBracket = false;
valid = true;
}
} else if (optionType == "PLT") {
if (optionValue.empty()) {
plotSpectra = "ALL";
valid = true;
} else if (optionValue == "!") {
plotSpectra = "";
valid = true;
} else {
plotSpectra = optionValue;
valid = true;
}
} else if (optionType == "CEN") {
if (optionValue.empty()) {
centroidPeaks = true;
valid = true;
} else if (optionValue == "!") {
centroidPeaks = false;
valid = true;
}
} else if (optionType == "XAN") {
if (optionValue.empty()) {
skipRawAnnotation = true;
valid = true;
} else if (optionValue == "!") {
skipRawAnnotation = false;
valid = true;
}
} else if (optionType == "WGT") {
if (!optionValue.empty()) {
if (optionValue[0] == 'X') {
replicateWeight = "XCORR";
valid = true;
} else if (optionValue[0] == 'P') {
replicateWeight = "PROB";
valid = true;
} else if (optionValue[0] == 'S') {
replicateWeight = "SN";
valid = true;
} else if (optionValue[0] == 'N') {
replicateWeight = "NONE";
valid = true;
} else if (optionValue[0] == 'I') {
replicateWeight = "INTP";
valid = true;
}
}
} else if (optionType == "DIS") {
if (optionValue.empty()) {
removeDissimilarReplicates = true;
valid = true;
} else if (optionValue == "!") {
removeDissimilarReplicates = false;
valid = true;
}
} else if (optionType == "QUO") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (k >= 0.0 && k <= 1.0) {
peakQuorum = f;
valid = true;
}
}
} else if (optionType == "XPU") {
if (!optionValue.empty()) {
k = atoi(optionValue.c_str());
if (k > 0) {
maximumNumPeaksUsed = k;
valid = true;
}
}
} else if (optionType == "XNR") {
if (!optionValue.empty()) {
k = atoi(optionValue.c_str());
if (k > 1) {
maximumNumReplicates = k;
valid = true;
}
}
} else if (optionType == "XPK") {
if (!optionValue.empty()) {
k = atoi(optionValue.c_str());
if (k >= 0) {
maximumNumPeaksKept = k;
valid = true;
}
}
} else if (optionType == "RRS") {
if (optionValue.empty()) {
recordRawSpectra = true;
valid = true;
} else if (optionValue == "!") {
recordRawSpectra = false;
valid = true;
}
} else if (optionType == "BDU") {
if (optionValue.empty()) {
useBayesianDenoiser = true;
valid = true;
} else if (optionValue == "!") {
useBayesianDenoiser = false;
valid = true;
}
} else if (optionType == "BDT") {
if (optionValue.empty()) {
trainBayesianDenoiser = true;
valid = true;
} else if (optionValue == "!") {
trainBayesianDenoiser = false;
valid = true;
}
} else if (optionType == "BDP") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0 && f <= 1.0) {
denoiserMinimumSignalProb = f;
valid = true;
}
}
} else if (optionType == "BDF") {
if (!optionValue.empty()) {
// fixpath(optionValue);
denoiserParamFile = optionValue;
makeFullPath(denoiserParamFile);
}
valid = true;
} else if (optionType == "QP1") {
if (optionValue.empty()) {
qualityPenalizeSingletons = true;
valid = true;
} else if (optionValue == "!") {
qualityPenalizeSingletons = false;
valid = true;
}
} else if (optionType == "QIP") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0) {
qualityImmuneProbThreshold = f;
valid = true;
}
}
} else if (optionType == "QIE") {
if (optionValue.empty()) {
qualityImmuneMultipleEngines = true;
valid = true;
} else if (optionValue == "!") {
qualityImmuneMultipleEngines = false;
valid = true;
}
} else if (optionType == "RTO") {
if (optionValue.empty()) {
refreshTrypticOnly = true;
valid = true;
} else if (optionValue == "!") {
refreshTrypticOnly = false;
valid = true;
}
} else if (optionType == "IRT") {
if (!optionValue.empty()) {
normalizeRTWithLandmarks = optionValue;
makeFullPath(normalizeRTWithLandmarks);
valid = true;
} else {
valid = false;
}
} else if (optionType == "IRR") {
if (optionValue.empty()) {
normalizeRTLinearRegression = true;
valid = true;
} else if (optionValue == "!") {
normalizeRTLinearRegression = false;
valid = true;
}
} else if (optionType == "PHO") {
if (optionValue.empty()) {
evaluatePhosphoSiteAssignment = true;
valid = true;
} else if (optionValue == "!") {
evaluatePhosphoSiteAssignment = false;
valid = true;
}
} else if (optionType == "UCR") {
if (optionValue.empty()) {
unidentifiedClusterIndividualRun = true;
valid = true;
} else if (optionValue == "!") {
unidentifiedClusterIndividualRun = false;
valid = true;
}
} else if (optionType == "UCD") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0 && f <= 1.0) {
unidentifiedClusterMinimumDot = f;
valid = true;
}
}
} else if (optionType == "UX1") {
if (optionValue.empty()) {
unidentifiedRemoveSinglyCharged = true;
valid = true;
} else {
unidentifiedRemoveSinglyCharged = false;
valid = true;
}
} else if (optionType == "UNP") {
if (!optionValue.empty()) {
k = atoi(optionValue.c_str());
if (k >= 1) {
unidentifiedMinimumNumPeaksToInclude = k;
valid = true;
}
}
} else if (optionType == "USX") {
if (!optionValue.empty()) {
f = atof(optionValue.c_str());
if (f >= 0.0 && f <= 1.0) {
unidentifiedSingletonXreaThreshold = f;
valid = true;
}
}
} else if (optionType == "DPS") {
if (optionValue.empty()) {
decoyPrecursorSwap = true;
valid = true;
} else if (optionValue == "!") {
decoyPrecursorSwap = false;
valid = true;
}
} else if (optionType == "OTL") {
predictionOrigTargetFileName = optionValue;
valid = true;
} else if (optionType == "PEP") {
predictionTargetPeptidesFileName = optionValue;
valid = true;
} else if (optionType == "SNP") {
allowableSNP = optionValue;
valid = true;
} else if (optionType == "PTM") {
allowableMutatedModifications = optionValue;
valid = true;
} else if (optionType == "DST"){
allowablePredictionDistance = atoi(optionValue.c_str());
valid = true;
} else {
if (!g_quiet) cout << "Advanced option \"-c_" << option << " is undefined. Ignored." << endl;
valid = true;
}
if (!valid && !g_quiet) {
cout << "Invalid value for advanced option \"-c_" << option << ". Ignored." << endl;
}
}
// addOption - add an option to the list of options
bool SpectraSTCreateParams::addOption(string option) {
// to allow command-line override of options set by reading a params file (-cF option),
// options are first read from the file, and then the command-line options are allowed
// to overwrite them. Hence, we want to make sure the -cF option (if any) is the first
// to be executed.
// check if it's the -cF option, in which case, put as the first option
if (option.length() == 0) {
return (true);
} else if (option[0] == 'F') {
m_options.insert(m_options.begin(), option);
return (true);
} else {
// else, put at the back
if (isExpectingArg(option)) {
return (false);
} else {
m_options.push_back(option);
return (true);
}
}
}
bool SpectraSTCreateParams::isExpectingArg(string option) {
return (option == "N" || option == "n" || option == "m" || option == "f" || option == "T" || option == "O" ||
option == "D" || option == "I");
}
// setDefault - sets the defaults for all options
void SpectraSTCreateParams::setDefault() {
// Defaults for all options - see SpectraSTCreateParams::printUsage() for more information
// GENERAL
paramsFileName = DEFAULT_CREATE_PARAMS_FILE;
outputFileName = "";
reannotatePeaks = false;
binaryFormat = true;
writeDtaFiles = false;
writeMgfFile = false;
writePAIdent = false;
remark = "";
useProbTable = "";
useProteinList= "";
printMRMTable = "";
minimumMRMQ3MZ = 200.0;
maximumMRMQ3MZ = 1400.0;
removeDecoyProteins = "";
setFragmentation = "";
// PEPXML
minimumProbabilityToInclude = 0.9;
maximumFDRToInclude = 9999.0; // not using by default
datasetName = "";
addMzXMLFileToDatasetName = false;
rawSpectraNoiseThreshold = 0.0;
rawSpectraMaxDynamicRange = 100000.0;
setDeamidatedNXST = false;
minimumDeltaCnToInclude = 0.0;
minimumNumAAToInclude = 6;
minimumNumPeaksToInclude = 10;
maximumMassDiffToInclude = 9999.0;
centroidPeaks = false;
skipRawAnnotation = false;
evaluatePhosphoSiteAssignment = false;
keepRawIntensities = false;
bracketSpectra = false;
mergeBracket = false;
// LIBRARY MANIPULATION
filterCriteria = "";
combineAction = "UNION";
buildAction = "";
plotSpectra = "";
reduceSpectrum = 0;
// CONSENSUS
minimumNumReplicates = 1;
peakQuorum = 0.6;
maximumNumPeaksUsed = 300;
maximumNumReplicates = 100;
removeDissimilarReplicates = true;
replicateWeight = "SN";
maximumNumPeaksKept = 150;
recordRawSpectra = false;
// DENOISER
useBayesianDenoiser = false;
trainBayesianDenoiser = false;
denoiserMinimumSignalProb = 0.0;
denoiserParamFile = "";
// QUALITY FILTER
qualityLevelRemove = 2;
qualityLevelMark = 5;
qualityPenalizeSingletons = true;
qualityImmuneProbThreshold = 0.999;
qualityImmuneMultipleEngines = true;
// DECOY
decoyConcatenate = false;
decoySizeRatio = 1;
decoyPrecursorSwap = false;
// REFRESH PROTEIN MAPPINGS
refreshDatabase = "";
refreshDeleteUnmapped = false;
refreshDeleteMultimapped = false;
refreshTrypticOnly = false;
// USER SPECIFIED MODIFICATIONS
allowableModTokens = "";
predictionOrigTargetFileName = "";
predictionTargetPeptidesFileName = "";
allowableSNP = "ALL";
allowableMutatedModifications = "ALL";
allowablePredictionDistance = 1;
// UNIDENTIFIED LIBRARIES
unidentifiedClusterIndividualRun = false;
unidentifiedClusterMinimumDot = 0.7;
unidentifiedRemoveSinglyCharged = true;
unidentifiedMinimumNumPeaksToInclude = 35;
unidentifiedSingletonXreaThreshold = 0.6;
// new features
}
// readFromFile - loads the options from the params file
// the params file has the format
// <param name> = <param value> (the '=' can be replaced by ':' or just blank space)
void SpectraSTCreateParams::readFromFile() {
if (paramsFileName.empty()) {
return;
}
ifstream fin;
if (!myFileOpen(fin, paramsFileName)) {
g_log->error("CREATE", "Cannot open PARAMS file \"" + paramsFileName + "\" for reading Create params. Using all defaults.");
setDefault();
return;
}
string line("");
while (nextLine(fin, line, "", "")) {
if (line == "_EOF_") {
return;
}
string::size_type pos = 0;
string param = nextToken(line, 0, pos, " #\t\r\n=:");
string value = nextToken(line, pos, pos, " #\t\r\n", " \t\r\n=:");
double f;
int k;
bool valid = false;
if (param.empty()) continue;
// GENERAL
if (param == "outputFileName") {
if (!value.empty()) {
// fixpath(value);
outputFileName = value;
valid = true;
}
} else if (param == "reannotatePeaks") {
reannotatePeaks = (value == "true");
valid = true;
} else if (param == "binaryFormat") {
binaryFormat = (value == "true");
valid = true;
} else if (param == "remark") {
if (!value.empty()) {
remark = value;
valid = true;
}
} else if (param == "writeDtaFiles") {
writeDtaFiles = (value == "true");
valid = true;
} else if (param == "writeMgfFile") {
writeMgfFile = (value == "true");
valid = true;
} else if (param == "writePAIdent") {
writePAIdent = (value == "true");
valid = true;
} else if (param == "filterCriteria") {
if (value[0] == '\"' && value[value.length() - 1] == '\"') {
filterCriteria = value.substr(1, value.length() - 2);
valid = true;
} else if (value[0] == '\'' && value[value.length() - 1] == '\'') {
filterCriteria = value.substr(1, value.length() - 2);
valid = true;
} else {
valid = false;
}
} else if (param == "useProbTable") {
if (!value.empty()) {
// fixpath(value);
useProbTable = value;
valid = true;
}
} else if (param == "useProteinList") {
if (!value.empty()) {
// fixpath(value);
useProteinList = value;
valid = true;
}
} else if (param == "printMRMTable") {
printMRMTable = value;
valid = true;
} else if (param == "minimumMRMQ3MZ") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0) {
minimumMRMQ3MZ = f;
valid = true;
}
}
} else if (param == "maximumMRMQ3MZ") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0) {
maximumMRMQ3MZ = f;
valid = true;
}
}
} else if (param == "removeDecoyProteins") {
if (!value.empty()) {
removeDecoyProteins = value;
valid = true;
}
} else if (param == "setFragmentation") {
if (!value.empty()) {
setFragmentation = value;
valid = true;
}
// PEPXML
} else if (param == "minimumProbabilityToInclude") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0 && f <= 1.0) {
minimumProbabilityToInclude = f;
valid = true;
}
}
} else if (param == "maximumFDRToInclude") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0 && f <= 1.0) {
maximumFDRToInclude = f;
valid = true;
}
}
} else if (param == "rawSpectraNoiseThreshold") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0) {
rawSpectraNoiseThreshold = f;
valid = true;
}
}
} else if (param == "rawSpectraMaxDynamicRange") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 1.0) {
rawSpectraMaxDynamicRange = f;
valid = true;
}
}
} else if (param == "datasetName") {
if (!value.empty()) {
datasetName = value;
valid = true;
}
} else if (param == "setDeamidatedNXST") {
setDeamidatedNXST = (value == "true");
valid = true;
} else if (param == "minimumDeltaCnToInclude") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0) {
minimumDeltaCnToInclude = f;
valid = true;
}
}
} else if (param == "minimumNumAAToInclude") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0) {
minimumNumAAToInclude = k;
valid = true;
}
}
} else if (param == "minimumNumPeaksToInclude") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0) {
minimumNumPeaksToInclude = k;
valid = true;
}
}
} else if (param == "maximumMassDiffToInclude") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0) {
maximumMassDiffToInclude = f;
valid = true;
}
}
} else if (param == "centroidPeaks") {
centroidPeaks = (value == "true");
valid = true;
} else if (param == "skipRawAnnotation") {
skipRawAnnotation = (value == "true");
valid = true;
} else if (param == "evaluatePhosphoSiteAssignment") {
evaluatePhosphoSiteAssignment = (value == "true");
valid = true;
} else if (param == "keepRawIntensities") {
keepRawIntensities = (value == "true");
valid = true;
} else if (param == "bracketSpectra") {
bracketSpectra = (value == "true");
valid = true;
} else if (param == "mergeBracket") {
mergeBracket = (value == "true");
valid = true;
// LIBRARY MANIPULATION
} else if (param == "combineAction") {
if (value == "UNION" || value == "INTERSECT" || value == "SUBTRACT" || value == "SUBTRACT_HOMOLOG" || value == "APPEND") {
combineAction = value;
valid = true;
}
} else if (param == "buildAction") {
if (value == "BEST_REPLICATE" || value == "CONSENSUS" || value == "QUALITY_FILTER" ||
value == "DECOY" || value == "SORT_BY_NREPS" || value == "USER_SPECIFIED_MODS" ||
value == "SIMILARITY_CLUSTERING") {
buildAction = value;
valid = true;
}
} else if (param == "plotSpectra") {
plotSpectra = value;
valid = true;
} else if (param == "reduceSpectrum") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0) {
reduceSpectrum = k;
valid = true;
}
}
// CONSENSUS
} else if (param == "minimumNumReplicates") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k > 0) {
minimumNumReplicates = k;
valid = true;
}
}
} else if (param == "peakQuorum") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0 && f <= 1.0) {
peakQuorum = f;
valid = true;
}
}
} else if (param == "maximumNumPeaksKept") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0) {
maximumNumPeaksKept = k;
valid = true;
}
}
} else if (param == "replicateWeight") {
if (value == "XCORR" || value == "PROB" || value == "SN" || value == "INTP" || value == "NONE") {
replicateWeight = value;
valid = true;
}
} else if (param == "removeDissimilarReplicates") {
removeDissimilarReplicates = (value == "true");
valid = true;
} else if (param == "maximumNumReplicates") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k > 1) {
maximumNumReplicates = k;
valid = true;
}
}
} else if (param == "maximumNumPeaksUsed") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k > 0) {
maximumNumPeaksUsed = k;
valid = true;
}
}
} else if (param == "recordRawSpectra") {
recordRawSpectra = (value == "true");
valid = true;
// DENOISER
} else if (param == "useBayesianDenoiser") {
useBayesianDenoiser = (value == "true");
valid = true;
} else if (param == "trainBayesianDenoiser") {
trainBayesianDenoiser = (value == "true");
valid = true;
} else if (param == "denoiserMinimumSignalProb") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0 && f <= 1.0) {
denoiserMinimumSignalProb = f;
valid = true;
}
}
} else if (param == "denoiserParamFile") {
if (!value.empty()) {
// fixpath(value);
denoiserParamFile = value;
makeFullPath(denoiserParamFile);
}
valid = true;
// QUALITY FILTER
} else if (param == "qualityLevelRemove") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0 && k <= 5) {
qualityLevelRemove = k;
valid = true;
}
}
} else if (param == "qualityLevelMark") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0 && k <= 5) {
qualityLevelMark = k;
valid = true;
}
}
} else if (param == "qualityPenalizeSingletons") {
qualityPenalizeSingletons = (value == "true");
valid = true;
} else if (param == "qualityImmuneProbThreshold") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0) {
qualityImmuneProbThreshold = f;
valid = true;
}
}
} else if (param == "qualityImmuneMultipleEngines") {
qualityImmuneMultipleEngines = (value == "true");
valid = true;
// DECOY
} else if (param == "decoyConcatenate") {
decoyConcatenate = (value == "true");
valid = true;
} else if (param == "decoySizeRatio") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0) {
decoySizeRatio = k;
valid = true;
}
}
} else if (param == "decoyPrecursorSwap") {
decoyPrecursorSwap = (value == "true");
valid = true;
// REFRESH PROTEIN MAPPINGS
} else if (param == "refreshDatabase") {
if (!value.empty()) {
// fixpath(value);
refreshDatabase = value;
valid = true;
}
} else if (param == "refreshDeleteUnmapped") {
refreshDeleteUnmapped = (value == "true");
valid = true;
} else if (param == "refreshDeleteMultimapped") {
refreshDeleteMultimapped = (value == "true");
valid = true;
} else if (param == "refreshTrypticOnly") {
refreshTrypticOnly = (value == "true");
valid = true;
// USER SPECIFIED MODIFICATIONS
} else if (param == "allowableModTokens") {
allowableModTokens = value;
valid = true;
// SIMILARITY CLUSTERING
} else if (param == "unidentifiedClusterIndividualRun") {
unidentifiedClusterIndividualRun = (value == "true");
valid = true;
} else if (param == "unidentifiedClusterMinimumDot") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0 && f <= 1.0) {
unidentifiedClusterMinimumDot = f;
valid = true;
}
}
} else if (param == "unidentifiedRemoveSinglyCharged") {
unidentifiedRemoveSinglyCharged = (value == "true");
valid = true;
} else if (param == "unidentifiedMinimumNumPeaksToInclude") {
if (!value.empty()) {
k = atoi(value.c_str());
if (k >= 0) {
unidentifiedMinimumNumPeaksToInclude = k;
valid = true;
}
}
} else if (param == "unidentifiedSingletonXreaThreshold") {
if (!value.empty()) {
f = atof(value.c_str());
if (f >= 0.0 && f <= 1.0) {
unidentifiedSingletonXreaThreshold = f;
valid = true;
}
}
} else {
if (!g_quiet) {
cout << "Unknown option in " << paramsFileName << " : \"" << param << "\". Ignored. " << endl;
}
valid = true;
}
if (!valid && !g_quiet) {
cout << "Invalid value of \"" << param << "\" in " << paramsFileName << ". Ignored." << endl;
}
}
}
void SpectraSTCreateParams::printUsage(ostream& out) {
out << "(I) CREATE MODE " << endl;
out << "Usage: spectrast [ options ] <FileName1> [ <FileName2> ... <FileNameN> ]" << endl;
out << "where: FileNameX = Name of file containing spectra from which library is to be created." << endl;
out << " Extension specifies format of file. Supports .msp, .hlf, .pepXML (or .pep.xml or .xml), .ms2, and .splib." << endl;
out << endl;
out << "Options: GENERAL OPTIONS" << endl;
out << " -cF<file> Read create options from file <file>. " << endl;
out << " If <file> is not given, \"spectrast_create.params\" is assumed." << endl;
out << " NOTE: All options set in the file will be overridden by command-line options, if specified." << endl;
out << " -cN<name> Specify output file name for .splib, .spidx and .pepidx files. " << endl;
out << " -cm<remark> Remark. Add a Remark=<remark> comment to all library entries created. " << endl;
out << " -cM<format> Write all library spectra as MRM transition tables. Leave <format> blank for default. (Turn off with -cM!) " << endl;
out << " -cT<file> Use probability table in <file>. Only those peptide ions included in the table will be imported. " << endl;
out << " A probability table is a text file with one peptide ion in the format AC[160]DEFGHIK/2 per line. " << endl;
out << " If a probability is supplied following the peptide ion separated by a tab, it will be used to replace the original probability of that library entry." << endl;
out << " -cO<file> Use protein list in <file>. Only those peptide ions associated with proteins in the list will be imported. " << endl;
out << " A protein list is a text file with one protein identifier per line. " << endl;
out << " If a number X is supplied following the protein separated by a tab, then at most X peptide ions associated with that protein will be imported." << endl;
out << endl;
out << " PEPXML IMPORT OPTIONS (Applicable with .pepXML files)" << endl;
out << " -cP<prob> Include all spectra identified with probability no less than <prob> in the library." << endl;
out << " -cq<fdr> (Only PepXML import) Only include spectra with global FDR no greater than <fdr> in the library." << endl;
out << " -cn<name> Specify a dataset identifier for the file to be imported." << endl;
out << " -co Add the originating mzXML file name to the dataset identifier. Good for keeping track of in which" << endl;
out << " MS run the peptide is observed. (Turn off with -co!)" << endl;
out << " -cg Set all asparagines (N) in the motif NX(S/T) as deamidated (N[115]). Use for glycocaptured peptides. (Turn off with -cg!)." << endl;
out << " -cI Set the instrument and acquisition settings of the spectra (in case not specified in data files)." << endl;
out << " Examples: -cICID, -cIETD, -cICID-QTOF, -cIHCD. The latter two are treated as high-mass accuracy spectra." << endl;
out << endl;
out << " LIBRARY MANIPULATION OPTIONS (Applicable with .splib files)" << endl;
out << " -cf<pred> Filter library. Keep only those entries satisfying the predicate <pred>. " << endl;
out << " <pred> should be a C-style predicate in quotes. " << endl;
out << " -cJU Union. Include all the peptide ions in all the files. " << endl;
out << " -cJI Intersection. Only include peptide ions that are present in all the files. " << endl;
out << " -cJS Subtraction. Only include peptide ions in the first file that are not present in any of the other files." << endl;
out << " -cJH Subtraction of homologs. Only include peptide ions in the first file " << endl;
out << " that do not have any homologs with same charge and similar m/z in any of the other files." << endl;
out << " -cJA Appending. Each peptide ion is added from only one library: the first file in the argument list that contains that peptide ion." << endl;
out << " Useful for keeping existing consensus spectra unchanged while adding only previously unseen peptide ions." << endl;
out << " -cAB Best replicate. Pick the best replicate of each peptide ion. " << endl;
out << " -cAC Consensus. Create the consensus spectrum of all replicate spectra of each peptide ion. " << endl;
out << " -cAQ Quality filter. Apply quality filters to library." << endl;
out << " IMPORTANT: Quality filter can only be applied on a SINGLE .splib file with no peptide ion represented by more than one spectrum." << endl;
out << " -cAD Create artificial decoy spectra. " << endl;
out << " -cAN Sort library entries by descending number of replicates used (tie-breaking by probability). " << endl;
out << " -cAM Create semi-empirical spectra based on allowable modifications specified by -cx option. " << endl;
// HIDDEN FOR NOW: out << " -cAS Cluster spectra by similarity and merge clusters into consensus spectra. " << endl;
out << " -cQ<num> Produce reduced spectra of at most <num> peaks. Inactive with -cAQ and -cAD." << endl;
out << " -cD<file> Refresh protein mappings of each library entry against the protein database <file> (Must be in .fasta format)." << endl;
out << " -cu Delete entries whose peptide sequences do not map to any protein during refreshing with -cD option." << endl;
out << " When off, unmapped entries will be marked with Protein=0/UNMAPPED but retained in library. (Turn off with -cu!)." << endl;
out << " -cd Delete entries whose peptide sequences map to multiple proteins during refreshing with -cD option. (Turn off with -cd!)." << endl;
out << endl;
out << " CONSENSUS/BEST-REPLICATE OPTIONS (Applicable with -cAC and -cAB options)" << endl;
out << " -cr<num> Minimum number of replicates required for each library entry." << endl;
out << " Peptide ions failing to have originated from enough replicates" << endl;
out << " will be excluded from library when creating consensus/best-replicate library." << endl;
out << endl;
out << " QUALITY FILTER OPTIONS (Applicable with -cAQ option)" << endl;
out << " -cr<num> Replicate quorum. Its value affects behavior of quality filter (see below)." << endl;
out << " -cL<level> Specify the stringency of the quality filter." << endl;
out << " -cl<level> -cL specifies the level for removal, -cl specifies the level for marking." << endl;
out << " <level> = 0: No filter." << endl;
out << " <level> = 1: Remove/mark impure spectra." << endl;
out << " <level> = 2: Also remove/mark spectra with a spectrally similar counterpart in the library that is better." << endl;
out << " <level> = 3: Also remove/mark inquorate entries (defined with -cr) that share no peptide sub-sequences with any other entries in the library." << endl;
out << " <level> = 4: Also remove/mark all singleton entries." << endl;
out << " <level> = 5: Also remove/mark all inquorate entries (defined with -cr)." << endl;
out << endl;
out << " DECOY CREATION OPTIONS (Applicable with -cAD option)" << endl;
out << " -cc Concatenate real and decoy libraries. (Turn off with -cc!)" << endl;
out << " -cy<num> Specify the (decoy / real) size ratio. Must be an integer." << endl;
out << endl;
out << " SEMI-EMPIRICAL SPECTRUM CREATION OPTIONS (Applicable with -cAM option)" << endl;
out << " -cx<str> Specify allowable modification tokens used to generate new peptide ions for which semi-empirical spectra are to be created." << endl;
out << " (e.g. -cx\"K[136]\" for static mod of +6 heavy lysines, -cx\"MM[147]\" for variable mod of methionine oxidation.)" << endl;
out << endl;
out << " OTHER ADVANCED OPTIONS" << endl;
out << " Type \"spectrast -c_\" for a full list of advanced (and obscure and not-so-useful) options." << endl;
out << endl;
out << endl;
}
void SpectraSTCreateParams::printAdvancedOptions(ostream& out) {
out << "Spectrast (version " << SPECTRAST_VERSION << "." << SPECTRAST_SUB_VERSION << ", " << szTPPVersionInfo << ") by Henry Lam." << endl;
out << endl;
out << "CREATE MODE ADVANCED OPTIONS" << endl;
out << endl;
out << "GENERAL OPTIONS:" << endl;
out << " -c_BIN Write library in binary format (Enables quicker search). (Turn off with -c_BIN!) " << endl;
out << " A human-readable text-format library file will also be created." << endl;
out << " -c_DTA Write all library spectra as .dta files. (Turn off with -c_DTA!) " << endl;
out << " -c_MGF Write all library spectra as .mgf files. (Turn off with -c_MGF!) " << endl;
out << " -c_RDY<prefix> Remove spectra of decoys, for which all proteins have names starting with <prefix>." << endl;
out << " Also remove decoy proteins from Protein field for peptides mapped to both target and decoy proteins." << endl;
out << "LIBRARY IMPORT OPTIONS (Applicable with .pep.xml, .tsv, .msp, .hlf, .ms2, .mz(X)ML)" << endl;
out << " -c_CEN Centroid peaks." << endl;
out << " -c_RNT<thres> Absolute noise filter. Filter out noise peaks with intensity below <thres>." << endl;
out << " -c_RDR<range> Relative noise filter. Filter out noise peaks with intensity below 1/<range> of that of the highest peak." << endl;
out << " -c_NAA<num> Exclude spectra with IDs of fewer than <num> amino acids." << endl;
out << " -c_NPK<num> Exclude spectra with fewer than <num> peaks." << endl;
out << " -c_XAN Skip (re-)annotation of the imported spectra." << endl;
out << " -c_DCN<thres> (Only PepXML import) Exclude spectra with deltaCn smaller than <thres>." << endl;
out << " Useful for excluding spectra with indiscriminate modification sites." << endl;
out << " -c_MDF<thres> (Only PepXML import) Exclude spectra with precursor mass difference (absolute value) of over <thres> Daltons." << endl;
out << " -c_BRK (Only PepXML import) Bracket import: for each confident ID, also search neighboring scan numbers for repeated scans to import. (Turn off with -c_BRK!)" << endl;
out << " -c_BRM (Only PepXML import) Merge bracketed spectra: merge repeated scans of a bracket into one consensus spectrum for import. (Turn off with -c_BRM!)" << endl;
out << "LIBRARY MANIPULATION OPTIONS (Applicable with .splib files)" << endl;
out << " -c_ANN Re-annotate peaks (Turn off with -c_ANN!). " << endl;
out << " -c_Q3L Specify the lower m/z limit for Q3 in MRM table generation." << endl;
out << " -c_Q3H Specify the upper m/z limit for Q3 in MRM table generation. " << endl;
out << " -c_NAA<num> Exclude spectra with IDs of fewer than <num> amino acids." << endl;
out << " -c_NPK<num> Exclude spectra with fewer than <num> peaks." << endl;
out << " -c_RTO With -cD option, only map peptide to protein when the peptide is tryptic in that particular protein. (Turn off with -c_RTO!)" << endl;
out << "CONSENSUS/BEST-REPLICATE OPTIONS (Applicable with -cAC and -cAB options)" << endl;
out << " -c_DIS Remove dissimilar replicates before creating consensus spectrum. (Turn off with -c_DIS!)" << endl;
out << " -c_QUO<frac> Peak quorum: the fraction of all replicates required to contain a certain peak." << endl;
out << " Peaks not present in enough replicates will be deleted." << endl;
out << " -c_XPU<num> Maximum number of peaks in each replicate to be considered in creating consensus." << endl;
out << " Only the top <num> peaks by intensity will be considered." << endl;
out << " -c_XNR<num> Maximum number of replicates used to build consensus spectrum. " << endl;
out << " Note: This is not an absolute hard cap for consensus spectrum created from consensus spectra." << endl;
out << " -c_XPK<num> Maximum number of peaks kept in the final library spectrum. " << endl;
out << " The most intense <num> peaks will be kept. <num> = 0 means keeping all peaks." << endl;
out << " -c_WGT<score> Select the type of score to weigh and rank the replicates." << endl;
out << " <score> = 'X': will use a function of the SEQUEST xcorr score as the weight." << endl;
out << " <score> = 'S': will use a measure of signal-to-noise ratio as the weight." << endl;
out << " <score> = 'P': will use a function of the PeptideProphet probability as the weight." << endl;
out << " <score> = 'I': will use a function of the precursor intensity as the weight." << endl;
out << " <score> = everything else: all replicates will be weighted equally and ranked randomly." << endl;
out << " -c_RRS Record all raw spectra (in the format file.scan.scan) used to build the consensus in the Comment." << endl;
out << "BAYESIAN DENOISER OPTIONS" << endl;
out << " -c_BDU Use Bayesian denoiser. Default parameters are used unless trained on the fly with -c_BDT. (Turn off with -c_BDU!)" << endl;
out << " -c_BDT Train Bayesian denoiser. Only active in consensus mode (-cAC)." << endl;
out << " -c_BDP<thres> Minimum signal probability to retain a peak when denoiser is used." << endl;
out << " -c_BDF<file> Specify parameter file for Bayesian denoiser for writing and reading." << endl;
out << "QUALITY FILTER OPTIONS" << endl;
out << " -c_QP1 Apply stricter thresholds to singleton spectra during quality filters. (Turn off with -c_QP1!)" << endl;
out << " -c_QIP<thres> Specify a probability above which library spectra are immune to quality filters." << endl;
out << " Set <thres> to above 1.0 to subject all spectra to quality filters regardless of probability." << endl;
out << " -c_QIE Make spectra identified by multiple sequence search engines immune to quality filters. (Turn off with -c_QIE!)" << endl;
out << endl;
out << "DECOY CREATION OPTIONS" << endl;
out << " -c_DPS Use the precursor swap method for generating decoys. (Turn off with -c_DPS!)" << endl;
out << "RETENTION TIME NORMALIZATION OPTIONS (Applicable with .pep.xml)" << endl;
out << " -c_IRT Use landmark peptides in <file> to normalize retention times to iRT's." << endl;
out << " -c_IRR Regress the real RTs of landmark peptides (i.e. assume they form a straight line). (Turn off with -c_IRR!)" << endl;
out << "UNIDENTIFIED LIBRARY/CLUSTERING OPTIONS" << endl;
out << " -c_UCR Cluster spectra in each run as they are imported from data files. (Turn off with -c_UCR!)" << endl;
out << " -c_UCD<thres> Specify minimum dot products for two spectra to be clustered." << endl;
out << " -c_UX1 Remove spectra that appear to be singly charged. (Turn off with -c_UX1!)" << endl;
out << " -c_UNP<num> Remove spectra that have fewer than <num> peaks." << endl;
out << " -c_USX<thres> Apply an Xrea (quality measure) filter to singleton spectra after clustering." << endl;
}
string SpectraSTCreateParams::constructDescrStr(string fileList, string fileType) {
stringstream ss;
if (fileType == ".splib") {
ss << "COMPILE FROM " << fileList;
if (buildAction == "CONSENSUS") {
ss << " [" << buildAction;
ss << ";r=" << minimumNumReplicates;
ss << ";I=" << setFragmentation;
ss << ";_QUO=" << peakQuorum;
ss << ";_XNR=" << maximumNumReplicates;
ss << ";_WGT=" << replicateWeight;
ss << ";_DIS=" << (removeDissimilarReplicates ? "TRUE" : "FALSE");
ss << ";_XPK=" << maximumNumPeaksKept;
ss << ";_XPU=" << maximumNumPeaksUsed;
ss << ";_BDN=" << (useBayesianDenoiser ? "TRUE" : "FALSE");
ss << ";_TBD=" << (trainBayesianDenoiser ? "TRUE" : "FALSE");
if (useBayesianDenoiser) ss << ";_MSP=" << denoiserMinimumSignalProb;
ss << "]";
} else if (buildAction == "BEST_REPLICATE") {
ss << " [" << buildAction;
ss << ";r=" << minimumNumReplicates;
ss << ";I=" << setFragmentation;
ss << ";_DIS=" << (removeDissimilarReplicates ? "TRUE" : "FALSE");
ss << ";_BDN=" << (useBayesianDenoiser ? "TRUE" : "FALSE");
if (useBayesianDenoiser) ss << ";_MSP=" << denoiserMinimumSignalProb;
ss << "]";
} else if (buildAction == "QUALITY_FILTER") {
ss << " [" << buildAction;
ss << ";L=" << qualityLevelRemove;
ss << ";l=" << qualityLevelMark;
ss << ";r=" << minimumNumReplicates;
ss << ";I=" << setFragmentation;
ss << ";_QP1=" << (qualityPenalizeSingletons ? "TRUE" : "FALSE");
ss << ";_QIP=" << qualityImmuneProbThreshold;
ss << ";_QIE=" << (qualityImmuneMultipleEngines ? "TRUE" : "FALSE");
ss << "]";
} else if (buildAction == "DECOY") {
ss << " [" << buildAction;
ss << ";c=" << (decoyConcatenate ? "TRUE" : "FALSE");
ss << ";y=" << decoySizeRatio;
ss << ";DPS=" << (decoyPrecursorSwap ? "TRUE" : "FALSE");
ss << ";I=" << setFragmentation;
ss << "]";
} else if (buildAction == "SORT_BY_NREPS") {
ss << " [" << buildAction;
ss << ";I=" << setFragmentation;
ss << "]";
} else if (buildAction == "USER_SPECIFIED_MODS") {
ss << " [" << buildAction;
ss << ";x=" << allowableModTokens;
ss << ";I=" << setFragmentation;
ss << "]";
} else if (buildAction == "SIMILARITY_CLUSTERING") {
ss << " [" << buildAction;
ss << ";r=" << minimumNumReplicates;
ss << ";I=" << setFragmentation;
ss << ";_QUO=" << peakQuorum;
ss << ";_XNR=" << maximumNumReplicates;
ss << ";_WGT=" << replicateWeight;
ss << ";_DIS=" << (removeDissimilarReplicates ? "TRUE" : "FALSE");
ss << ";_XPK=" << maximumNumPeaksKept;
ss << ";_XPU=" << maximumNumPeaksUsed;
ss << ";_UCD=" << unidentifiedClusterMinimumDot;
ss << ";_USX=" << unidentifiedSingletonXreaThreshold;
ss << ";_BDN=" << (useBayesianDenoiser ? "TRUE" : "FALSE");
if (useBayesianDenoiser) ss << ";_MSP=" << denoiserMinimumSignalProb;
ss << "]";
}
} else if (fileType == ".msp") {
ss << "IMPORT FROM MSP " << fileList;
} else if (fileType == ".hlf") {
ss << "IMPORT FROM HLF " << fileList;
} else if (fileType == ".ms2") {
ss << "IMPORT FROM MS2 " << fileList;
} else if (fileType == ".pepXML") {
ss << "IMPORT FROM PepXML " << fileList;
ss << "[P=" << minimumProbabilityToInclude;
ss << ";q=" << maximumFDRToInclude;
ss << ";n=" << datasetName;
ss << ";g=" << (setDeamidatedNXST ? "TRUE" : "FALSE");
ss << ";o=" << (addMzXMLFileToDatasetName ? "TRUE" : "FALSE");
ss << ";I=" << setFragmentation;
ss << ";_RNT=" << rawSpectraNoiseThreshold;
ss << ";_RDR=" << rawSpectraMaxDynamicRange;
ss << ";_DCN=" << minimumDeltaCnToInclude;
ss << ";_NAA=" << minimumNumAAToInclude;
ss << ";_NPK=" << minimumNumPeaksToInclude;
ss << ";_MDF=" << maximumMassDiffToInclude;
ss << ";_CEN=" << (centroidPeaks ? "TRUE" : "FALSE");
ss << ";_XAN=" << (skipRawAnnotation ? "TRUE" : "FALSE");
ss << ";_BRK=" << (bracketSpectra ? "TRUE" : "FALSE");
ss << ";_BRM=" << (mergeBracket ? "TRUE" : "FALSE");
ss << ";_IRT=" << normalizeRTWithLandmarks;
ss << ";_IRR=" << (normalizeRTLinearRegression ? "TRUE" : "FALSE");
// ss << ";_PHO=" << (evaluatePhosphoSiteAssignment ? "TRUE" : "FALSE");
ss << "]";
} else if (fileType == ".tsv") {
ss << "IMPORT FROM TSV " << fileList;
ss << "[P=" << minimumProbabilityToInclude;
ss << ";n=" << datasetName;
ss << ";g=" << (setDeamidatedNXST ? "TRUE" : "FALSE");
ss << ";o=" << (addMzXMLFileToDatasetName ? "TRUE" : "FALSE");
ss << ";I=" << setFragmentation;
ss << ";_RNT=" << rawSpectraNoiseThreshold;
ss << ";_RDR=" << rawSpectraMaxDynamicRange;
ss << ";_DCN=" << minimumDeltaCnToInclude;
ss << ";_NAA=" << minimumNumAAToInclude;
ss << ";_NPK=" << minimumNumPeaksToInclude;
ss << ";_CEN=" << (centroidPeaks ? "TRUE" : "FALSE");
ss << ";_XAN=" << (skipRawAnnotation ? "TRUE" : "FALSE");
ss << "]";
} else if (fileType == ".mzXML") {
ss << "IMPORT FROM MZXML " << fileList;
ss << ";n=" << datasetName;
ss << ";o=" << (addMzXMLFileToDatasetName ? "TRUE" : "FALSE");
ss << ";I=" << setFragmentation;
ss << ";_RNT=" << rawSpectraNoiseThreshold;
ss << ";_RDR=" << rawSpectraMaxDynamicRange;
ss << ";_CEN=" << (centroidPeaks ? "TRUE" : "FALSE");
ss << ";_UCR=" << (unidentifiedClusterIndividualRun ? "TRUE" : "FALSE");
ss << ";_UCD=" << unidentifiedClusterMinimumDot;
ss << ";_UX1=" << (unidentifiedRemoveSinglyCharged ? "TRUE" : "FALSE");
ss << ";_UNP=" << unidentifiedMinimumNumPeaksToInclude;
ss << "]";
}
// add filter string
if (!filterCriteria.empty()) {
ss << "; FILTER for " << filterCriteria;
}
if (!useProbTable.empty()) {
ss << "; FILTER for entries in probability table \"" << useProbTable << "\"";
}
if (!useProteinList.empty()) {
ss << "; FILTER for entries in protein list \"" << useProteinList << "\"";
}
// add refresh string (if .splib)
if (!refreshDatabase.empty() && fileType == ".splib") {
ss << "; REFRESH against " << refreshDatabase;
if (refreshTrypticOnly) {
ss << " (Tryptic Only)";
}
if (refreshDeleteUnmapped || refreshDeleteMultimapped) {
ss << " (Delete";
if (refreshDeleteUnmapped) {
ss << " Unmapped";
}
if (refreshDeleteMultimapped) {
ss << " Multimapped";
}
ss << ")";
}
}
return (ss.str());
}
| 32.752351 | 196 | 0.57523 | [
"cad",
"vector"
] |
1261bedcc5bf6c3d5e8c18f5005c4bed381f4a28 | 7,271 | cpp | C++ | projects/multitask/yolopcut/main.cpp | ChenKQ/detsrv | 258a8d841bc03c4e0e8651ad19de543cf6475833 | [
"Xnet",
"X11"
] | null | null | null | projects/multitask/yolopcut/main.cpp | ChenKQ/detsrv | 258a8d841bc03c4e0e8651ad19de543cf6475833 | [
"Xnet",
"X11"
] | null | null | null | projects/multitask/yolopcut/main.cpp | ChenKQ/detsrv | 258a8d841bc03c4e0e8651ad19de543cf6475833 | [
"Xnet",
"X11"
] | null | null | null | #include "yolov5.hpp"
#include "utils.h"
#include <opencv2/opencv.hpp>
#include <csignal>
static volatile bool keep_running = true;
void keyboard_handler(int sig) {
// handle keyboard interrupt
if (sig == SIGINT)
keep_running = false;
}
void saveresult(cv::Mat& cvt_img, cv::Mat& seg_res, std::vector<Yolo::Detection>& res)
{
static const std::vector<cv::Vec3b> segColor{cv::Vec3b(0, 0, 0), cv::Vec3b(0, 255, 0), cv::Vec3b(255, 0, 0)};
static const std::vector<cv::Vec3b> laneColor{cv::Vec3b(0, 0, 0), cv::Vec3b(0, 0, 255), cv::Vec3b(0, 0, 0)};
cv::Mat cvt_img_cpu = cvt_img;
// cvt_img.download(cvt_img_cpu);
// handling seg and lane results
for (int row = 0; row < cvt_img_cpu.rows; ++row) {
uchar* pdata = cvt_img_cpu.data + row * cvt_img_cpu.step;
for (int col = 0; col < cvt_img_cpu.cols; ++col) {
int seg_idx = seg_res.at<int>(row, col);
// int lane_idx = lane_res.at<int>(row, col);
//std::cout << "enter" << ix << std::endl;
for (int i = 0; i < 3; ++i) {
// if (lane_idx) {
// if (i != 2)
// pdata[i] = pdata[i] / 2 + laneColor[lane_idx][i] / 2;
// }
if (seg_idx)
pdata[i] = pdata[i] / 2 + segColor[seg_idx][i] / 2;
}
pdata += 3;
}
}
// handling det results
std::cout << "number of detection result: " << res.size() << '\n';
for (size_t j = 0; j < res.size(); ++j) {
std::cout << "class: " << res[j].class_id
<< ", confidence: " << res[j].conf
<< ", [centerx: " << res[j].bbox[0]
<< ", centery: " << res[j].bbox[1]
<< ", width: " << res[j].bbox[2]
<< ", height: " << res[j].bbox[3] << "]\n";
// if(int(res[j].class_id) != 1)
// continue;
cv::Rect r = get_rect(cvt_img_cpu, res[j].bbox);
cv::rectangle(cvt_img_cpu, r, cv::Scalar(0x27, 0xC1, 0x36), 2);
cv::putText(cvt_img_cpu, std::to_string((int)res[j].class_id), cv::Point(r.x, r.y - 1), cv::FONT_HERSHEY_PLAIN, 1.2, cv::Scalar(0xFF, 0xFF, 0xFF), 2);
}
cv::imwrite("./zed_result.jpg", cvt_img_cpu);
}
int main(int argc, char** argv) {
signal(SIGINT, keyboard_handler);
cudaSetDevice(DEVICE);
// std::string wts_name = "yolop.wts";
std::string engine_name = "yolopcut.engine";
// deserialize the .engine and run inference
std::ifstream file(engine_name, std::ios::binary);
if (!file.good()) {
std::cerr << "read " << engine_name << " error!" << std::endl;
return -1;
}
char *trtModelStream = nullptr;
size_t size = 0;
file.seekg(0, file.end);
size = file.tellg();
file.seekg(0, file.beg);
trtModelStream = new char[size];
assert(trtModelStream);
file.read(trtModelStream, size);
file.close();
// prepare data ---------------------------
static float data[BATCH_SIZE * 3 * INPUT_H * INPUT_W];
static float det_out[BATCH_SIZE * OUTPUT_SIZE];
static int seg_out[BATCH_SIZE * IMG_H * IMG_W];
// static int lane_out[BATCH_SIZE * IMG_H * IMG_W];
IRuntime* runtime = createInferRuntime(gLogger);
assert(runtime != nullptr);
ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size);
assert(engine != nullptr);
IExecutionContext* context = engine->createExecutionContext();
assert(context != nullptr);
delete[] trtModelStream;
std::cout << "number of bindings: " << engine->getNbBindings() << "\n";
assert(engine->getNbBindings() == 4);
void* buffers[3];
// In order to bind the buffers, we need to know the names of the input and output tensors.
// Note that indices are guaranteed to be less than IEngine::getNbBindings()
const int inputIndex = engine->getBindingIndex(INPUT_BLOB_NAME);
const int output_det_index = engine->getBindingIndex(OUTPUT_DET_NAME);
const int output_seg_index = engine->getBindingIndex(OUTPUT_SEG_NAME);
// const int output_lane_index = engine->getBindingIndex(OUTPUT_LANE_NAME);
assert(inputIndex == 0);
assert(output_det_index == 1);
assert(output_seg_index == 2);
// assert(output_lane_index == 3);
// Create GPU buffers on device
CUDA_CHECK(cudaMalloc(&buffers[inputIndex], BATCH_SIZE * 3 * INPUT_H * INPUT_W * sizeof(float)));
CUDA_CHECK(cudaMalloc(&buffers[output_det_index], BATCH_SIZE * OUTPUT_SIZE * sizeof(float)));
CUDA_CHECK(cudaMalloc(&buffers[output_seg_index], BATCH_SIZE * IMG_H * IMG_W * sizeof(int)));
// CUDA_CHECK(cudaMalloc(&buffers[output_lane_index], BATCH_SIZE * IMG_H * IMG_W * sizeof(int)));
// Create stream
cudaStream_t stream;
CUDA_CHECK(cudaStreamCreate(&stream));
cv::Mat img = cv::imread("./01.jpg");
int width = img.cols;
int height = img.rows;
// store seg results
cv::Mat tmp_seg(IMG_H, IMG_W, CV_32S, seg_out);
// sotore lane results
// cv::Mat tmp_lane(IMG_H, IMG_W, CV_32S, lane_out);
cv::Mat seg_res(height, width, CV_32S);
// cv::Mat lane_res(height, width, CV_32S);
// preprocess ~3ms
cv::Mat preprocessedImage = preprocess_img(img, INPUT_W, INPUT_H);
int i = 0;
std::cout << "width: " << preprocessedImage.cols
<< ", height: " << preprocessedImage.rows
<< ", step: " << preprocessedImage.step
<< "\n" ;
for (int row = 0; row < INPUT_H; ++row) {
uchar* uc_pixel = preprocessedImage.data + row * preprocessedImage.step;
for (int col = 0; col < INPUT_W; ++col) {
data[i + 0 * INPUT_H * INPUT_W] = *(float*)(uc_pixel+0*sizeof(float));
data[i + 1 * INPUT_H * INPUT_W] = *(float*)(uc_pixel+1*sizeof(float));
data[i + 2 * INPUT_H * INPUT_W] = *(float*)(uc_pixel+2*sizeof(float));
uc_pixel += 3*sizeof(float);
++i;
}
}
// Run inference
auto start = std::chrono::system_clock::now();
// cuCtxPushCurrent(ctx);
doInferenceCpu(*context, stream, buffers, data, det_out, seg_out, nullptr, BATCH_SIZE);
// cuCtxPopCurrent(&ctx);
auto end = std::chrono::system_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
// postprocess ~0ms
std::vector<Yolo::Detection> batch_res;
nms(batch_res, det_out, CONF_THRESH, NMS_THRESH);
// nms(batch_res, det_out, 0.0, 0.0);
cv::resize(tmp_seg, seg_res, seg_res.size(), 0, 0, cv::INTER_NEAREST);
// cv::resize(tmp_lane, lane_res, lane_res.size(), 0, 0, cv::INTER_NEAREST);
// show results
//std::cout << res.size() << std::endl;
saveresult(img, seg_res, batch_res);
// destroy windows
#ifdef SHOW_IMG
cv::destroyAllWindows();
#endif
// Release stream and buffers
cudaStreamDestroy(stream);
CUDA_CHECK(cudaFree(buffers[inputIndex]));
CUDA_CHECK(cudaFree(buffers[output_det_index]));
CUDA_CHECK(cudaFree(buffers[output_seg_index]));
// CUDA_CHECK(cudaFree(buffers[output_lane_index]));
// Destroy the engine
context->destroy();
engine->destroy();
runtime->destroy();
return 0;
}
| 40.171271 | 158 | 0.599367 | [
"vector"
] |
1270a104db532324d8e9a80136302f8b3e37d92f | 4,481 | cpp | C++ | third_party/katana/plugin/pxrUsdInShipped/mesh.cpp | 1xinghuan/USD | a527e225224dd8634eb91ef749cf622cbf3d349d | [
"Unlicense"
] | 3 | 2019-02-20T07:34:17.000Z | 2019-08-13T08:17:04.000Z | third_party/katana/plugin/pxrUsdInShipped/mesh.cpp | 1xinghuan/USD | a527e225224dd8634eb91ef749cf622cbf3d349d | [
"Unlicense"
] | null | null | null | third_party/katana/plugin/pxrUsdInShipped/mesh.cpp | 1xinghuan/USD | a527e225224dd8634eb91ef749cf622cbf3d349d | [
"Unlicense"
] | null | null | null | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxrUsdInShipped/declareCoreOps.h"
#include "pxr/pxr.h"
#include "usdKatana/attrMap.h"
#include "usdKatana/readMesh.h"
#include "usdKatana/utils.h"
#include "pxr/base/tf/envSetting.h"
#include "pxr/usd/usdShade/material.h"
#include "pxr/usd/usdGeom/faceSetAPI.h"
#include "pxr/usd/usdGeom/mesh.h"
PXR_NAMESPACE_USING_DIRECTIVE
TF_DEFINE_ENV_SETTING(USD_KATANA_IMPORT_FACESET_API, true,
"Whether face-sets encoded using the deprecated "
"UsdGeomFaceSetAPI schema must be imported by PxrUsdIn.")
static void
_CreateFaceSetsFromFaceSetAPI(
const UsdPrim& prim,
const PxrUsdKatanaUsdInPrivateData &data,
FnKat::GeolibCookInterface& interface);
PXRUSDKATANA_USDIN_PLUGIN_DEFINE(PxrUsdInCore_MeshOp, privateData, opArgs, interface)
{
PxrUsdKatanaAttrMap attrs;
const UsdPrim& prim = privateData.GetUsdPrim();
PxrUsdKatanaReadMesh(
UsdGeomMesh(prim), privateData, attrs);
attrs.toInterface(interface);
if (TfGetEnvSetting(USD_KATANA_IMPORT_FACESET_API) &&
UsdShadeMaterial::HasMaterialFaceSet(prim))
{
_CreateFaceSetsFromFaceSetAPI(prim, privateData, interface);
}
}
// For now, this is only used by the mesh op. If this logic needs to be
// accessed elsewhere, it should move down into usdKatana.
static void
_CreateFaceSetsFromFaceSetAPI(
const UsdPrim& prim,
const PxrUsdKatanaUsdInPrivateData &data,
FnKat::GeolibCookInterface& interface)
{
UsdGeomFaceSetAPI faceSet = UsdShadeMaterial::GetMaterialFaceSet(prim);
bool isPartition = faceSet.GetIsPartition();;
if (!isPartition) {
TF_WARN("Found face set on prim <%s> that is not a partition.",
prim.GetPath().GetText());
// continue here?
}
const double currentTime = data.GetCurrentTime();
VtIntArray faceCounts, faceIndices;
faceSet.GetFaceCounts(&faceCounts, currentTime);
faceSet.GetFaceIndices(&faceIndices, currentTime);
SdfPathVector bindingTargets;
faceSet.GetBindingTargets(&bindingTargets);
size_t faceSetIdxStart = 0;
for(size_t faceSetIdx = 0; faceSetIdx < faceCounts.size(); ++faceSetIdx) {
size_t faceCount = faceCounts[faceSetIdx];
FnKat::GroupBuilder faceSetAttrs;
faceSetAttrs.set("type", FnKat::StringAttribute("faceset"));
faceSetAttrs.set("materialAssign", FnKat::StringAttribute(
PxrUsdKatanaUtils::ConvertUsdMaterialPathToKatLocation(
bindingTargets[faceSetIdx], data)));
FnKat::IntBuilder facesBuilder;
{
std::vector<int> faceIndicesVec(faceCount);
for (size_t faceIndicesIdx = 0; faceIndicesIdx < faceCount; ++faceIndicesIdx)
{
faceIndicesVec[faceIndicesIdx] =
faceIndices[faceSetIdxStart + faceIndicesIdx];
}
faceSetIdxStart += faceCount;
facesBuilder.set(faceIndicesVec);
}
faceSetAttrs.set("geometry.faces", facesBuilder.build());
std::string faceSetName = TfStringPrintf("faceset_%zu", faceSetIdx);
FnKat::GroupBuilder staticSceneCreateAttrs;
staticSceneCreateAttrs.set("a", faceSetAttrs.build());
interface.createChild(
faceSetName,
"StaticSceneCreate",
staticSceneCreateAttrs.build());
}
}
| 35.848 | 89 | 0.699397 | [
"mesh",
"geometry",
"vector"
] |
127800f2784b90a52103889f63f0618160eda211 | 59,471 | cpp | C++ | libmilk/src/linux/var.cpp | lyramilk/libmilk | 153b8ca3f14ac1d2e5a017a0ba4ca3e6f35fd680 | [
"Apache-2.0"
] | 3 | 2017-09-06T12:45:34.000Z | 2018-07-21T17:05:10.000Z | libmilk/src/linux/var.cpp | lyramilk/libmilk | 153b8ca3f14ac1d2e5a017a0ba4ca3e6f35fd680 | [
"Apache-2.0"
] | null | null | null | libmilk/src/linux/var.cpp | lyramilk/libmilk | 153b8ca3f14ac1d2e5a017a0ba4ca3e6f35fd680 | [
"Apache-2.0"
] | null | null | null | #include "var.h"
#include "dict.h"
#include "datawrapper.h"
#include <vector>
#include <sstream>
#include <algorithm>
#include <stdio.h>
#include <memory.h>
#ifndef null
#define null nullptr
#endif
#ifdef Z_HAVE_JEMALLOC
#include <jemalloc/jemalloc.h>
#endif
#ifdef _WIN32
#include <Windows.h>
#elif defined __linux__
#include <iconv.h>
#include <assert.h>
#include <arpa/inet.h>
#endif
//namespace lyramilk { namespace data{
const lyramilk::data::var lyramilk::data::var::nil;
template <typename T>
T reverse_order(T t)
{
const int sz = sizeof(T);
union{
T v;
char c[sizeof(T)];
}s,d;
s.v = t;
for(int i =0;i < sz;++i){
d.c[i] = s.c[sz - i - 1];
}
return d.v;
}
#ifdef _WIN32
class u2a
{
lyramilk::data::string p;
public:
u2a(const lyramilk::data::wstring& wstr)
{
p.resize((wstr.length() + 1) << 1);
char* _ = (char*)p.c_str();
int i = WideCharToMultiByte(CP_ACP,0,wstr.c_str(),(int)wstr.length(),_,(int)p.capacity(),null,null);
p.erase(p.begin() + i,p.end());
}
/*
operator const char*()
{
return p.data();
}*/
operator lyramilk::data::string()
{
return p;
}
};
class a2u
{
lyramilk::data::wstring p;
public:
a2u(const lyramilk::data::string& str)
{
p.resize(str.length() + 1);
wchar_t* _ = (wchar_t*)p.c_str();
int i = MultiByteToWideChar(CP_ACP,0,str.c_str(),(int)str.length(),_,(int)p.capacity());
p.erase(p.begin() + i,p.end());
}
/*
operator const wchar_t*()
{
return p.data();
}*/
operator lyramilk::data::wstring()
{
return p;
}
};
class u2t
{
lyramilk::data::string p;
public:
u2t(const wstring& wstr)
{
int len = WideCharToMultiByte(CP_UTF8,0,wstr.c_str(),(int)wstr.length(),null,0,null,null);
p.resize(len);
char* _ = (char*)p.c_str();
int i = WideCharToMultiByte(CP_UTF8,0,wstr.c_str(),(int)wstr.length(),_,(int)p.capacity(),null,null);
p.erase(p.begin() + i,p.end());
}
/*
operator const char*()
{
return p.c_str();
}*/
operator lyramilk::data::string()
{
return p;
}
};
class t2u
{
wstring p;
public:
t2u(const lyramilk::data::string& str)
{
int len = MultiByteToWideChar(CP_UTF8,0,str.c_str(),(int)str.length(),null,0);
p.resize(len);
wchar_t* _ = (wchar_t*)p.c_str();
int i = MultiByteToWideChar(CP_UTF8,0,str.c_str(),(int)str.length(),_,(int)p.capacity());
p.erase(p.begin() + i,p.end());
}
/*
operator const wchar_t*()
{
return p.data();
}*/
operator wstring()
{
return wstring(p.data());
}
};
#define t2a(x) (u2a(t2u(x)))
#define a2t(x) (u2t(a2u(x)))
#elif defined __linux__
lyramilk::data::string iconv(const lyramilk::data::string& str,const lyramilk::data::string& from,const lyramilk::data::string& to)
{
const size_t ds = 4096;
iconv_t cd = iconv_open(to.c_str(),from.c_str());
if(cd == 0){
assert(cd);
return "";
}
char* p1 = (char*)str.c_str();
size_t p1s = str.size();
std::vector<char> ret;
char* p2 = ret.data();
size_t p2s = ret.size();
int rc = -1;
do{
size_t pos = p2 - ret.data();
ret.insert(ret.end(),ds,0);
p2 = ret.data() + pos;
p2s = ret.size() - pos;
rc = ::iconv(cd,&p1,&p1s,&p2,&p2s);
}while(rc == -1 && p2s < ds);
iconv_close(cd);
if(rc == -1){
return "";
}
return lyramilk::data::string(ret.data(),p2 - (char*)ret.data());
}
lyramilk::data::wstring inline utf8_unicode(const lyramilk::data::string& str)
{
lyramilk::data::string dst = iconv(str,"utf8//ignore","wchar_t");
if(dst.size()&1){
dst.push_back(0);
}
return lyramilk::data::wstring((wchar_t*)dst.c_str(),dst.size() >> lyramilk::data::intc<sizeof(wchar_t)>::square);
}
lyramilk::data::string inline unicode_utf8(const lyramilk::data::wstring& str)
{
lyramilk::data::string src((char*)str.c_str(),str.size() << lyramilk::data::intc<sizeof(wchar_t)>::square);
lyramilk::data::string dst = iconv(src,"wchar_t","utf8");
return dst;
}
class u2a
{
lyramilk::data::string p;
public:
u2a(const lyramilk::data::wstring& wstr)
{
p = unicode_utf8(wstr);
}
operator lyramilk::data::string()
{
return p;
}
};
class a2u
{
lyramilk::data::wstring p;
public:
a2u(const lyramilk::data::string& str)
{
p = utf8_unicode(str);
}
operator lyramilk::data::wstring()
{
return p;
}
};
#define t2a(x) (x)
#define a2t(x) (x)
#define t2u(x) a2u(x)
#define u2t(x) u2a(x)
#endif
lyramilk::data::var::var()
{
t = t_invalid;
}
lyramilk::data::var::var(const lyramilk::data::var& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::~var()
{
clear();
}
lyramilk::data::var::var(const unsigned char* v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const char* v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const wchar_t* v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::chunk& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::string& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::wstring& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(bool v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(int8 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(uint8 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(int16 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(uint16 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(int32 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(uint32 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(long v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(unsigned long v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(int64 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(uint64 v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(double v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(float v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::array& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::map& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::stringdict& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::case_insensitive_unordered_map& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::case_insensitive_map& v)
{
t = t_invalid;
assign(v);
}
lyramilk::data::var::var(const lyramilk::data::datawrapper& v)
{
t = t_invalid;
assign(v);
}
bool lyramilk::data::var::operator ==(const lyramilk::data::var& v) const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:{
if(v.t == t_bool){
return ((bool)*this) == v.u.b;
}else{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
return bp->compare((lyramilk::data::chunk)v) == 0;
}
}break;
case t_str:{
if(v.t == t_bool){
return ((bool)*this) == v.u.b;
}else{
const lyramilk::data::string* bs = reinterpret_cast<const lyramilk::data::string*>(&u.bs);
return bs->compare((lyramilk::data::string)v) == 0;
}
}break;
case t_wstr:{
if(v.t == t_bool){
return ((bool)*this) == v.u.b;
}else{
const lyramilk::data::wstring* bw = reinterpret_cast<const lyramilk::data::wstring*>(&u.bw);
return bw->compare((lyramilk::data::wstring)v) == 0;
}
}break;
case t_bool:{
return u.b == (bool)v;
}break;
case t_int:{
return u.i8 == (int64)v;
}break;
case t_uint:{
return u.u8 == (uint64)v;
}break;
case t_double:{
return u.f8 == (double)v;
}break;
case t_array:{
if(v.t != t_array){
return false;
}else{
const lyramilk::data::array* ba = reinterpret_cast<const lyramilk::data::array*>(&u.ba);
const lyramilk::data::array* vba = reinterpret_cast<const lyramilk::data::array*>(&v.u.ba);
return *ba == *vba;
}
}break;
case t_map:{
if(v.t != t_map){
return false;
}else{
const lyramilk::data::map* bm = reinterpret_cast<const lyramilk::data::map*>(&u.bm);
const lyramilk::data::map* vbm = reinterpret_cast<const lyramilk::data::map*>(&v.u.bm);
if(bm->size() != vbm->size()) return false;
for(lyramilk::data::map::const_iterator it1 = vbm->begin(),it2 = bm->begin();it1 != vbm->end() && it2 != bm->end();++it1,++it2){
if(it1->first != it2->first || it1->second != it2->second) return false;
}
return true;
}
}break;
case t_user:{
return false;
}break;
case t_invalid:{
return t_invalid == v.t;
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator ==()",type_name(t).c_str()));
}
bool lyramilk::data::var::operator !=(const lyramilk::data::var& v) const throw(lyramilk::data::type_invalid)
{
return !(*this == v);
}
bool lyramilk::data::var::operator <(const lyramilk::data::var& v) const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
return bp->compare((lyramilk::data::chunk)v) < 0;
}break;
case t_str:{
const lyramilk::data::string* bs = reinterpret_cast<const lyramilk::data::string*>(&u.bs);
return bs->compare((lyramilk::data::string)v) < 0;
}break;
case t_wstr:{
const wstring* bw = reinterpret_cast<const wstring*>(&u.bw);
return bw->compare((wstring)v) < 0;
}break;
case t_array:{
if(v.t != t_array){
return t < v.t;
}else{
const array* ba = reinterpret_cast<const array*>(&u.ba);
const array* vba = reinterpret_cast<const array*>(&v.u.ba);
return *ba < *vba;
}
}break;
case t_map:{
if(v.t != t_map){
return t < v.t;
}else{
const map* bm = reinterpret_cast<const map*>(&u.bm);
const map* vbm = reinterpret_cast<const map*>(&v.u.bm);
if(bm->size() != vbm->size()) return false;
for(map::const_iterator it1 = vbm->begin(),it2 = bm->begin();it1 != vbm->end() && it2 != bm->end();++it1,++it2){
if(it2->first < it1->first) return false;
}
return bm->size() < vbm->size();
}
}break;
case t_bool:{
return u.b < (bool)v;
}break;
case t_int:{
return u.i8 < (int64)v;
}break;
case t_uint:{
return u.u8 < (uint64)v;
}break;
case t_double:{
return u.f8 < (double)v;
}break;
case t_invalid:{
return false;
}break;
default:
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator <()",type_name(t).c_str()));
}
}
lyramilk::data::var& lyramilk::data::var::operator =(const lyramilk::data::var& v)
{
return assign(v);
}
lyramilk::data::var& lyramilk::data::var::at(lyramilk::data::uint64 index) throw(lyramilk::data::type_invalid)
{
if(t == t_array){
array* ba = reinterpret_cast<array*>(&u.ba);
return ba->at(index);
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的索引类型%s[%s]","lyramilk::data::var::at()",type_name(t).c_str(),"t_uint"));
}
lyramilk::data::var& lyramilk::data::var::at(const lyramilk::data::string& index) throw(lyramilk::data::type_invalid)
{
if(t == t_map){
map* bm = reinterpret_cast<map*>(&u.bm);
return bm->operator[](index);
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的索引类型%s[%s]","lyramilk::data::var::at()",type_name(t).c_str(),"t_str"));
}
lyramilk::data::var& lyramilk::data::var::at(const wstring& index) throw(lyramilk::data::type_invalid)
{
if(t == t_map){
lyramilk::data::var str = index;
map* bm = reinterpret_cast<map*>(&u.bm);
return bm->operator[](str);
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的索引类型%s[%s]","lyramilk::data::var::at()",type_name(t).c_str(),"t_wstr"));
}
const lyramilk::data::var& lyramilk::data::var::at(lyramilk::data::uint64 index) const throw(lyramilk::data::type_invalid)
{
if(t == t_array){
const lyramilk::data::array* ba = reinterpret_cast<const lyramilk::data::array*>(&u.ba);
return ba->at(index);
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的索引类型%s[%s]","lyramilk::data::var::at()",type_name(t).c_str(),"t_uint"));
}
const lyramilk::data::var& lyramilk::data::var::at(const lyramilk::data::string& index) const throw(lyramilk::data::type_invalid)
{
if(t == t_map){
const lyramilk::data::map* bm = reinterpret_cast<const lyramilk::data::map*>(&u.bm);
map::const_iterator it = bm->find(index);
if (it != bm->end()) {
return it->second;
}
return lyramilk::data::var::nil;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的索引类型%s[%s]","lyramilk::data::var::at()",type_name(t).c_str(),"t_str"));
}
const lyramilk::data::var& lyramilk::data::var::at(const wstring& index) const throw(lyramilk::data::type_invalid)
{
if(t == t_map){
lyramilk::data::var str = index;
const map* bm = reinterpret_cast<const map*>(&u.bm);
map::const_iterator it = bm->find(str.str());
if (it != bm->end()) {
return it->second;
}
return lyramilk::data::var::nil;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的索引类型%s[%s]","lyramilk::data::var::at()",type_name(t).c_str(),"t_wstr"));
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::var& v)
{
if(this == &v) return *this;
vt newt = v.t;
switch(v.t){
case t_bin:
{
const lyramilk::data::chunk* vbp = reinterpret_cast<const lyramilk::data::chunk*>(&v.u.bp);
lyramilk::data::chunk cache = *vbp;
clear();
(new (u.bp) lyramilk::data::chunk)->swap(cache);
}
break;
case t_str:
{
const lyramilk::data::string* vbs = reinterpret_cast<const lyramilk::data::string*>(&v.u.bs);
lyramilk::data::string cache = *vbs;
clear();
(new (u.bs) lyramilk::data::string)->swap(cache);
}
break;
case t_wstr:
{
const lyramilk::data::wstring* vbw = reinterpret_cast<const lyramilk::data::wstring*>(&v.u.bw);
lyramilk::data::wstring cache = *vbw;
clear();
(new (u.bw) lyramilk::data::wstring)->swap(cache);
}
break;
case t_bool:
{
bool tmp = v.u.b;
clear();
u.b = tmp;
}
break;
case t_int:
{
int64 tmp = v.u.i8;
clear();
u.i8 = tmp;
}
break;
case t_uint:
{
uint64 tmp = v.u.u8;
clear();
u.u8 = tmp;
}
break;
case t_double:
{
double tmp = v.u.f8;
clear();
u.f8 = tmp;
}
break;
case t_array:
{
const lyramilk::data::array* vba = reinterpret_cast<const lyramilk::data::array*>(&v.u.ba);
lyramilk::data::array cache = *vba;
clear();
(new (u.ba) lyramilk::data::array)->swap(cache);
}
break;
case t_map:
{
const lyramilk::data::map* vbm = reinterpret_cast<const lyramilk::data::map*>(&v.u.bm);
lyramilk::data::map cache = *vbm;
clear();
(new (u.bm) lyramilk::data::map)->swap(cache);
}
break;
case t_user:
{
vu newu;
newu.pu = v.u.pu->clone();
clear();
u = newu;
}
break;
case t_invalid:
clear();
break;
default:
uint64 tu = v.u.u8;
clear();
u.u8 = tu;
}
t = newt;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const unsigned char* v)
{
clear();
t = t_str;
new (u.bp) lyramilk::data::chunk(v?v:(const unsigned char*)"");
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const char* v)
{
clear();
t = t_str;
new (u.bs) lyramilk::data::string(v?v:"");
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const wchar_t* v)
{
clear();
t = t_wstr;
new (u.bw) lyramilk::data::wstring(v?v:L"");
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::chunk& v)
{
clear();
t = t_bin;
new (u.bp) lyramilk::data::chunk(v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const string& v)
{
clear();
t = t_str;
new (u.bs) lyramilk::data::string(v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const wstring& v)
{
clear();
t = t_wstr;
new (u.bw) lyramilk::data::wstring(v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(bool v)
{
clear();
t = t_bool;
u.b = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(int8 v)
{
clear();
t = t_int;
u.i8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(uint8 v)
{
clear();
t = t_uint;
u.u8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(int16 v)
{
clear();
t = t_int;
u.i8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(uint16 v)
{
clear();
t = t_uint;
u.u8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(int32 v)
{
clear();
t = t_int;
u.i8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(uint32 v)
{
clear();
t = t_uint;
u.u8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(long v)
{
assign((lyramilk::data::intc<sizeof(long)>::t)v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(unsigned long v)
{
assign((lyramilk::data::intc<sizeof(unsigned long)>::ut)v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(int64 v)
{
clear();
t = t_int;
u.i8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(uint64 v)
{
clear();
t = t_uint;
u.u8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(double v)
{
clear();
t = t_double;
u.f8 = v;
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(float v)
{
assign((double)v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::array& v)
{
clear();
t = t_array;
new (u.ba) lyramilk::data::array(v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::map& v)
{
clear();
t = t_map;
new (u.bm) lyramilk::data::map(v);
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::stringdict& v)
{
clear();
t = t_map;
lyramilk::data::map* bm = new (u.bm) lyramilk::data::map(v.bucket_count());
stringdict::const_iterator it = v.begin();
for(;it!=v.end();++it){
bm->operator[](it->first) = it->second;
}
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::case_insensitive_unordered_map& v)
{
clear();
t = t_map;
lyramilk::data::map* bm = new (u.bm) lyramilk::data::map(v.bucket_count());
case_insensitive_unordered_map::const_iterator it = v.begin();
for(;it!=v.end();++it){
bm->operator[](it->first) = it->second;
}
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::case_insensitive_map& v)
{
clear();
t = t_map;
lyramilk::data::map* bm = new (u.bm) lyramilk::data::map();
case_insensitive_map::const_iterator it = v.begin();
for(;it!=v.end();++it){
bm->operator[](it->first) = it->second;
}
return *this;
}
lyramilk::data::var& lyramilk::data::var::assign(const lyramilk::data::datawrapper& v)
{
clear();
t = t_user;
u.pu = v.clone();
return *this;
}
/*lyramilk::data::var::operator lyramilk::data::chunk& () throw(lyramilk::data::type_invalid)
{
if(t != t_bin) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator lyramilk::data::chunk&()",type_name(t).c_str()));
return *u.p;
}*/
lyramilk::data::var::operator lyramilk::data::chunk() const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
return *bp;
}break;
case t_str:{
const lyramilk::data::string* bs = reinterpret_cast<const string*>(&u.bs);
return lyramilk::data::chunk((const unsigned char*)bs->c_str(),bs->size());
}break;
case t_wstr:{
const lyramilk::data::wstring* bw = reinterpret_cast<const wstring*>(&u.bw);
return lyramilk::data::chunk((const unsigned char*)bw->c_str(),(bw->size() << (int)lyramilk::data::intc<sizeof(wchar_t)>::square));
}break;
case t_bool:{
return lyramilk::data::chunk((const unsigned char*)&u.b,sizeof(u.b));
}break;
case t_int:{
int64 i8 = reverse_order(u.i8);
return lyramilk::data::chunk((const unsigned char*)&i8,sizeof(i8));
}break;
case t_uint:{
uint64 u8 = reverse_order(u.u8);
return lyramilk::data::chunk((const unsigned char*)&u8,sizeof(u8));
}break;
case t_double:{
return lyramilk::data::chunk((const unsigned char*)&u.f8,sizeof(u.f8));
}break;
case t_user:{
return u.pu->get_bytes();
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator lyramilk::data::chunk()",type_name(t).c_str()));
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator lyramilk::data::chunk()",type_name(t).c_str()));
}
/*lyramilk::data::var::operator string& () throw(lyramilk::data::type_invalid)
{
if(t != t_str) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator string&()",type_name(t).c_str()));
return *u.s;
}*/
lyramilk::data::var::operator string () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
return string((const char*)bp->c_str(),bp->size());
}break;
case t_str:{
const string* bs = reinterpret_cast<const string*>(&u.bs);
return *bs;
}break;
case t_wstr:{
const wstring* bw = reinterpret_cast<const wstring*>(&u.bw);
return string(u2a(*bw));
}break;
case t_bool:{
return u.b?"true":"false";
}break;
case t_int:{
char buff[256];
std::size_t fs = snprintf(buff,sizeof(buff),"%lld",u.i8);
if(fs < 256) return buff;
char* pbuff = (char*)calloc(1,fs + 1);
snprintf(pbuff,fs+1,"%lld",u.i8);
return pbuff;
}break;
case t_uint:{
char buff[256];
std::size_t fs = snprintf(buff,sizeof(buff),"%llu",u.u8);
if(fs < 256) return buff;
char* pbuff = (char*)calloc(1,fs + 1);
snprintf(pbuff,fs+1,"%llu",u.u8);
return pbuff;
}break;
case t_double:{
char buff[256];
std::size_t fs = snprintf(buff,sizeof(buff),"%f",u.f8);
if(fs < 256) return buff;
char* pbuff = (char*)calloc(1,fs + 1);
snprintf(pbuff,fs+1,"%f",u.f8);
return pbuff;
}break;
case t_array:{
const array* ba = reinterpret_cast<const array*>(&u.ba);
array::const_iterator it = ba->begin();
string str = "[";
if(it != ba->end()){
str += (string)*it;
for(++it;it!=ba->end();++it){
str += ",";
str += (string)*it;
}
}
str += "]";
return str;
}break;
case t_map:{
const map* bm = reinterpret_cast<const map*>(&u.bm);
string str = "{";
map::const_iterator it = bm->begin();
if(it != bm->end()){
str += (string)it->first + ":" + (string)it->second;
for(++it;it!=bm->end();++it){
str += "," + (string)it->first + ":" + (string)it->second;
}
}
str += "}";
return str;
}break;
case t_user:{
return u.pu->get_str();
}break;
case t_invalid:{
//throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator string()",type_name(t).c_str()));
return "";
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator string()",type_name(t).c_str()));
}
/*lyramilk::data::var::operator wstring& () throw(lyramilk::data::type_invalid)
{
if(t != t_wstr) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator wstring&()",type_name(t).c_str()));
return *u.w;
}*/
lyramilk::data::var::operator wstring () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
return wstring((const wchar_t*)bp->c_str(),(bp->size() << (int)lyramilk::data::intc<sizeof(wchar_t)>::square));
}break;
case t_str:{
const string* bs = reinterpret_cast<const string*>(&u.bs);
return a2u(*bs);
}break;
case t_wstr:{
const wstring* bw = reinterpret_cast<const wstring*>(&u.bw);
return *bw;
}break;
case t_bool:{
return u.b?L"true":L"false";
}break;
case t_int:{
wchar_t buff[256];
swprintf(buff,sizeof(buff),L"%lld",u.i8);
return buff;
}break;
case t_uint:{
wchar_t buff[256];
swprintf(buff,sizeof(buff),L"%llu",u.u8);
return buff;
}break;
case t_double:{
wchar_t buff[256];
swprintf(buff,sizeof(buff),L"%f",u.f8);
return buff;
}break;
case t_array:{
const array* ba = reinterpret_cast<const array*>(&u.ba);
array::const_iterator it = ba->begin();
wstring str = L"[";
if(it != ba->end()){
str += (wstring)*it;
for(++it;it!=ba->end();++it){
str += L",";
str += (wstring)*it;
}
}
str += L"]";
return str;
}break;
case t_map:{
const map* bm = reinterpret_cast<const map*>(&u.bm);
wstring str = L"{";
map::const_iterator it = bm->begin();
if(it != bm->end()){
wstring strfirst = lyramilk::data::var(it->first);
str += strfirst + L":" + (wstring)it->second;
for(++it;it!=bm->end();++it){
wstring strfirst = lyramilk::data::var(it->first);
str += L"," + strfirst + L":" + (wstring)it->second;
}
}
str += L"}";
return str;
}break;
case t_user:{
return u.pu->get_wstr();
}break;
case t_invalid:{
return L"";
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator wstring()",type_name(t).c_str()));
}
lyramilk::data::var::operator bool () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
if(sizeof(bool) > bp->size()) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator bool()",type_name(t).c_str()));
bool b;
memcpy(&b,bp->c_str(),sizeof(b));
return b; }break;
case t_str:{
const lyramilk::data::string* bs = reinterpret_cast<const lyramilk::data::string*>(&u.bs);
lyramilk::data::string w = *bs;
std::transform(bs->begin(),bs->end(),w.begin(),tolower);
if(w.compare("true") == 0) return true;
if(w.compare("false") == 0) return false;
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator bool()",type_name(t).c_str()));
}break;
case t_wstr:{
const lyramilk::data::wstring* bw = reinterpret_cast<const lyramilk::data::wstring*>(&u.bw);
lyramilk::data::wstring w = *bw;
std::transform(bw->begin(),bw->end(),w.begin(),towlower);
if(w.compare(L"true") == 0) return true;
if(w.compare(L"false") == 0) return false;
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator bool()",type_name(t).c_str()));
}break;
case t_bool:
case t_int:
case t_uint:
case t_double:{
return (int64)*this != 0;
}break;
case t_array:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator bool()",type_name(t).c_str()));
}break;
case t_map:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator bool()",type_name(t).c_str()));
}break;
case t_user:{
return u.pu->get_bool();
}break;
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator bool()",type_name(t).c_str()));
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator bool()",type_name(t).c_str()));
}
lyramilk::data::var::operator int8 () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:
case t_str:
case t_wstr:
case t_bool:
case t_int:
case t_uint:
case t_user:
case t_double:{
return (int8)(int64)*this;
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int8()",type_name(t).c_str()));
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int8()",type_name(t).c_str()));
}
lyramilk::data::var::operator uint8 () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:
case t_str:
case t_wstr:
case t_bool:
case t_int:
case t_uint:
case t_user:
case t_double:{
return (uint8)(int64)*this;
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator uint8()",type_name(t).c_str()));
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator uint8()",type_name(t).c_str()));
}
lyramilk::data::var::operator int16 () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:
case t_str:
case t_wstr:
case t_bool:
case t_int:
case t_uint:
case t_user:
case t_double:{
return (int16)(int64)*this;
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int16()",type_name(t).c_str()));
}
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int16()",type_name(t).c_str()));
}
lyramilk::data::var::operator uint16 () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:
case t_str:
case t_wstr:
case t_bool:
case t_int:
case t_uint:
case t_user:
case t_double:{
return (uint16)(int64)*this;
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator uint16()",type_name(t).c_str()));
}
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator uint16()",type_name(t).c_str()));
}
lyramilk::data::var::operator int32 () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:
case t_str:
case t_wstr:
case t_bool:
case t_int:
case t_uint:
case t_user:
case t_double:{
return (int32)(int64)*this;
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int32()",type_name(t).c_str()));
}
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int32()",type_name(t).c_str()));
}
lyramilk::data::var::operator uint32 () const throw(lyramilk::data::type_invalid)
{
return (uint32)(int32)*this;
}
lyramilk::data::var::operator long () const throw(lyramilk::data::type_invalid)
{
return (lyramilk::data::intc<sizeof(long)>::t)*this;
}
lyramilk::data::var::operator unsigned long () const throw(lyramilk::data::type_invalid)
{
return (lyramilk::data::intc<sizeof(unsigned long)>::ut)*this;
}
lyramilk::data::var::operator int64 () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_int:{
return u.i8;
}break;
case t_uint:{
return u.u8;
}break;
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
if(sizeof(int64) > bp->size()) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int64()",type_name(t).c_str()));
int64 i8;
memcpy(&i8,bp->c_str(),sizeof(i8));
return i8;
}break;
case t_str:{
const string* bs = reinterpret_cast<const string*>(&u.bs);
char* p;
return strtoll(bs->c_str(),&p,10);
}break;
case t_wstr:{
const wstring* bw = reinterpret_cast<const wstring*>(&u.bw);
wchar_t* p;
return wcstoll(bw->c_str(),&p,10);
}break;
case t_bool:{
return u.b;
}break;
case t_double:{
return (int64)u.f8;
}break;
case t_user:{
return u.pu->get_int();
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int64()",type_name(t).c_str()));
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int64()",type_name(t).c_str()));
}
lyramilk::data::var::operator uint64 () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_int:{
return u.i8;
}break;
case t_uint:{
return u.u8;
}break;
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
if(sizeof(int64) > bp->size()) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int64()",type_name(t).c_str()));
uint64 u8;
memcpy(&u8,bp->c_str(),sizeof(u8));
return u8;
}break;
case t_str:{
const string* bs = reinterpret_cast<const string*>(&u.bs);
char* p;
return strtoull(bs->c_str(),&p,10);
}break;
case t_wstr:{
const wstring* bw = reinterpret_cast<const wstring*>(&u.bw);
wchar_t* p;
return wcstoull(bw->c_str(),&p,10);
}break;
case t_bool:{
return u.b;
}break;
case t_double:{
return (int64)u.f8;
}break;
case t_user:{
return u.pu->get_int();
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int64()",type_name(t).c_str()));
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator int64()",type_name(t).c_str()));
}
lyramilk::data::var::operator double () const throw(lyramilk::data::type_invalid)
{
switch(t){
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
if(sizeof(int64) > bp->size()) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator uint64()",type_name(t).c_str()));
double f8;
memcpy(&f8,bp->c_str(),sizeof(f8));
return f8;
}break;
case t_str:{
const string* bs = reinterpret_cast<const string*>(&u.bs);
char* p;
return strtod(bs->c_str(),&p);
}break;
case t_wstr:{
const wstring* bw = reinterpret_cast<const wstring*>(&u.bw);
wchar_t* p;
return wcstod(bw->c_str(),&p);
}break;
case t_bool:{
return u.b;
}break;
case t_int:{
return (double)u.i8;
}break;
case t_uint:{
return (double)u.u8;
}break;
case t_double:{
return u.f8;
}break;
case t_user:{
return u.pu->get_double();
}break;
case t_array:
case t_map:
case t_invalid:{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator double()",type_name(t).c_str()));
}break;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的子类型%s","lyramilk::data::var::operator double()",type_name(t).c_str()));
}
lyramilk::data::var::operator float () const throw(lyramilk::data::type_invalid)
{
return (float)(double)*this;
}
lyramilk::data::var::operator lyramilk::data::var::array& () throw(lyramilk::data::type_invalid)
{
array* ba = reinterpret_cast<array*>(&u.ba);
if(t == t_array) return *ba;
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:%s类型无法转换为%s类型","lyramilk::data::var::operator lyramilk::data::var::array()",type_name(t).c_str(),type_name(t_array).c_str()));
}
lyramilk::data::var::operator const lyramilk::data::var::array& () const throw(lyramilk::data::type_invalid)
{
const array* ba = reinterpret_cast<const array*>(&u.ba);
if(t == t_array) return *ba;
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:%s类型无法转换为%s类型","lyramilk::data::var::operator lyramilk::data::var::array()",type_name(t).c_str(),type_name(t_array).c_str()));
}
lyramilk::data::var::operator lyramilk::data::var::map& () throw(lyramilk::data::type_invalid)
{
map* bm = reinterpret_cast<map*>(&u.bm);
if(t == t_map) return *bm;
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:%s类型无法转换为%s类型","lyramilk::data::var::operator lyramilk::data::var::map()",type_name(t).c_str(),type_name(t_map).c_str()));
}
lyramilk::data::var::operator const lyramilk::data::map& () const throw(lyramilk::data::type_invalid)
{
const map* bm = reinterpret_cast<const map*>(&u.bm);
if(t == t_map) return *bm;
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:%s类型无法转换为%s类型","lyramilk::data::var::operator lyramilk::data::var::map()",type_name(t).c_str(),type_name(t_map).c_str()));
}
lyramilk::data::chunk lyramilk::data::var::conv(const lyramilk::data::chunk& if_not_compat) const
{
if(type_like(t_bin)) return *this;
return if_not_compat;
}
lyramilk::data::string lyramilk::data::var::conv(const lyramilk::data::string& if_not_compat) const
{
if(type_like(t_str)) return *this;
return if_not_compat;
}
lyramilk::data::wstring lyramilk::data::var::conv(const lyramilk::data::wstring& if_not_compat) const
{
if(type_like(t_str)) return *this;
return if_not_compat;
}
lyramilk::data::string lyramilk::data::var::conv(const char* if_not_compat) const
{
if(type_like(t_str)) return *this;
return if_not_compat;
}
lyramilk::data::string lyramilk::data::var::conv(char* if_not_compat) const
{
if(type_like(t_str)) return *this;
return if_not_compat;
}
lyramilk::data::wstring lyramilk::data::var::conv(const wchar_t* if_not_compat) const
{
if(type_like(t_str)) return *this;
return if_not_compat;
}
lyramilk::data::wstring lyramilk::data::var::conv(wchar_t* if_not_compat) const
{
if(type_like(t_str)) return *this;
return if_not_compat;
}
lyramilk::data::chunk lyramilk::data::var::conv(const unsigned char* if_not_compat) const
{
if(type_like(t_bin)) return *this;
return if_not_compat;
}
lyramilk::data::chunk lyramilk::data::var::conv(unsigned char* if_not_compat) const
{
if(type_like(t_bin)) return *this;
return if_not_compat;
}
bool lyramilk::data::var::conv(bool if_not_compat) const
{
if(type_like(t_bool)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::int8 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::uint8 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::int16 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::uint16 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::int32 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::uint32 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::int64 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(lyramilk::data::uint64 if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(long if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
lyramilk::data::uint64 lyramilk::data::var::conv(unsigned long if_not_compat) const
{
if(type_like(t_int)) return *this;
return if_not_compat;
}
double lyramilk::data::var::conv(double if_not_compat) const
{
if(type_like(t_double)) return *this;
return if_not_compat;
}
lyramilk::data::var::array& lyramilk::data::var::conv(lyramilk::data::var::array& if_not_compat)
{
if(!type_like(t_array)) return if_not_compat;
return *this;
}
lyramilk::data::var::map& lyramilk::data::var::conv(lyramilk::data::var::map& if_not_compat)
{
if(!type_like(t_map)) return if_not_compat;
return *this;
}
const lyramilk::data::var::array& lyramilk::data::var::conv(const lyramilk::data::var::array& if_not_compat) const
{
if(!type_like(t_array)) return if_not_compat;
return *this;
}
const lyramilk::data::var::map& lyramilk::data::var::conv(const lyramilk::data::var::map& if_not_compat) const
{
if(!type_like(t_map)) return if_not_compat;
return *this;
}
lyramilk::data::datawrapper* lyramilk::data::var::userdata() const
{
if(t != t_user) return null;
return u.pu;
}
lyramilk::data::var& lyramilk::data::var::operator[](const char* index) throw(lyramilk::data::type_invalid)
{
return at(index);
}
lyramilk::data::var& lyramilk::data::var::operator[](const wchar_t* index) throw(lyramilk::data::type_invalid)
{
return at(index);
}
lyramilk::data::var& lyramilk::data::var::operator[](const lyramilk::data::string& index) throw(lyramilk::data::type_invalid)
{
return at(index);
}
lyramilk::data::var& lyramilk::data::var::operator[](const lyramilk::data::wstring& index) throw(lyramilk::data::type_invalid)
{
return at(index);
}
lyramilk::data::var& lyramilk::data::var::operator[](lyramilk::data::uint64 index) throw(lyramilk::data::type_invalid)
{
return at(index);
}
lyramilk::data::var& lyramilk::data::var::operator[](int index) throw(lyramilk::data::type_invalid)
{
return at((lyramilk::data::uint64)index);
}
const lyramilk::data::var& lyramilk::data::var::operator[](const char* index) const throw(lyramilk::data::type_invalid)
{
return at(index);
}
const lyramilk::data::var& lyramilk::data::var::operator[](const wchar_t* index) const throw(lyramilk::data::type_invalid)
{
return at(index);
}
const lyramilk::data::var& lyramilk::data::var::operator[](const lyramilk::data::string& index) const throw(lyramilk::data::type_invalid)
{
return at(index);
}
const lyramilk::data::var& lyramilk::data::var::operator[](const lyramilk::data::wstring& index) const throw(lyramilk::data::type_invalid)
{
return at(index);
}
const lyramilk::data::var& lyramilk::data::var::operator[](lyramilk::data::uint64 index) const throw(lyramilk::data::type_invalid)
{
return at(index);
}
const lyramilk::data::var& lyramilk::data::var::operator[](int index) const throw(lyramilk::data::type_invalid)
{
return at((lyramilk::data::uint64)index);
}
lyramilk::data::var::vt lyramilk::data::var::type() const
{
return t;
}
lyramilk::data::string lyramilk::data::var::type_name(lyramilk::data::var::vt nt)
{
switch(nt){
case t_bin:
return "t_bin";
case t_str:
return "t_str";
case t_wstr:
return "t_wstr";
case t_bool:
return "t_bool";
case t_int:
return "t_int";
case t_uint:
return "t_uint";
case t_double:
return "t_double";
case t_array:
return "t_array";
case t_map:
return "t_map";
case t_user:
return "t_user";
case t_invalid:
return "t_invalid";
default:
return "t_unknow ";
}
}
lyramilk::data::string lyramilk::data::var::type_name() const
{
if(t == t_user) {
return type_name(t) + "(" + u.pu->name() + ")";
}
return type_name(t);
}
lyramilk::data::var& lyramilk::data::var::type(lyramilk::data::var::vt nt) throw(lyramilk::data::type_invalid)
{
if(t == nt) return *this;
switch(nt){
case t_bin:{
lyramilk::data::chunk t = *this;
clear();
new (u.bp) lyramilk::data::chunk(t);
}break;
case t_str:{
lyramilk::data::string t = *this;
clear();
new (u.bs) lyramilk::data::string(t);
}break;
case t_wstr:{
lyramilk::data::wstring t = *this;
clear();
new (u.bw) lyramilk::data::wstring(t);
}break;
case t_bool:{
bool t = *this;
clear();
u.b = t;
}break;
case t_int:{
lyramilk::data::int64 t = *this;
clear();
u.i8 = t;
}break;
case t_uint:{
lyramilk::data::uint64 t = *this;
clear();
u.u8 = t;
}break;
case t_double:{
double t = *this;
clear();
u.f8 = t;
}break;
case t_array:{
if(type_like(t_array)){
array t = *this;
clear();
new (u.ba) lyramilk::data::array(t);
}else{
clear();
new (u.ba) lyramilk::data::array();
}
}break;
case t_map:{
if(type_like(t_map)){
lyramilk::data::map t = *this;
clear();
new (u.bm) lyramilk::data::map(t);
}else{
clear();
new (u.bm) lyramilk::data::map();
}
}break;
case t_user:{
if(t != nt){
clear();
}
}break;
case t_invalid:
clear();
break;
default:
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:错误的新类型%d","lyramilk::data::var::operator lyramilk::data::var::type()",nt));
}
t = nt;
return *this;
}
bool lyramilk::data::var::type_like(lyramilk::data::var::vt nt) const
{
if((nt == t_bin || nt == t_str || nt == t_wstr || nt == t_int || nt == t_uint || nt == t_double) && (t == t_bin || t == t_str || t == t_wstr || t == t_int || t == t_uint || t == t_double)){
return true;
}
if(nt == t_user && t == t_user){
return true;
}
if(nt == t_any) return true;
if(nt == t_invalid) return false;
if(nt == t_valid) return true;
if(t == t_user) return u.pu->type_like(nt);
if(nt == t) return true;
return false;
}
lyramilk::data::var::array::size_type lyramilk::data::var::size() const throw(lyramilk::data::type_invalid)
{
if(t == t_array){
const lyramilk::data::array* ba = reinterpret_cast<const lyramilk::data::array*>(&u.ba);
return ba->size();
}
if(t == t_map){
const lyramilk::data::map* bm = reinterpret_cast<const lyramilk::data::map*>(&u.bm);
return bm->size();
}
return 0;
}
lyramilk::data::string lyramilk::data::var::str() const
{
return *this;
}
void lyramilk::data::var::clear()
{
if(t == t_invalid){
return;
}
switch(t){
case t_bool:
case t_int:
case t_uint:
case t_double:
case t_invalid:
break;
case t_bin:
{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
bp->~chunk();
}
break;
case t_str:
{
const lyramilk::data::string* bs = reinterpret_cast<const lyramilk::data::string*>(&u.bs);
bs->~string();
}
break;
case t_wstr:
{
const lyramilk::data::wstring* bw = reinterpret_cast<const lyramilk::data::wstring*>(&u.bw);
bw->~wstring();
}
break;
case t_array:
{
const lyramilk::data::array* ba = reinterpret_cast<const lyramilk::data::array*>(&u.ba);
ba->~array();
}
break;
case t_map:
{
const lyramilk::data::map* bm = reinterpret_cast<const lyramilk::data::map*>(&u.bm);
bm->~map();
}
break;
case t_user:
{
u.pu->destory();
}
break;
}
t = t_invalid;
}
/* 序列化相关 */
bool inline is_igendian()
{
union{
short s;
char c[1];
}u;
u.s = 1;
return u.c[0] == 0;
}
const bool g_igendian = is_igendian();
typedef unsigned short array_size_type;
typedef unsigned int string_size_type;
template <typename T>
void write(lyramilk::data::ostream& os,T& t)
{
os.write((const char*)&t,sizeof(T));
}
template <typename T>
bool read(lyramilk::data::istream& is,T& t)
{
is.read((char*)&t,sizeof(T));
return is.gcount() == sizeof(T);
}
bool lyramilk::data::var::_serialize(ostream& os) const throw(lyramilk::data::type_invalid)
{
if((t&0x7f) != t) throw lyramilk::data::type_invalid(lyramilk::kdict("%s:不支持的类型%d","lyramilk::data::var::serialize()",(t&0x7f)));
unsigned char m;
m = g_igendian<<7;
m |= t&0x7f;
switch(t){
case t_bin:{
const lyramilk::data::chunk* bp = reinterpret_cast<const lyramilk::data::chunk*>(&u.bp);
string_size_type size = (string_size_type)bp->size();
write(os,m);
write(os,size);
os.write((const char*)bp->c_str(),size);
return true;
}break;
case t_str:{
const lyramilk::data::string* bs = reinterpret_cast<const lyramilk::data::string*>(&u.bs);
lyramilk::data::string utf8str = a2t(*bs);
string_size_type size = (string_size_type)utf8str.size();
write(os,m);
write(os,size);
os.write(utf8str.c_str(),size);
return true;
}break;
case t_wstr:{
const lyramilk::data::wstring* bw = reinterpret_cast<const lyramilk::data::wstring*>(&u.bw);
lyramilk::data::string utf8str = u2t(*bw);
string_size_type size = (string_size_type)utf8str.size();
write(os,m);
write(os,size);
os.write(utf8str.c_str(),size);
return true;
}break;
case t_bool:
case t_int:
case t_uint:{
write(os,m);
write(os,u.u8);
return true;
}break;
case t_double:{
write(os,m);
write(os,u.f8);
return true;
}break;
case t_array:{
const lyramilk::data::array* ba = reinterpret_cast<const lyramilk::data::array*>(&u.ba);
array_size_type size = (array_size_type)ba->size();
write(os,m);
write(os,size);
array::const_iterator it = ba->begin();
for(;it != ba->end();++it){
if(!it->_serialize(os)) return false;
}
return true;
}break;
case t_map:{
const lyramilk::data::map* bm = reinterpret_cast<const lyramilk::data::map*>(&u.bm);
array_size_type size = (array_size_type)bm->size();
write(os,m);
write(os,size);
map::const_iterator it = bm->begin();
for(;it != bm->end();++it){
{
string utf8str = a2t(it->first);
string_size_type size = (string_size_type)utf8str.size();
unsigned char mstr = (g_igendian<<7)|(t_str&0x7f);
write(os,mstr);
write(os,size);
os.write((const char*)utf8str.c_str(),size);
}
if(!it->second._serialize(os)) return false;
}
return true;
}break;
case t_user:
return true;
case t_invalid:
return false;
}
throw lyramilk::data::type_invalid(lyramilk::kdict("%s:不支持的类型%d","lyramilk::data::var::serialize()",(t&0x7f)));
}
bool lyramilk::data::var::_deserialize(istream& is)
{
unsigned char m;
if(!read(is,m)) return false;
vt ts = (vt)(m&0x7f);
bool r = (g_igendian?1:0) != (m>>7);
switch(ts){
case t_bin:{
string_size_type size = 0;
if(!read(is,size)) return false;
if(r) size = reverse_order(size);
lyramilk::data::chunk binstr;
binstr.resize(size);
is.read((char*)binstr.c_str(),size);
if(is.gcount() == size){
assign(binstr);
return true;
}
return false;
}break;
case t_str:{
string_size_type size = 0;
if(!read(is,size)) return false;
if(r) size = reverse_order(size);
lyramilk::data::string utf8str;
utf8str.resize(size);
is.read((char*)utf8str.c_str(),size);
if(is.gcount() == size){
lyramilk::data::string localstr = t2a(utf8str);
assign(localstr);
return true;
}
return false;
}break;
case t_wstr:{
string_size_type size = 0;
if(!read(is,size)) return false;
if(r) size = reverse_order(size);
lyramilk::data::string utf8str;
utf8str.resize(size);
is.read((char*)utf8str.c_str(),size);
if(is.gcount() == size){
lyramilk::data::string localstr = t2a(utf8str);
assign(wstring(a2u(localstr)));
return true;
}
return false;
}break;
case t_bool:
case t_int:
case t_uint:{
if(!read(is,u.u8)) return false;
if(r) u.u8 = reverse_order(u.u8);
t = ts;
return true;
}break;
case t_double:{
if(!read(is,u.f8)) return false;
t = ts;
return true;
}break;
case t_array:{
array_size_type size = 0;
if(!read(is,size)) return false;
if(r) size = reverse_order(size);
type(t_array);
array* ba = reinterpret_cast<array*>(&u.ba);
for(array_size_type i=0;i<size;++i){
lyramilk::data::var d;
if(!d._deserialize(is)){
clear();
return false;
}
ba->push_back(d);
}
t = ts;
return true;
}break;
case t_map:{
array_size_type size = 0;
if(!read(is,size)) return false;
if(r) size = reverse_order(size);
type(t_map);
map* bm = reinterpret_cast<map*>(&u.bm);
for(array_size_type i=0;i<size;++i){
lyramilk::data::var key;
lyramilk::data::var value;
if(!(key._deserialize(is) && value._deserialize(is))){
clear();
return false;
}
bm->operator[](key) = value;
}
t = ts;
return true;
}break;
case t_user:
return true;
case t_invalid:
return false;
}
return false;
}
bool lyramilk::data::var::serialize(ostream& os) const throw(lyramilk::data::type_invalid)
{
ostream::streamoff bpos = os.tellp();
int32 size = 0;
write(os,size);
bool ret = _serialize(os);
if(ret){
ostream::streamoff epos = os.tellp();
os.seekp(bpos,ostream::beg);
size = (int32)(epos - bpos - sizeof(size));
if(size > 0){
size = htonl(size);
write(os,size);
os.seekp(epos,ostream::beg);
if(os.good()) return true;
}
}
os.clear();
os.seekp(bpos,ostream::beg);
return false;
}
bool lyramilk::data::var::deserialize(istream& is)
{
istream::streamoff bpos = is.tellg();
is.seekg(0,istream::end);
istream::streamoff epos = is.tellg();
is.seekg(bpos,istream::beg);
int32 objsize = 0;
if(read(is,objsize)){
objsize = ntohl(objsize);
int32 realsize = (int32)(epos - bpos - sizeof(objsize));
if(objsize <= realsize){
if(_deserialize(is)){
return true;
}
}
}
is.clear();
is.seekg(bpos,istream::beg);
return false;
}
void lyramilk::data::var::dump(lyramilk::data::ostream& os) const
{
os << str() << std::endl;
}
lyramilk::data::strings inline split(const lyramilk::data::string& data,const lyramilk::data::string& sep)
{
lyramilk::data::strings lines;
std::size_t posb = 0;
do{
std::size_t poscrlf = data.find(sep,posb);
if(poscrlf == data.npos){
lyramilk::data::string newline = data.substr(posb);
posb = poscrlf;
lines.push_back(newline);
}else{
lyramilk::data::string newline = data.substr(posb,poscrlf - posb);
posb = poscrlf + sep.size();
lines.push_back(newline);
}
}while(posb != data.npos);
return lines;
}
lyramilk::data::strings inline pathof(const lyramilk::data::string& varpath) throw(lyramilk::data::type_invalid)
{
lyramilk::data::strings ret;
lyramilk::data::strings v = split(varpath,"/");
lyramilk::data::strings::iterator it = v.begin();
if(it==v.end()) return ret;
while(it!=v.end()){
if(it->compare(".") == 0 || it->empty()){
++it;
continue;
}
ret.push_back(*it);
break;
}
for(++it;it!=v.end();++it){
if(it->compare(".") == 0 || it->empty()) continue;
if(it->compare("..") == 0 && !ret.empty()){
ret.pop_back();
continue;
}
ret.push_back(*it);
}
return ret;
}
lyramilk::data::var& lyramilk::data::var::path(const lyramilk::data::string& varpath) throw(lyramilk::data::type_invalid)
{
lyramilk::data::strings fields = pathof(varpath);
//如果前面的回退无法清除,说明想要的值越过了根,不允许。
if(!fields.empty() && fields.at(0).compare("..") == 0){
throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径错误,试图越过了根结点:%s","lyramilk::data::var::path()",varpath.c_str()));
}
//如果路径表达式为空或路径表达式只表达一个目录,则直接返回根。
if(fields.size() == 0){
return *this;
}
//此时的fields中包含且仅包含枝节点。
lyramilk::data::strings::iterator it = fields.begin();
//如果var是空的
lyramilk::data::var* p = this;
/*
if(p->type() == t_invalid){
p->type(t_map);
}
if((p->type() & (t_map | t_array)) == 0) throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径:根元素不是t_map或t_array(%s)","lyramilk::data::var::path()",varpath.c_str()));
*/
for(;it!=fields.end();++it){
if(p->type() == t_array){
lyramilk::data::string& str = *it;
if(str.find_first_not_of("0123456789") != str.npos){
throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径:t_array类型只能接收纯整数的字符串形式(%s)","lyramilk::data::var::path()",varpath.c_str()));
}
unsigned int index = atoi(str.c_str());
lyramilk::data::array* ba = reinterpret_cast<lyramilk::data::array*>(&p->u.ba);
if(ba->size() == index){
ba->push_back(nil);
}else if(ba->size() < index + 1){
throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径:t_array类型越界(%s)","lyramilk::data::var::path()",varpath.c_str()));
}
p = &ba->at(index);
}else if(p->type() == t_map){
lyramilk::data::map* bm = reinterpret_cast<lyramilk::data::map*>(&p->u.bm);
p = &bm->operator[](*it);
}else if(p->type() == t_invalid){
lyramilk::data::string& str = *it;
if(str.find_first_not_of("0123456789") == str.npos){
unsigned int index = atoi(str.c_str());
p->type(t_array);
lyramilk::data::array* ba = reinterpret_cast<lyramilk::data::array*>(&p->u.ba);
if(ba->size() == index){
ba->push_back(nil);
p = &ba->back();
}else if(ba->size() < index - 1){
p = &ba->operator[](index);
}
}else{
p->type(t_map);
lyramilk::data::map* bm = reinterpret_cast<lyramilk::data::map*>(&p->u.bm);
p = &bm->operator[](str);
}
}else{
throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径:%s","lyramilk::data::var::path()",varpath.c_str()));
}
}
return *p;
}
const lyramilk::data::var& lyramilk::data::var::path(const lyramilk::data::string& varpath) const throw(lyramilk::data::type_invalid)
{
lyramilk::data::strings fields = pathof(varpath);
//如果前面的回退无法清除,说明想要的值越过了根,不允许。
if(!fields.empty() && fields.at(0).compare("..") == 0){
throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径错误,试图越过了根结点:%s","lyramilk::data::var::path()",varpath.c_str()));
}
//如果路径表达式为空或路径表达式只表达一个目录,则直接返回根。
if(fields.size() == 0){
return *this;
}
//此时的fields中包含且仅包含枝节点。
lyramilk::data::strings::iterator it = fields.begin();
//如果var是空的
const lyramilk::data::var* p = this;
/*
if(p->type() == t_invalid){
p->type(t_map);
}
if((p->type() & (t_map | t_array)) == 0) throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径:根元素不是t_map或t_array(%s)","lyramilk::data::var::path()",varpath.c_str()));
*/
for(;it!=fields.end();++it){
if(p->type() == t_array){
lyramilk::data::string& str = *it;
if(str.find_first_not_of("0123456789") != str.npos){
throw lyramilk::data::type_invalid(lyramilk::kdict("%s 路径:t_array类型只能接收纯整数的字符串形式(%s)","lyramilk::data::var::path()",varpath.c_str()));
}
unsigned int index = atoi(str.c_str());
const array* ba = reinterpret_cast<const array*>(&u.ba);
if(ba->size() <= index){
return lyramilk::data::var::nil;
}
p = &ba->at(index);
}else if(p->type() == t_map){
const map* bm = reinterpret_cast<const map*>(&u.bm);
map::const_iterator it_map = bm->find(*it);
if(it_map == bm->end()){
return lyramilk::data::var::nil;
}
p = &it_map->second;
}else{
return lyramilk::data::var::nil;
}
}
return *p;
}
template < >
lyramilk::data::chunk& lyramilk::data::var::as<lyramilk::data::chunk&>() throw(lyramilk::data::type_invalid)
{
if(t != t_bin) throw lyramilk::data::type_invalid(lyramilk::kdict("as取引用时无法转换类型"));
lyramilk::data::chunk* bp = reinterpret_cast<lyramilk::data::chunk*>(&u.bp);
return *bp;
}
template < >
lyramilk::data::string& lyramilk::data::var::as<lyramilk::data::string&>() throw(lyramilk::data::type_invalid)
{
if(t != t_str) throw lyramilk::data::type_invalid(lyramilk::kdict("as取引用时无法转换类型"));
lyramilk::data::string* bs = reinterpret_cast<lyramilk::data::string*>(&u.bs);
return *bs;
}
template < >
lyramilk::data::wstring& lyramilk::data::var::as<lyramilk::data::wstring&>() throw(lyramilk::data::type_invalid)
{
if(t != t_wstr) throw lyramilk::data::type_invalid(lyramilk::kdict("as取引用时无法转换类型"));
lyramilk::data::wstring* bw = reinterpret_cast<lyramilk::data::wstring*>(&u.bw);
return *bw;
}
//}} //namespace
std::ostream& operator << (std::ostream& os,const lyramilk::data::var& t)
{
return os << t.str();
}
std::istream& operator >> (std::istream& is, lyramilk::data::var& t)
{
char buff[4096];
lyramilk::data::string str;
while(is){
is.read(buff,4096);
str.append(buff,(unsigned int)is.gcount());
}
t = str;
return is;
}
std::ostream& operator << (std::ostream& os, const lyramilk::data::map& t)
{
return os << lyramilk::data::var(t);
}
std::ostream& operator << (std::ostream& os, const lyramilk::data::array& t)
{
return os << lyramilk::data::var(t);
}
| 25.382416 | 194 | 0.642599 | [
"vector",
"transform"
] |
127d891f7ce1b02032dc18dc37965766e2d21b90 | 3,665 | cpp | C++ | src/Physics/StringGL.cpp | william-taylor/interactive-physical-modelling | d03087bb2329b5c13fa54c042aebed148913e516 | [
"Apache-2.0"
] | null | null | null | src/Physics/StringGL.cpp | william-taylor/interactive-physical-modelling | d03087bb2329b5c13fa54c042aebed148913e516 | [
"Apache-2.0"
] | null | null | null | src/Physics/StringGL.cpp | william-taylor/interactive-physical-modelling | d03087bb2329b5c13fa54c042aebed148913e516 | [
"Apache-2.0"
] | 1 | 2018-04-09T01:30:12.000Z | 2018-04-09T01:30:12.000Z |
#include "StringGL.h"
StringGL::StringGL(std::string fontname, std::string texture)
: object(nullptr)
{
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindVertexArray(0);
setColour(0, 0, 0, 1);
prepareFont(fontname, texture);
}
StringGL::~StringGL()
{
if (vbo != 0 && vao != 0)
{
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
}
}
void StringGL::prepareFont(std::string fontname, std::string texture)
{
if (!fontname.empty() && !texture.empty())
{
this->fontname = fontname;
document = new tinyxml2::XMLDocument();
document->LoadFile(fontname.c_str());
sprite = TextureManagerGL::get()->createTexture(texture, GL_CLAMP_TO_EDGE);
}
}
GLvoid StringGL::setParameters(ObjectGL * object)
{
this->object = object;
}
GLvoid StringGL::prepare()
{
GLchar * vs = "data/shaders/text.vert";
GLchar * fs = "data/shaders/text.frag";
object->setShaders(vs, fs);
}
void StringGL::setString(std::string text, int spacing)
{
if (!text.empty())
{
vec2 position = object->getPosition();
std::vector<vec4> positions;
positions.reserve(text.size() * 4);
height = 0;
width = 0;
tinyxml2::XMLElement * start = document->FirstChildElement("fontMetrics")->FirstChildElement("character");
for (auto i = 0u; i < text.size(); i++)
{
tinyxml2::XMLElement * element = start;
for (auto b = 0; b < (int)text[i] - 32; b++)
{
element = element->NextSiblingElement();
}
GLfloat x = atof(element->FirstChildElement("x")->GetText());
GLfloat w = atof(element->FirstChildElement("width")->GetText()) + spacing;
GLfloat y = sprite->height - atof(element->FirstChildElement("y")->GetText());
GLfloat h = atof(element->FirstChildElement("height")->GetText());
GLfloat realX = (GLfloat)x / sprite->width;
GLfloat realY = (GLfloat)y / sprite->height;
GLfloat realW = (GLfloat)(x + w) / sprite->width;
GLfloat realH = (GLfloat)(y - h) / sprite->height;
positions.push_back(vec4(position, vec2(realX, realH)));
positions.push_back(vec4(position + vec2(0, h), vec2(realX, realY)));
positions.push_back(vec4(position + vec2(w, 0), vec2(realW, realH)));
positions.push_back(vec4(position + vec2(w, h), vec2(realW, realY)));
height += h;
width += w;
position += vec2(w, 0);
}
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vec4) * positions.size(), &positions[0], GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glBindVertexArray(0);
height /= text.size();
this->text = text;
}
}
GLvoid StringGL::setColour(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
{
colour[0] = r;
colour[1] = g;
colour[2] = b;
colour[3] = a;
}
GLuint StringGL::getHeight()
{
return(height);
}
GLuint StringGL::getWidth()
{
return(width);
}
GLuint StringGL::getTextureID()
{
return sprite->uniqueID;
}
GLuint StringGL::getStringLength()
{
return(text.size() * 4);
}
GLuint StringGL::getVertexArray()
{
return vao;
}
ObjectGL * StringGL::getObject()
{
return object;
}
std::string StringGL::getString()
{
return text;
}
GLfloat* StringGL::getColour()
{
return colour;
} | 24.271523 | 114 | 0.59427 | [
"object",
"vector"
] |
128486664173fd47c618ab39e9c985b28cc32416 | 4,495 | cc | C++ | src/common/chemistry/reactions/secondary_species.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/common/chemistry/reactions/secondary_species.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | src/common/chemistry/reactions/secondary_species.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | /*
Chemistry
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Base class for secondary species (aqueous equilibrium complexes,
minerals.
*/
#include <iostream>
#include <iomanip>
#include <sstream>
#include "chemistry_exception.hh"
#include "exceptions.hh"
#include "matrix_block.hh"
#include "secondary_species.hh"
namespace Amanzi {
namespace AmanziChemistry {
SecondarySpecies::SecondarySpecies()
: Species(),
ncomp_(0), // # components in reaction
h2o_stoich_(0.0),
lnK_(0.0),
lnQK_(0.0),
logK_(0.0) {
species_names_.clear();
species_ids_.clear();
stoichiometry_.clear();
logK_array_.clear();
}
SecondarySpecies::SecondarySpecies(const SpeciesName in_name,
const SpeciesId in_id,
const std::vector<SpeciesName>& in_species,
const std::vector<double>& in_stoichiometries,
const std::vector<SpeciesId>& in_species_ids,
const double in_h2o_stoich,
const double in_charge,
const double in_mol_wt,
const double in_size,
const double in_logK)
: Species(in_id, in_name, in_charge, in_mol_wt, in_size),
h2o_stoich_(in_h2o_stoich),
lnK_(0.0),
lnQK_(0.0),
logK_(in_logK) {
ncomp(static_cast<int>(in_species.size()));
// species names
for (std::vector<SpeciesName>::const_iterator i = in_species.begin();
i != in_species.end(); i++) {
species_names_.push_back(*i);
}
// species stoichiometries
for (std::vector<double>::const_iterator i = in_stoichiometries.begin();
i != in_stoichiometries.end(); i++) {
stoichiometry_.push_back(*i);
}
// species ids
for (std::vector<int>::const_iterator i = in_species_ids.begin();
i != in_species_ids.end(); i++) {
species_ids_.push_back(*i);
}
lnK_ = log_to_ln(logK());
//
// verify the setup
//
// must have ncomp > 0, or ncomp > 1?
if (ncomp() < 1) {
std::ostringstream error_stream;
error_stream << "SecondarySpecies::SecondarySpecies(): \n"
<< "invalid number of components "
<< "(ncomp < 1), ncomp = " << ncomp() << std::endl;
Exceptions::amanzi_throw(ChemistryInvalidInput(error_stream.str()));
}
// size of species names, stoichiometries and id arrays must be the same
if (species_names_.size() != stoichiometry_.size()) {
std::ostringstream error_stream;
error_stream << "SecondarySpecies::SecondarySpecies(): \n"
<< "invalid input data: \n"
<< "species_names.size() != stoichiometries.size()" << std::endl;
Exceptions::amanzi_throw(ChemistryInvalidInput(error_stream.str()));
}
if (species_names_.size() != species_ids_.size()) {
std::ostringstream error_stream;
error_stream << "SecondarySpecies::SecondarySpecies(): \n"
<< "invalid input data: \n"
<< "species_names.size() != species_ids.size()" << std::endl;
Exceptions::amanzi_throw(ChemistryInvalidInput(error_stream.str()));
}
}
/*
** these functions are only needed if SecondarySpecies equilibrium is added.
*/
void SecondarySpecies::Update(const std::vector<Species>& primary_species) {
static_cast<void>(primary_species);
}
void SecondarySpecies::AddContributionToTotal(std::vector<double> *total) {
static_cast<void>(total);
}
void SecondarySpecies::AddContributionToDTotal(
const std::vector<Species>& primary_species,
MatrixBlock* dtotal) {
static_cast<void>(primary_species);
static_cast<void>(dtotal);
}
/*
** Display functions
*/
void SecondarySpecies::Display(void) const {
std::cout << " " << name() << " = ";
for (unsigned int i = 0; i < species_names_.size(); i++) {
std::cout << stoichiometry_[i] << " " << species_names_[i];
if (i < species_names_.size() - 1) {
std::cout << " + ";
}
}
std::cout << std::endl;
std::cout << std::setw(40) << " "
<< std::setw(10) << logK_
<< std::setw(10) << gram_molecular_weight()
<< std::endl;
}
} // namespace AmanziChemistry
} // namespace Amanzi
| 30.787671 | 82 | 0.611791 | [
"vector"
] |
1284be4d40db9fba2391e9fcca18700b6f8dab83 | 1,693 | hh | C++ | include/tensor_serie.hh | freemeson/multinomial | 9bf1913a0e6d24ac40f219d44f757393decd1ad6 | [
"Apache-2.0"
] | null | null | null | include/tensor_serie.hh | freemeson/multinomial | 9bf1913a0e6d24ac40f219d44f757393decd1ad6 | [
"Apache-2.0"
] | null | null | null | include/tensor_serie.hh | freemeson/multinomial | 9bf1913a0e6d24ac40f219d44f757393decd1ad6 | [
"Apache-2.0"
] | null | null | null | #ifndef TENSOR_SERIE_HH
#define TENSOR_SERIE_HH
#include <vector>
#include <string>
#include "monopoly.h"
template <class T>
class tensor_serie{
friend class tensor_serie<T>;
#ifdef USE_LAPACK
#else
typedef Eigen::LDLT< Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic > > decomposition;
//typedef Eigen::FullPivLU< Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic > > decomposition;
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic > Matrix;
#endif
public:
tensor_serie(unsigned int dimensions,unsigned int max_order);
~tensor_serie();
void normalize();
void pretrain_add(tensor_serie<T> const & series_b);
void decompose(int order);
void solve(decomposition & ext_decomposed_matrix);
void create_diad(std::vector<T> const & x);
void fill(tensor_serie<T> const & x, T const & target, T const & weight);
T eval(tensor_serie<T> const & x) const;
void create_diad_1dim(const T & x);
void fill_1dim(tensor_serie<T> const & x, T const & target, T const & weight);
T eval_1dim(tensor_serie<T> const & x) const;
void print(std::string name = "") const;
void release();
tensor_serie<T> const * principal_axis();
std::vector<symmetric_tensor<T> > m_S;
private:
void vector(unsigned int order);
void matrix(unsigned int order);
void matrix_1dim(unsigned int order);
void set_values();
unsigned int m_max_order;
unsigned int m_dimensions;
//TVectorT<double> m_vector;
std::vector<T> m_vector;
#ifdef USE_LAPACK
fortran_matrix<double > m_matrix;
#else
public:
Matrix m_eigen_matrix;
decomposition m_decomposed_matrix;
#endif
//public:
//EIGEN_MAKE_ALIGNED_OPERATOR_NEW
// std::vector<T> x;
};
#endif //TENSOR_SERIE_HH
| 27.754098 | 96 | 0.727112 | [
"vector"
] |
1287285a98ab64ac675c215f1c37941e20d1e976 | 23,141 | cc | C++ | src_mex/mex_CircleArcMexWrapper.cc | DottorZini/Clothoids | 5dc563ae56044edb3efee1f3ca37501afa184328 | [
"BSD-2-Clause"
] | null | null | null | src_mex/mex_CircleArcMexWrapper.cc | DottorZini/Clothoids | 5dc563ae56044edb3efee1f3ca37501afa184328 | [
"BSD-2-Clause"
] | null | null | null | src_mex/mex_CircleArcMexWrapper.cc | DottorZini/Clothoids | 5dc563ae56044edb3efee1f3ca37501afa184328 | [
"BSD-2-Clause"
] | null | null | null | /****************************************************************************\
Copyright (c) Enrico Bertolazzi 2016
All Rights Reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the file license.txt for more details.
\****************************************************************************/
#include "Circle.hh"
#include "mex_utils.hh"
#include <vector>
#define MEX_ERROR_MESSAGE \
"==========================================================================\n" \
"Compute cicle arc\n" \
"\n" \
"USAGE:\n" \
"\n" \
" OBJ = CircleArcMexWrapper( 'new' ) ;\n" \
" OBJ = CircleArcMexWrapper( 'new', x0, y0, theta0, kur, L ) ;\n" \
"\n" \
" CircleArcMexWrapper( 'delete', OBJ ) ;\n" \
"\n" \
" CircleArcMexWrapper( 'build', OBJ, x0, y0, theta0, kur, L ) ;\n" \
" CircleArcMexWrapper( 'build_G1', OBJ, p0, theta0, p1 ) ;\n" \
" CircleArcMexWrapper( 'build_G1', OBJ, x0, y0, theta0, x1, y1 ) ;\n" \
" CircleArcMexWrapper( 'build_3P', OBJ, p0, p1, p2 ) ;\n" \
" CircleArcMexWrapper( 'build_3P', OBJ, x0, y0, x1, y1, x2, y2 ) ;\n" \
" CircleArcMexWrapper( 'copy', OBJ, OBJ1 ) ;\n" \
"\n" \
" CircleArcMexWrapper( 'changeOrigin', OBJ, x0, y0 ) ;\n" \
" CircleArcMexWrapper( 'translate', OBJ, tx, ty ) ;\n" \
" CircleArcMexWrapper( 'trim', OBJ, smin, smax ) ;\n" \
" CircleArcMexWrapper( 'rotate', OBJ, angle, cx, cy ) ;\n" \
" CircleArcMexWrapper( 'scale', OBJ, scale ) ;\n" \
" CircleArcMexWrapper( 'reverse', OBJ ) ;\n" \
"\n" \
" [d,s] = CircleArcMexWrapper( 'distance', OBJ, x, y ) ;\n" \
" [s,t] = CircleArcMexWrapper( 'findST', OBJ, x, y ) ;\n" \
"\n" \
" [p0,p1,p2,ok] = CircleArcMexWrapper( 'bbTriangle', OBJ ) ;\n" \
"\n" \
" burbs = CircleArcMexWrapper( 'to_nurbs', OBJ ) ;\n" \
"\n" \
" res = CircleArcMexWrapper( 'xBegin', OBJ ) ;\n" \
" res = CircleArcMexWrapper( 'yBegin', OBJ ) ;\n" \
" res = CircleArcMexWrapper( 'thetaBegin', OBJ ) ;\n" \
" res = CircleArcMexWrapper( 'kappa', OBJ ) ;\n" \
" res = CircleArcMexWrapper( 'length', OBJ ) ;\n" \
"\n" \
" [X,Y] = CircleArcMexWrapper( 'eval', OBJ, s [,t] ) ;\n" \
" [X,Y] = CircleArcMexWrapper( 'eval_D', OBJ, s [,t] ) ;\n" \
" [X,Y] = CircleArcMexWrapper( 'eval_DD', OBJ, s [,t] ) ;\n" \
" [X,Y] = CircleArcMexWrapper( 'eval_DDD', OBJ, s [,t] ) ;\n" \
"\n" \
" [X,Y] = CircleArcMexWrapper( 'theta', OBJ, s ) ;\n" \
"\n" \
" nurbs = CircleArcMexWrapper( 'to_nurbs', OBJ ) ;\n" \
"\n" \
"%==========================================================================%\n" \
"% %\n" \
"% Autor: Enrico Bertolazzi %\n" \
"% Department of Industrial Engineering %\n" \
"% University of Trento %\n" \
"% enrico.bertolazzi@unitn.it %\n" \
"% %\n" \
"%==========================================================================%\n"
namespace G2lib {
using namespace std;
static
CircleArc *
DATA_NEW( mxArray * & mx_id ) {
CircleArc * ptr = new CircleArc();
mx_id = convertPtr2Mat<CircleArc>(ptr);
return ptr ;
}
static
inline
CircleArc *
DATA_GET( mxArray const * & mx_id ) {
return convertMat2Ptr<CircleArc>(mx_id);
}
static
void
DATA_DELETE( mxArray const * & mx_id ) {
destroyObject<CircleArc>(mx_id);
}
extern "C"
void
mexFunction( int nlhs, mxArray *plhs[],
int nrhs, mxArray const *prhs[] ) {
// the first argument must be a string
if ( nrhs == 0 ) {
mexErrMsgTxt(MEX_ERROR_MESSAGE) ;
return ;
}
try {
MEX_ASSERT( mxIsChar(arg_in_0), "CircleArcMexWrapper(...): First argument must be a string" ) ;
string cmd = mxArrayToString(arg_in_0) ;
mwSize size0, size1, size2 ;
bool do_new = cmd == "new" ;
CircleArc * ptr = do_new ? DATA_NEW(arg_out_0) : DATA_GET(arg_in_1);
if ( do_new || cmd == "build" ) {
int_type kk = do_new ? 0 : 1 ;
if ( do_new ) {
MEX_ASSERT( nlhs == 1, "CircleArcMexWrapper, expected 1 output, nlhs = " << nlhs );
} else {
MEX_ASSERT( nlhs == 0, "CircleArcMexWrapper, expected no output, nlhs = " << nlhs );
}
if ( nrhs == 6+kk ) {
#define CMD "CircleArcMexWrapper(x0,y0,theta0,k0,L): "
real_type x0 = getScalarValue( prhs[1+kk], CMD "`x0` expected to be a real scalar" );
real_type y0 = getScalarValue( prhs[2+kk], CMD "`y0` expected to be a real scalar" );
real_type theta0 = getScalarValue( prhs[3+kk], CMD "`theta0` expected to be a real scalar" );
real_type k0 = getScalarValue( prhs[4+kk], CMD "`k0` expected to be a real scalar" );
real_type L = getScalarValue( prhs[5+kk], CMD "`L` expected to be a real scalar" );
ptr->build( x0, y0, theta0, k0, L );
#undef CMD
} else if ( nrhs == 1 ) {
// nothing to do
} else {
MEX_ASSERT(false, "CircleArc, expected 1 or " << 6+kk << " inputs, nrhs = " << nrhs );
}
plhs[0] = convertPtr2Mat<CircleArc>(ptr);
} else if ( cmd == "build_G1" ) {
MEX_ASSERT( nlhs == 0 || nlhs ==1, "CircleArcMexWrapper, expected 1 or no output, nlhs = " << nlhs );
real_type x0(0), y0(0), x1(0), y1(0), theta0(0);
if ( nrhs == 5 ) {
#define CMD "CircleArcMexWrapper('build_G1',OBJ,p0,theta0,p1): "
real_type const * p0 = getVectorPointer( arg_in_2, size0, CMD "`p0` expected to be a real vector" );
theta0 = getScalarValue( arg_in_3, CMD "`theta0` expected to be a real vector" );
real_type const * p1 = getVectorPointer( arg_in_4, size1, CMD "`p1` expected to be a real vector" );
MEX_ASSERT( size0 == 2 && size1 == 2,
CMD "bad dimension size(p0) = " << size0 << ", size(p1) = " << size1 ) ;
#undef CMD
x0 = p0[0] ; y0 = p0[1] ;
x1 = p1[0] ; y1 = p1[1] ;
} else if ( nrhs == 7 ) {
#define CMD "CircleArcMexWrapper('build_G1',OBJ,x0,x1,theta0,x1,y1): "
x0 = getScalarValue( arg_in_2,CMD "`x0` expected to be a scalar value" );
y0 = getScalarValue( arg_in_3,CMD "`y0` expected to be a scalar value" );
theta0 = getScalarValue( arg_in_4,CMD "`theta0` expected to be a scalar value" );
x1 = getScalarValue( arg_in_5,CMD "`x1` expected to be a scalar value" );
y1 = getScalarValue( arg_in_6,CMD "`y1` expected to be a scalar value" );
#undef CMD
} else {
MEX_ASSERT(false, "CircleArc, expected 5 or 7 inputs, nrhs = " << nrhs );
}
bool ok = ptr->build_G1( x0, y0, theta0, x1, y1 ) ;
if ( nlhs == 1 ) {
arg_out_0 = mxCreateNumericMatrix(1, 1, mxLOGICAL_CLASS, mxREAL);
*static_cast<mxLogical*>(mxGetData(arg_out_0)) = ok ;
}
#undef CMD
} else if ( cmd == "build_3P" ) {
MEX_ASSERT( nlhs == 0 || nlhs ==1, "CircleArcMexWrapper, expected 1 or no output, nlhs = " << nlhs );
real_type x0(0), y0(0), x1(0), y1(0), x2(0), y2(0);
if ( nrhs == 5 ) {
#define CMD "CircleArcMexWrapper('build_G1',OBJ,p0,p1,p2): "
real_type const * p0 = getVectorPointer( arg_in_2, size0, CMD "`p0` expected to be a real vector" );
real_type const * p1 = getVectorPointer( arg_in_3, size1, CMD "`p1` expected to be a real vector" );
real_type const * p2 = getVectorPointer( arg_in_4, size2, CMD "`p2` expected to be a real vector" );
MEX_ASSERT( size0 == 2 && size1 == 2 && size2 == 2,
CMD "bad dimension size(p0) = " << size0 <<
", size(p1) = " << size1 << ", size(p2) = " << size2 ) ;
#undef CMD
x0 = p0[0] ; y0 = p0[1] ;
x1 = p1[0] ; y1 = p1[1] ;
x2 = p2[0] ; y2 = p2[1] ;
} else if ( nrhs == 8 ) {
#define CMD "CircleArcMexWrapper('build_G1',OBJ,x0,x1,x1,y1,x2,y2): "
x0 = getScalarValue( arg_in_2,CMD "`x0` expected to be a scalar value" );
y0 = getScalarValue( arg_in_3,CMD "`y0` expected to be a scalar value" );
x1 = getScalarValue( arg_in_4,CMD "`x1` expected to be a scalar value" );
y1 = getScalarValue( arg_in_5,CMD "`y1` expected to be a scalar value" );
x2 = getScalarValue( arg_in_6,CMD "`x2` expected to be a scalar value" );
y2 = getScalarValue( arg_in_7,CMD "`y2` expected to be a scalar value" );
#undef CMD
} else {
MEX_ASSERT(false, "CircleArc, expected 5 or 7 inputs, nrhs = " << nrhs );
}
bool ok = ptr->build_3P( x0, y0, x1, y1, x2, y2 ) ;
if ( nlhs == 1 ) setScalarBool(arg_out_0,ok);
} else if ( cmd == "delete" ) {
#define CMD "CircleArcMexWrapper('delete',OBJ): "
MEX_ASSERT(nrhs == 2, CMD "expected 2 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
// Destroy the C++ object
DATA_DELETE( arg_in_1 ) ;
#undef CMD
} else if ( cmd == "copy" ) {
#define CMD "CircleArcMexWrapper('copy',OBJ,OBJ1): "
MEX_ASSERT(nrhs == 3, CMD "expected 3 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
CircleArc const * CC = convertMat2Ptr<CircleArc>(arg_in_2);
ptr->copy(*CC) ;
#undef CMD
} else if ( cmd == "changeOrigin" ) {
#define CMD "CircleArcMexWrapper('changeOrigin',OBJ,x0,y0): "
MEX_ASSERT(nrhs == 4, CMD "expected 4 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
real_type new_x0 = getScalarValue( arg_in_2, CMD "`x0` expected to be a real scalar" );
real_type new_y0 = getScalarValue( arg_in_3, CMD "`y0` expected to be a real scalar" );
ptr->changeOrigin( new_x0, new_y0 );
#undef CMD
} else if ( cmd == "translate" ) {
#define CMD "CircleArcMexWrapper('translate',OBJ,tx,ty): "
MEX_ASSERT(nrhs == 4, CMD "expected 4 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
real_type tx = getScalarValue( arg_in_2, CMD "`tx` expected to be a real scalar" );
real_type ty = getScalarValue( arg_in_3, CMD "`ty` expected to be a real scalar" );
ptr->translate( tx, ty );
#undef CMD
} else if ( cmd == "changeCurvilinearOrigin" ) {
#define CMD "CircleArcMexWrapper('changeCurvilinearOrigin',OBJ,s0,L): "
MEX_ASSERT(nrhs == 4, CMD "expected 4 inputs, nrhs = " << nrhs );
real_type s0 = getScalarValue(arg_in_2,CMD "Error in reading s0") ;
real_type L = getScalarValue(arg_in_3,CMD "Error in reading L") ;
ptr->changeCurvilinearOrigin(s0,L);
#undef CMD
} else if ( cmd == "rotate" ) {
#define CMD "CircleArcMexWrapper('rotate',OBJ,angle,cx,cy): "
MEX_ASSERT(nrhs == 5, CMD "expected 5 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
real_type angle = getScalarValue( arg_in_2, CMD "`angle` expected to be a real scalar" );
real_type cx = getScalarValue( arg_in_3, CMD "`cx` expected to be a real scalar" );
real_type cy = getScalarValue( arg_in_4, CMD "`cy` expected to be a real scalar" );
ptr->rotate( angle, cx, cy );
#undef CMD
} else if ( cmd == "scale" ) {
#define CMD "CircleArcMexWrapper('scale',OBJ,scale): "
MEX_ASSERT(nrhs == 3, CMD "expected 3 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
real_type sc = getScalarValue( arg_in_2, CMD "`scale` expected to be a real scalar" );
ptr->scale( sc );
#undef CMD
} else if ( cmd == "reverse" ) {
#define CMD "CircleArcMexWrapper('reverse',OBJ): "
MEX_ASSERT(nrhs == 2, CMD "expected 2 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
ptr->reverse();
#undef CMD
} else if ( cmd == "trim" ) {
#define CMD "CircleArcMexWrapper('trim',OBJ,s_begin,s_end): "
MEX_ASSERT(nrhs == 4, CMD "expected 4 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 0, CMD "expected no output, nlhs = " << nlhs );
real_type s_begin = getScalarValue( arg_in_2, CMD "`s_begin` expected to be a real scalar" );
real_type s_end = getScalarValue( arg_in_3, CMD "`s_end` expected to be a real scalar" );
ptr->trim( s_begin, s_end );
#undef CMD
} else if ( cmd == "theta" ) {
#define CMD "CircleArcMexWrapper('theta',OBJ,s): "
MEX_ASSERT(nrhs == 3, CMD "expected 3 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 1, CMD "expected 1 output, nlhs = " << nlhs );
real_type s = getScalarValue( arg_in_2, CMD "`s` expected to be a real scalar" );
setScalarValue( arg_out_0, ptr->theta( s ) ) ;
#undef CMD
} else if ( cmd == "distance" ) {
#define CMD "CircleArcMexWrapper('distance',OBJ,x,y): "
MEX_ASSERT( nrhs == 4, CMD "expected 4 input, nrhs = " << nrhs );
if ( nlhs > 0 ) {
MEX_ASSERT(nlhs <= 2, CMD "expected 1 or 2 output, nlhs = " << nlhs );
mwSize nrx, ncx, nry, ncy;
real_type const * x = getMatrixPointer( arg_in_2, nrx, ncx, CMD "`x` expected to be a real vector/matrix" ) ;
real_type const * y = getMatrixPointer( arg_in_3, nry, ncy, CMD "`y` expected to be a real vector/matrix" ) ;
MEX_ASSERT( nrx == nry && ncx == ncy,
CMD "`x` and `y` expected to be of the same size, found size(x) = " <<
nrx << " x " << nry << " size(y) = " << nry << " x " << ncy );
real_type * dst = createMatrixValue( arg_out_0, nrx, ncx ) ;
mwSize size = nrx*ncx ;
if ( nlhs > 1 ) {
real_type * s = createMatrixValue( arg_out_1, nrx, ncx ) ;
for ( mwSize i = 0 ; i < size ; ++i )
*dst++ = ptr->distance( *x++, *y++, *s++ ) ;
} else {
for ( mwSize i = 0 ; i < size ; ++i )
*dst++ = ptr->distance( *x++, *y++ ) ;
}
}
#undef CMD
} else if ( cmd == "bbTriangle" ) {
#define CMD "CircleArcMexWrapper('bbTriangle',OBJ): "
MEX_ASSERT(nrhs == 2, CMD "expected 2 inputs, nrhs = " << nrhs );
MEX_ASSERT(nlhs == 4, CMD "expected 4 output, nlhs = " << nlhs );
double * p0 = createMatrixValue( arg_out_0, 1, 2 );
double * p1 = createMatrixValue( arg_out_1, 1, 2 );
double * p2 = createMatrixValue( arg_out_2, 1, 2 );
bool ok = ptr->bbTriangle( p0, p1, p2 );
setScalarBool(arg_out_3,ok);
#undef CMD
} else if ( cmd == "to_nurbs" ) {
#define CMD "CircleArcMexWrapper('to_nurbs',OBJ): "
int_type npts = ptr->toNURBS( nullptr, nullptr, true );
mxArray * mx_knots, * mx_Poly ;
double * knots = createMatrixValue( mx_knots, 1, npts+3 );
double * poly = createMatrixValue( mx_Poly, 3, npts );
ptr->toNURBS( knots, poly, false );
static char const * fieldnames[] = { "form", "order", "dim", "number", "knots", "coefs" } ;
arg_out_0 = mxCreateStructMatrix(1,1,6,fieldnames);
mxSetFieldByNumber( arg_out_0, 0, 0, mxCreateString("rB") );
mxSetFieldByNumber( arg_out_0, 0, 1, mxCreateDoubleScalar(3) );
mxSetFieldByNumber( arg_out_0, 0, 2, mxCreateDoubleScalar(2) );
mxSetFieldByNumber( arg_out_0, 0, 3, mxCreateDoubleScalar(npts) );
mxSetFieldByNumber( arg_out_0, 0, 4, mx_knots );
mxSetFieldByNumber( arg_out_0, 0, 5, mx_Poly );
#undef CMD
} else if ( cmd == "findST" ) {
#define CMD "CircleArcMexWrapper('findST',OBJ,x,y): "
MEX_ASSERT( nrhs == 4, CMD "expected 4 input, nrhs = " << nrhs );
MEX_ASSERT( nlhs == 2, CMD "expected 2 output, nlhs = " << nlhs );
mwSize nrx, ncx, nry, ncy;
real_type const * x = getMatrixPointer( arg_in_2, nrx, ncx,
CMD "`x` expected to be a real vector/matrix" ) ;
real_type const * y = getMatrixPointer( arg_in_3, nry, ncy,
CMD "`y` expected to be a real vector/matrix" ) ;
MEX_ASSERT( nrx == nry && ncx == ncy,
CMD "`x` and `y` expected to be of the same size, found size(x) = " <<
nrx << " x " << nry << " size(y) = " << nry << " x " << ncy );
real_type * s = createMatrixValue( arg_out_0, nrx, ncx ) ;
real_type * t = createMatrixValue( arg_out_1, nrx, ncx ) ;
mwSize size = nrx*ncx ;
for ( mwSize i = 0 ; i < size ; ++i )
ptr->findST( *x++, *y++, *s++, *t++ ) ;
#undef CMD
} else if ( cmd == "info" ) {
#define CMD "CircleArcMexWrapper('info',OBJ): "
MEX_ASSERT( nrhs == 2, CMD "expected 2 inputs, nrhs = " << nrhs ) ;
MEX_ASSERT( nlhs == 0, CMD "expected NO outputs, nlhs = " << nlhs ) ;
ptr->info(cout) ;
#undef CMD
} else if ( cmd == "eval" || cmd == "eval_D" ||
cmd == "eval_DD" || cmd == "eval_DDD" ) {
if ( nrhs == 4 ) {
#define CMD "CircleArcMexWrapper('eval*',OBJ,s,t): "
mwSize size, sizet ;
real_type const * s = getVectorPointer( arg_in_2, size, CMD "`s` expected to be a real vector" ) ;
real_type const * t = getVectorPointer( arg_in_3, sizet, CMD "`t` expected to be a real vector" ) ;
MEX_ASSERT( size == sizet || size == 1 || sizet ==1,
CMD " size(s) = " << size <<
" must be equal to size(t) = " << sizet <<
" or size(s|t) == 1" );
mwSize incs = size == 1 ? 0 : 1 ;
mwSize inct = sizet == 1 ? 0 : 1 ;
mwSize npts = max(size,sizet) ;
#define LOOPXY1 for ( mwSize i = 0 ; i < npts ; ++i, s += incs, t += inct, pXY += 2 )
#define LOOPXY2 for ( mwSize i = 0 ; i < npts ; ++i, s += incs, t += inct, ++pX, ++pY )
if ( nlhs == 1 ) {
real_type *pXY = createMatrixValue( arg_out_0, 2,size );
if ( cmd == "eval" ) {
LOOPXY1 ptr->eval( *s, *t, pXY[0], pXY[1] ) ;
} else if ( cmd == "eval_D" ) {
LOOPXY1 ptr->eval_D( *s, *t, pXY[0], pXY[1] ) ;
} else if ( cmd == "eval_DD" ) {
LOOPXY1 ptr->eval_DD( *s, *t, pXY[0], pXY[1] ) ;
} else if ( cmd == "eval_DDD" ) {
LOOPXY1 ptr->eval_DDD( *s, *t, pXY[0], pXY[1] ) ;
} else {
MEX_ASSERT(false, "Unknown command: " << cmd );
}
} else if ( nlhs == 2 ) {
real_type *pX = createMatrixValue( arg_out_0, 1,size );
real_type *pY = createMatrixValue( arg_out_1, 1,size );
if ( cmd == "eval" ) {
LOOPXY2 ptr->eval( *s, *t, *pX, *pY ) ;
} else if ( cmd == "eval_D" ) {
LOOPXY2 ptr->eval_D( *s, *t, *pX, *pY ) ;
} else if ( cmd == "eval_DD" ) {
LOOPXY2 ptr->eval_DD( *s, *t, *pX, *pY ) ;
} else if ( cmd == "eval_DDD" ) {
LOOPXY2 ptr->eval_DDD( *s, *t, *pX, *pY ) ;
} else {
MEX_ASSERT(false, "Unknown command: " << cmd );
}
} else {
MEX_ASSERT( nlhs == 0, CMD "expected 1 or 2 outputs, nlhs = " << nlhs ) ;
}
#undef LOOPXY1
#undef LOOPXY2
#undef CMD
} else if ( nrhs == 3 ) {
#define CMD "CircleArcMexWrapper('eval*',OBJ,s): "
mwSize npts ;
real_type const * s = getVectorPointer( arg_in_2, npts, CMD "`s` expected to be a real vector" ) ;
#define LOOPXY1 for ( mwSize i = 0 ; i < npts ; ++i, ++s, pXY += 2 )
#define LOOPXY2 for ( mwSize i = 0 ; i < npts ; ++i, ++s, ++pX, ++pY )
if ( nlhs == 1 ) {
real_type *pXY = createMatrixValue( arg_out_0, 2, npts );
if ( cmd == "eval" ) {
LOOPXY1 ptr->eval( *s, pXY[0], pXY[1] ) ;
} else if ( cmd == "eval_D" ) {
LOOPXY1 ptr->eval_D( *s, pXY[0], pXY[1] ) ;
} else if ( cmd == "eval_DD" ) {
LOOPXY1 ptr->eval_DD( *s, pXY[0], pXY[1] ) ;
} else if ( cmd == "eval_DDD" ) {
LOOPXY1 ptr->eval_DDD( *s, pXY[0], pXY[1] ) ;
} else {
MEX_ASSERT(false, "Unknown command: " << cmd );
}
} else if ( nlhs == 2 ) {
real_type *pX = createMatrixValue( arg_out_0, 1, npts );
real_type *pY = createMatrixValue( arg_out_1, 1, npts );
if ( cmd == "eval" ) {
LOOPXY2 ptr->eval( *s, *pX, *pY ) ;
} else if ( cmd == "eval_D" ) {
LOOPXY2 ptr->eval_D( *s, *pX, *pY ) ;
} else if ( cmd == "eval_DD" ) {
LOOPXY2 ptr->eval_DD( *s, *pX, *pY ) ;
} else if ( cmd == "eval_DDD" ) {
LOOPXY2 ptr->eval_DDD( *s, *pX, *pY ) ;
} else {
MEX_ASSERT(false, "Unknown command: " << cmd );
}
} else {
MEX_ASSERT( nlhs == 0, CMD "expected 1 or 2 outputs, nlhs = " << nlhs ) ;
}
#undef LOOPXY1
#undef LOOPXY2
#undef CMD
} else {
MEX_ASSERT( false, "CircleArcMexWrapper('eval*',OBJ,...) bad number of arguments nrhs = " << nrhs ) ;
}
} else if ( nrhs == 2 ) {
if ( cmd == "xBegin" ) setScalarValue( arg_out_0, ptr->xBegin());
else if ( cmd == "xEnd" ) setScalarValue( arg_out_0, ptr->xEnd());
else if ( cmd == "yBegin" ) setScalarValue( arg_out_0, ptr->yBegin());
else if ( cmd == "yEnd" ) setScalarValue( arg_out_0, ptr->yEnd());
else if ( cmd == "thetaBegin" ) setScalarValue( arg_out_0, ptr->thetaBegin());
else if ( cmd == "thetaEnd" ) setScalarValue( arg_out_0, ptr->thetaEnd());
else if ( cmd == "kappa" ) setScalarValue( arg_out_0, ptr->kappa());
else if ( cmd == "length" ) setScalarValue( arg_out_0, ptr->length());
else {
MEX_ASSERT(false, "CircleArcMexWrapper unknown command: " << cmd );
}
} else {
MEX_ASSERT(false, "CircleArcMexWrapper unknown command: " << cmd );
}
} catch ( exception const & e ) {
mexErrMsgTxt(e.what()) ;
} catch (...) {
mexErrMsgTxt("CircleArcMexWrapper failed\n") ;
}
}
}
| 41.249554 | 119 | 0.516961 | [
"object",
"vector"
] |
128d7b52157ca8a43b31a291e2bcef5f3922b9b0 | 4,321 | cpp | C++ | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Jastrow/JastrowBasisBuilder.cpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 55 | 2015-07-28T01:32:58.000Z | 2022-02-27T16:27:46.000Z | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Jastrow/JastrowBasisBuilder.cpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Jastrow/JastrowBasisBuilder.cpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 26 | 2015-10-26T22:11:51.000Z | 2021-03-02T22:09:15.000Z | //////////////////////////////////////////////////////////////////
// (c) Copyright 2006- by Jeongnim Kim
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// National Center for Supercomputing Applications &
// Materials Computation Center
// University of Illinois, Urbana-Champaign
// Urbana, IL 61801
// e-mail: jnkim@ncsa.uiuc.edu
//
// Supported by
// National Center for Supercomputing Applications, UIUC
// Materials Computation Center, UIUC
//////////////////////////////////////////////////////////////////
// -*- C++ -*-
#include "QMCWaveFunctions/Jastrow/JastrowBasisBuilder.h"
#include "QMCWaveFunctions/MolecularOrbitals/AtomicBasisBuilder.h"
#include "QMCWaveFunctions/MolecularOrbitals/GTOBuilder.h"
#include "QMCWaveFunctions/MolecularOrbitals/BsplineAOBuilder.h"
#include "QMCWaveFunctions/Jastrow/CBSOBuilder.h"
#include "QMCWaveFunctions/SparseLocalizedBasisSet.h"
#include "Message/Communicate.h"
namespace qmcplusplus
{
/** constructor
* \param els reference to the electrons
* \param ions reference to the ions
*/
JastrowBasisBuilder::JastrowBasisBuilder(ParticleSet& els, ParticleSet& ions,
const string& functype, bool usespline):
targetPtcl(els), sourcePtcl(ions), UseSpline(usespline),FuncType(functype), myBasisSet(0)
{
}
JastrowBasisBuilder::~JastrowBasisBuilder()
{
}
template<typename RFBUILDER>
void JastrowBasisBuilder::createLocalizedBasisSet(xmlNodePtr cur)
{
typedef typename RFBUILDER::CenteredOrbitalType COT;
typedef SparseLocalizedBasisSet<COT> ThisBasisSetType;
ThisBasisSetType* curBasis= new ThisBasisSetType(sourcePtcl,targetPtcl);
//create the size vector with zeros
SizeOfBasisPerCenter.resize(sourcePtcl.getSpeciesSet().getTotalNum(),0);
//create the basis set
cur = cur->xmlChildrenNode;
while(cur!=NULL)
{
string cname((const char*)(cur->name));
if(cname == "atomicBasisSet")
{
const xmlChar* eptr=xmlGetProp(cur,(const xmlChar*)"elementType");
if(eptr == NULL)
{
app_error() << " Missing elementType attribute of atomicBasisSet.\n Abort at MOBasisBuilder::put " << endl;
OHMMS::Controller->abort();
}
string elementType((const char*)eptr);
map<string,BasisSetBuilder*>::iterator it = aoBuilders.find(elementType);
if(it == aoBuilders.end())
{
AtomicBasisBuilder<RFBUILDER>* any = new AtomicBasisBuilder<RFBUILDER>(elementType);
any->put(cur);
COT* aoBasis= any->createAOSet(cur);
if(aoBasis)
//add the new atomic basis to the basis set
{
int activeCenter =sourcePtcl.getSpeciesSet().findSpecies(elementType);
curBasis->add(activeCenter, aoBasis);
aoBuilders[elementType]=any;
printRadialFunctors(elementType,aoBasis);
SizeOfBasisPerCenter[activeCenter]=aoBasis->getBasisSetSize();
}
}
}
cur = cur->next;
}
//resize the basis set
curBasis->setBasisSetSize(-1);
//clean up
if(myBasisSet) delete myBasisSet;
myBasisSet=curBasis;
}
bool JastrowBasisBuilder::put(xmlNodePtr cur)
{
if(myBasisSet)
return true;
if(UseSpline)
{
createLocalizedBasisSet<CBSOBuilder>(cur);
}
else
{
if(FuncType == "Bspline")
{
createLocalizedBasisSet<BsplineAOBuilder>(cur);
}
if(FuncType == "gto" || FuncType == "GTO")
createLocalizedBasisSet<GTOBuilder>(cur);
}
return true;
}
template<typename COT>
void JastrowBasisBuilder::printRadialFunctors(const string& elementType, COT* aoBasis)
{
#if !defined(HAVE_MPI)
string fname(elementType);
fname.append(".j3.dat");
ofstream fout(fname.c_str());
int nr=aoBasis->Rnl.size();
fout << "# number of radial functors = " << nr << endl;
double r=0.0;
while(r<20)
{
fout << r ;
for(int i=0; i<nr; i++)
fout << " " << aoBasis->Rnl[i]->evaluate(r,1.0/r);
fout << endl;
r += 0.013;
}
#endif
}
}
/***************************************************************************
* $RCSfile$ $Author: jnkim $
* $Revision: 1623 $ $Date: 2007-01-18 18:01:15 -0600 (Thu, 18 Jan 2007) $
* $Id: JastrowBasisBuilder.h 1623 2007-01-19 00:01:15Z jnkim $
***************************************************************************/
| 32.007407 | 117 | 0.623004 | [
"vector"
] |
129b6ef240b0ab584a13467f226b70d370ac0489 | 8,214 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osganimationtimeline/osganimationtimeline.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osganimationtimeline/osganimationtimeline.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osganimationtimeline/osganimationtimeline.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /* -*-c++-*-
* Copyright (C) 2008 Cedric Pinson <cedric.pinson@plopbyte.net>
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <iostream>
#include <osgDB/ReadFile>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>
#include <osgAnimation/Bone>
#include <osgAnimation/Skeleton>
#include <osgAnimation/RigGeometry>
#include <osgAnimation/Timeline>
#include <osgAnimation/AnimationManagerBase>
#include <osgAnimation/TimelineAnimationManager>
#include <osgAnimation/ActionStripAnimation>
#include <osgAnimation/ActionBlendIn>
#include <osgAnimation/ActionBlendOut>
#include <osgAnimation/ActionAnimation>
struct NoseBegin : public osgAnimation::Action::Callback
{
virtual void operator()(osgAnimation::Action* action, osgAnimation::ActionVisitor* nv)
{
std::cout << "sacrebleu, it scratches my nose, let me scratch it" << std::endl;
std::cout << "process NoseBegin call back " << action->getName() << std::endl << std::endl;
}
};
struct NoseEnd : public osgAnimation::Action::Callback
{
virtual void operator()(osgAnimation::Action* action, osgAnimation::ActionVisitor* nv)
{
std::cout << "shhhrt shrrrrt shhhhhhrrrrt, haaa it's better"<< std::endl;
std::cout << "process NoseEnd call back " << action->getName() << std::endl << std::endl;
}
};
struct ExampleTimelineUsage : public osgGA::GUIEventHandler
{
osg::ref_ptr<osgAnimation::ActionStripAnimation> _mainLoop;
osg::ref_ptr<osgAnimation::ActionStripAnimation> _scratchHead;
osg::ref_ptr<osgAnimation::ActionStripAnimation> _scratchNose;
osg::ref_ptr<osgAnimation::TimelineAnimationManager> _manager;
bool _releaseKey;
ExampleTimelineUsage(osgAnimation::TimelineAnimationManager* manager)
{
_releaseKey = false;
_manager = manager;
const osgAnimation::AnimationList& list = _manager->getAnimationList();
osgAnimation::AnimationMap map;
for (osgAnimation::AnimationList::const_iterator it = list.begin(); it != list.end(); it++)
map[(*it)->getName()] = *it;
_mainLoop = new osgAnimation::ActionStripAnimation(map["Idle_Main"].get(),0.0,0.0);
_mainLoop->setLoop(0); // means forever
_scratchHead = new osgAnimation::ActionStripAnimation(map["Idle_Head_Scratch.02"].get(),0.2,0.3);
_scratchHead->setLoop(1); // one time
map["Idle_Nose_Scratch.01"]->setDuration(10.0); // set this animation duration to 10 seconds
_scratchNose = new osgAnimation::ActionStripAnimation(map["Idle_Nose_Scratch.01"].get(),0.2,0.3);
_scratchNose->setLoop(1); // one time
// add the main loop at priority 0 at time 0.
osgAnimation::Timeline* tml = _manager->getTimeline();
tml->play();
tml->addActionAt(0.0, _mainLoop.get(), 0);
// add a scratch head priority 1 at 3.0 second.
tml->addActionAt(5.0, _scratchHead.get(), 1);
// populate time with scratch head
for (int i = 1; i < 20; i++)
{
// we add a scratch head priority 1 each 10 second
// note:
// it's possible to add the same instance more then once on the timeline
// the only things you need to take care is if you remove it. It will remove
// all instance that exist on the timeline. If you need to differtiate
// it's better to create a new instance
tml->addActionAt(5.0 + 10.0 * i, _scratchHead.get(), 1);
}
// we will add the scratch nose action only when the player hit a key
// in the operator()
// now we will add callback at end and begin of animation of Idle_Nose_Scratch.02
_scratchNose->setCallback(0.0, new NoseBegin);
_scratchNose->setCallback(_scratchNose->getNumFrames()-1, new NoseEnd);
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&)
{
if (ea.getEventType() == osgGA::GUIEventAdapter::KEYUP)
{
_releaseKey = true;
}
return false;
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
if (nv && nv->getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)
{
if (_releaseKey) // we hit a key and release it execute an action
{
osgAnimation::Timeline* tml = _manager->getTimeline();
// dont play if already playing
if (!tml->isActive(_scratchNose.get()))
{
// add this animation on top of two other
// we add one to evaluate the animation at the next frame, else we
// will miss the current frame
tml->addActionAt(tml->getCurrentFrame() + 1, _scratchNose.get(), 2);
}
_releaseKey = false;
}
}
else
{
osgGA::EventVisitor* ev = dynamic_cast<osgGA::EventVisitor*>(nv);
if (ev && ev->getActionAdapter() && !ev->getEvents().empty())
{
for(osgGA::EventQueue::Events::iterator itr = ev->getEvents().begin();
itr != ev->getEvents().end();
++itr)
{
handleWithCheckAgainstIgnoreHandledEventsMask(*(*itr), *(ev->getActionAdapter()), node, nv);
}
}
}
traverse(node, nv);
}
};
int main (int argc, char* argv[])
{
std::cerr << "This example works only with nathan.osg" << std::endl;
osg::ArgumentParser psr(&argc, argv);
osgViewer::Viewer viewer(psr);
std::string file = "nathan.osg";
if(argc >= 2)
file = psr[1];
// replace the manager
osg::Group* root = dynamic_cast<osg::Group*>(osgDB::readNodeFile(file));
if (!root) {
osg::notify(osg::FATAL) << "can't read file " << file << std::endl;
return 1;
}
osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(root->getUpdateCallback());
if(!animationManager)
{
osg::notify(osg::FATAL) << "Did not find AnimationManagerBase updateCallback needed to animate elements" << std::endl;
return 1;
}
osg::ref_ptr<osgAnimation::TimelineAnimationManager> tl = new osgAnimation::TimelineAnimationManager(*animationManager);
root->setUpdateCallback(tl.get());
ExampleTimelineUsage* callback = new ExampleTimelineUsage(tl.get());
root->setEventCallback(callback);
root->getUpdateCallback()->addNestedCallback(callback);
// add the state manipulator
viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
// add the thread model handler
viewer.addEventHandler(new osgViewer::ThreadingHandler);
// add the window size toggle handler
viewer.addEventHandler(new osgViewer::WindowSizeHandler);
// add the stats handler
viewer.addEventHandler(new osgViewer::StatsHandler);
// add the help handler
viewer.addEventHandler(new osgViewer::HelpHandler(psr.getApplicationUsage()));
// add the LOD Scale handler
viewer.addEventHandler(new osgViewer::LODScaleHandler);
// add the screen capture handler
viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);
viewer.setSceneData(root);
return viewer.run();
}
| 36.834081 | 136 | 0.646457 | [
"model"
] |
129fe50ef4e68cddc9e618bf4b82259fbb2ad564 | 9,554 | cpp | C++ | puzzlemoppet/projects/Puzzle/EndLevelScreen.cpp | LibreGames/puzzlemoppet | d79b10e6968f9f1f27e930c4f13194700ff42126 | [
"WTFPL"
] | null | null | null | puzzlemoppet/projects/Puzzle/EndLevelScreen.cpp | LibreGames/puzzlemoppet | d79b10e6968f9f1f27e930c4f13194700ff42126 | [
"WTFPL"
] | null | null | null | puzzlemoppet/projects/Puzzle/EndLevelScreen.cpp | LibreGames/puzzlemoppet | d79b10e6968f9f1f27e930c4f13194700ff42126 | [
"WTFPL"
] | null | null | null |
#include "EndLevelScreen.h"
#include "MainState.h"
#include "Level.h"
#include "GUIPane.h"
const f32 timeBeforeShowing = 2.f;
EndLevelScreen::EndLevelScreen(MainState *mainState, Level *level)
: mainState(mainState), level(level)
{
engine = GetEngine();
renderSystem = engine->GetRenderSystem();
stats = level->GetLevelStats();
scoreResult = input_score(level->GetShortName(), stats);
engine->RegisterEventInterest(this, "ButtonDown");
engine->RegisterEventInterest(this, "EndLevelText");
engine->RegisterEventInterest(this, "ScreenFadeFinished");
engine->RegisterEventInterest(this, "EndLevelScreenShow");
engine->RegisterEventInterest(this, "EndLevelScreenClose");
engine->RegisterEventInterest(this, "EndLevelScreenListItem");
engine->RegisterEventInterest(this, "EndLevelScreenListItemFinalScore");
sound = engine->GetSoundSystem()->CreateSound2D();
sound->SetVolume(0.5);
eventQueue = engine->CreateEventQueue();
GetUpdater().AddUpdatable(eventQueue);
eventQueue->drop();
// Wait a brief period before showing.
Event event("EndLevelScreenShow");
eventQueue->AddTimeWait(timeBeforeShowing);
eventQueue->AddEvent(event);
}
EndLevelScreen::~EndLevelScreen()
{
if (sound)
sound->drop();
engine->UnregisterAllEventInterest(this);
for (auto & elem : guiElements)
elem->remove();
}
void offset_y(gui::IGUIElement *element, s32 y)
{
core::recti rect = element->getRelativePosition();
rect.UpperLeftCorner.Y += y;
rect.LowerRightCorner.Y += y;
element->setRelativePosition(rect);
}
void EndLevelScreen::OnEvent(const Event &event)
{
video::IVideoDriver *driver = engine->GetIrrlichtDevice()->getVideoDriver();
s32 screenWidth = driver->getScreenSize().Width;
s32 screenHeight = driver->getScreenSize().Height;
const f32 betweenItemWait = 1.f;
const f32 itemFadeOnTime = 0.5f;
//f32 bgMinY = 0.3;//0.15;
//bgMinY = (screenHeight - bgHeight) / 2 ;
if (event.IsType("EndLevelScreenShow"))
{
gui::IGUIElement *bg;
{
bg = new GUIPane(engine->GetIrrlichtDevice()->getGUIEnvironment()->getRootGUIElement(),
core::recti(-10,0,screenWidth+10,screenHeight),
video::SColor(200, 0,0,0));
bg->drop();
guiElements.push_back(bg);
}
{
core::stringw text = L"Level Complete!";
/*
std::vector<core::stringc> levels = find_levels();
core::stringc levelShortName = level->GetShortName();
for (u32 i = 0; i < levels.size(); i ++)
{
if (levels[i] == levelShortName)
{
text = L"Level ";
text += i;
text += L" of ";
text += 30;
text += L" Complete!";
break;
}
}
*/
s32 yPos = s32(screenHeight * 0.05);
gui::IGUIElement *element = add_static_text2( text.c_str() );
core::recti rect = element->getRelativePosition();
rect += core::vector2di( screenWidth/2-rect.getWidth()/2, yPos );
element->setRelativePosition(rect);
guiElements.push_back( element );
}
// apply fades to all stuff created so far
// (fade on)
for (auto & elem : guiElements)
{
GUIElementFade *fade = new GUIElementFade(engine->GetIrrlichtDevice()->getGUIEnvironment(),
elem, this, itemFadeOnTime, itemFadeOnTime, false);
fade->drop();
fade->OnPostRender(0);
}
// Now queue the rest of the stuff.
f32 yPos = 0.15;
const f32 yInc = 0.05f;
{
eventQueue->AddTimeWait(betweenItemWait);
Event event("EndLevelScreenListItem");
event["text"] << "Blocks pushed: " << stats.pushes;
event["y_pos"] = yPos;
eventQueue->AddEvent(event);
}
// presumably if there are elevators present, we will use them at least once.
// so this if should fail only if there are no elevators.
if (stats.elevatorMoves > 0)
{
yPos += yInc;
eventQueue->AddTimeWait(betweenItemWait);
Event event("EndLevelScreenListItem");
event["text"] << "Elevator journeys: " << stats.elevatorMoves;
event["y_pos"] = yPos;
eventQueue->AddEvent(event);
}
// ugly hack.
// we don't want to show undo stats on first level.
// (since tutorial doesn't introduce undo until second level)
if (level->GetShortName() != "first.lev")
{
yPos += yInc;
eventQueue->AddTimeWait(betweenItemWait);
Event event("EndLevelScreenListItem");
event["text"] << "Undos used: " << stats.undos;
event["y_pos"] = yPos;
eventQueue->AddEvent(event);
}
yPos += yInc;
{
eventQueue->AddTimeWait(betweenItemWait);
Event event("EndLevelScreenListItem");
event["text"] << "Deaths: " << stats.deaths;
event["y_pos"] = yPos;
eventQueue->AddEvent(event);
}
yPos += 0.1f;
{
eventQueue->AddTimeWait(betweenItemWait);
Event event("EndLevelScreenListItemFinalScore");
event["text"] << "Your rating: ";
event["text2"] << get_result_description(scoreResult);
event["y_pos"] = yPos;
eventQueue->AddEvent(event);
}
f32 bgHeight = yPos + 0.05f;
// set bg correct height
core::recti rect = bg->getRelativePosition();
rect.LowerRightCorner.Y = s32(screenHeight * bgHeight);
bg->setRelativePosition(rect);
// now find downwards Y offset required to centre everything vertically.
s32 yOffset = (screenHeight - s32(screenHeight*bgHeight)) / 2;
f32 yOffsetFloat = (1.f - bgHeight) / 2.f;
// apply to all gui elements created so far
for (auto & elem : guiElements)
offset_y(elem, yOffset);
// and all those waiting in events...
// (hack alert!)
std::vector<Event *> allEvents = eventQueue->GetAllEvents();
for (auto & elem : allEvents)
{
Event &event = (*elem);
if (event.HasKey("y_pos"))
event["y_pos"] = event["y_pos"] + yOffsetFloat;
}
// Stop player teleport effects.
// Not sure whether to do this or not.
//level->ClearEndLevelTeleportEffects();
}
else if (event.IsType("EndLevelScreenListItem"))
{
{
gui::IGUIElement *element = add_static_text( core::stringw(event["text"].To<core::stringc>()).c_str() );
core::recti rect = element->getRelativePosition();
rect += core::vector2di( screenWidth/2 - rect.getWidth()+75,
s32(screenHeight*event["y_pos"].To<f32>())-rect.getHeight()/2 );
element->setRelativePosition(rect);
guiElements.push_back( element );
GUIElementFade *fade = new GUIElementFade(engine->GetIrrlichtDevice()->getGUIEnvironment(),
element, this, itemFadeOnTime, itemFadeOnTime, false);
fade->drop();
fade->OnPostRender(0);
sound->Play(PROJECT_DIR"/Puzzle/media/sfx/appear.ogg");
}
}
else if (event.IsType("EndLevelScreenListItemFinalScore"))
{
{
gui::IGUIElement *element = add_static_text2( core::stringw(event["text"].To<core::stringc>()).c_str() );
core::recti rect = element->getRelativePosition();
rect += core::vector2di( screenWidth/2-rect.getWidth()/2,
s32(screenHeight*event["y_pos"].To<f32>())-rect.getHeight() );
element->setRelativePosition(rect);
guiElements.push_back( element );
GUIElementFade *fade = new GUIElementFade(engine->GetIrrlichtDevice()->getGUIEnvironment(),
element, this, itemFadeOnTime, itemFadeOnTime, false);
fade->drop();
fade->OnPostRender(0);
// rating is separate
gui::IGUIStaticText *textElement = add_static_text2( core::stringw(event["text2"].To<core::stringc>()).c_str() );
core::recti rect2 = textElement->getRelativePosition();
rect2 += core::vector2di( screenWidth/2-rect2.getWidth()/2,
s32(screenHeight*event["y_pos"].To<f32>())-rect2.getHeight() );
textElement->setRelativePosition(rect2);
guiElements.push_back( textElement );
textElement->setOverrideColor( get_rating_col(scoreResult)
// and make a bit brighter since we are on a black background
+ video::SColor(50,0,0,0) );
GUIElementFade *fade2 = new GUIElementFade(engine->GetIrrlichtDevice()->getGUIEnvironment(),
textElement, this, itemFadeOnTime, itemFadeOnTime, false);
fade2->drop();
fade2->OnPostRender(0);
// now reposition both
element->setRelativePosition( rect.UpperLeftCorner
- core::vector2di(rect2.getWidth()/2, 0) );
textElement->setRelativePosition( rect2.UpperLeftCorner
+ core::vector2di(rect.getWidth()/2 , 0) );
switch (scoreResult)
{
case ESR_AWFUL:
sound->Play(PROJECT_DIR"/Puzzle/media/sfx/laugh.ogg");
break;
case ESR_FAIR:
sound->SetVolume(0.15);
sound->Play(PROJECT_DIR"/Puzzle/media/sfx/fair.ogg");
break;
case ESR_GOOD:
sound->SetVolume(0.15);
sound->Play(PROJECT_DIR"/Puzzle/media/sfx/good.ogg");
break;
case ESR_EXCELLENT:
sound->SetVolume(0.15);
sound->Play(PROJECT_DIR"/Puzzle/media/sfx/excellent.ogg");
break;
case ESR_PERFECT:
sound->SetVolume(0.25);
sound->Play(PROJECT_DIR"/Puzzle/media/sfx/perfect.ogg");
break;
case ESR_EXTRAORDINARY:
sound->SetVolume(0.25);
sound->Play(PROJECT_DIR"/Puzzle/media/sfx/extraordinary.ogg");
break;
default:
WARN << "Unknown score result.";
break;
}
}
}
else if (event.IsType("ButtonDown") && eventQueue->IsEmpty())// && event["button"] == KEY_LBUTTON)
{
// Fade off
renderSystem->ScreenFade(0.f, 2, true);
// And close this.
Event event("EndLevelScreenClose");
TimedEvent(event, 2.f);
}
else if (event.IsType("ButtonDown") && !eventQueue->IsEmpty()
&& eventQueue->IsEventWaiting("EndLevelScreenListItemFinalScore"))
{
// Speed up displaying...
eventQueue->ScaleTimes(0.1);
}
else if (event.IsType("EndLevelScreenClose"))
{
// Finished.
// So call next level and remove this screen.
mainState->NextLevel(true);
engine->GetWorld()->GetUpdater().RemoveUpdatable(this);
}
else if (event.IsType("EndLevelText"))
{
}
}
| 28.266272 | 116 | 0.683483 | [
"vector"
] |
12a388a9ccb9a77afc48262f67f3509e2e1182ab | 309 | hpp | C++ | include/wee/core/aabb.hpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2019-02-11T12:18:39.000Z | 2019-02-11T12:18:39.000Z | include/wee/core/aabb.hpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:27:58.000Z | 2021-11-11T07:27:58.000Z | include/wee/core/aabb.hpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:22:12.000Z | 2021-11-11T07:22:12.000Z | #pragma once
#include <core/vec3.hpp>
#include <core/mat4.hpp>
namespace wee {
struct mat4;
struct aabb {
vec3f min = vec3f::zero(), max = vec3f::zero();
static aabb transform(const aabb&, const mat4&);
aabb& add(const vec3f&);
vec3 get_corner(int) const;
};
}
| 18.176471 | 56 | 0.592233 | [
"transform"
] |
12a8a7439055caa63896154de553787efe9c167d | 22,869 | cpp | C++ | dev/Code/Tools/AssetProcessor/native/resourcecompiler/rcjob.cpp | stickyparticles/lumberyard | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 2 | 2019-11-29T09:04:54.000Z | 2021-03-18T02:34:44.000Z | dev/Code/Tools/AssetProcessor/native/resourcecompiler/rcjob.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/Tools/AssetProcessor/native/resourcecompiler/rcjob.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 3 | 2019-05-13T09:41:33.000Z | 2021-04-09T12:12:38.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "rcjob.h"
#include <AzCore/Debug/TraceMessageBus.h>
#include <AzCore/std/smart_ptr/unique_ptr.h>
#include <AzCore/IO/FileIO.h>
#include <AzCore/IO/SystemFile.h> // for max path len
#include <AzCore/std/string/string.h> // for wstring
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzFramework/Logging/LogFile.h>
#include <AssetBuilderSDK/AssetBuilderBusses.h>
#include <AssetBuilderSDK/AssetBuilderSDK.h>
#include "native/utilities/assetUtilEBusHelper.h"
#include <QtConcurrent/QtConcurrentRun>
#include <QDir>
#include <QDateTime>
#include <QElapsedTimer>
#include "native/utilities/PlatformConfiguration.h"
#include "native/utilities/AssetUtils.h"
#include "native/assetprocessor.h"
namespace
{
unsigned long s_jobSerial = 1;
bool s_typesRegistered = false;
// You have up to 60 minutes to finish processing an asset.
// This was increased from 10 to account for PVRTC compression
// taking up to an hour for large normal map textures, and should
// be reduced again once we move to the ASTC compression format, or
// find another solution to reduce processing times to be reasonable.
const unsigned int g_jobMaximumWaitTime = 1000 * 60 * 60;
const unsigned int g_sleepDurationForLockingAndFingerprintChecking = 100;
const unsigned int g_graceTimeBeforeLockingAndFingerprintChecking = 300;
const unsigned int g_timeoutInSecsForRetryingCopy = 30;
bool MoveCopyFile(QString sourceFile, QString productFile, bool isCopyJob = false)
{
if (!isCopyJob && (AssetUtilities::MoveFileWithTimeout(sourceFile, productFile, g_timeoutInSecsForRetryingCopy)))
{
//We do not want to rename the file if it is a copy job
return true;
}
else if (AssetUtilities::CopyFileWithTimeout(sourceFile, productFile, g_timeoutInSecsForRetryingCopy))
{
// try to copy instead
return true;
}
AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Failed to move OR copy file from Source directory: %s to Destination Directory: %s", sourceFile.toUtf8().data(), productFile.toUtf8().data());
return false;
}
}
using namespace AssetProcessor;
bool Params::IsValidParams() const
{
return (!m_finalOutputDir.isEmpty());
}
bool RCParams::IsValidParams() const
{
return (
(!m_rcExe.isEmpty()) &&
(!m_rootDir.isEmpty()) &&
(!m_inputFile.isEmpty()) &&
Params::IsValidParams()
);
}
namespace AssetProcessor
{
RCJob::RCJob(QObject* parent)
: QObject(parent)
, m_timeCreated(QDateTime::currentDateTime())
, m_scanFolderID(0)
{
m_jobState = RCJob::pending;
if (!s_typesRegistered)
{
qRegisterMetaType<RCParams>("RCParams");
qRegisterMetaType<BuilderParams>("BuilderParams");
qRegisterMetaType<JobOutputInfo>("JobOutputInfo");
s_typesRegistered = true;
}
}
RCJob::~RCJob()
{
}
void RCJob::Init(JobDetails& details)
{
m_jobDetails = AZStd::move(details);
m_queueElementID = QueueElementID(GetInputFileRelativePath(), GetPlatform(), GetJobKey());
}
const JobEntry& RCJob::GetJobEntry() const
{
return m_jobDetails.m_jobEntry;
}
QDateTime RCJob::GetTimeCreated() const
{
return m_timeCreated;
}
void RCJob::SetTimeCreated(const QDateTime& timeCreated)
{
m_timeCreated = timeCreated;
}
QDateTime RCJob::GetTimeLaunched() const
{
return m_timeLaunched;
}
void RCJob::SetTimeLaunched(const QDateTime& timeLaunched)
{
m_timeLaunched = timeLaunched;
}
QDateTime RCJob::GetTimeCompleted() const
{
return m_timeCompleted;
}
void RCJob::SetTimeCompleted(const QDateTime& timeCompleted)
{
m_timeCompleted = timeCompleted;
}
AZ::u32 RCJob::GetOriginalFingerprint() const
{
return m_jobDetails.m_jobEntry.m_computedFingerprint;
}
void RCJob::SetOriginalFingerprint(unsigned int fingerprint)
{
m_jobDetails.m_jobEntry.m_computedFingerprint = fingerprint;
}
RCJob::JobState RCJob::GetState() const
{
return m_jobState;
}
void RCJob::SetState(const JobState& state)
{
m_jobState = state;
}
void RCJob::SetJobEscalation(int jobEscalation)
{
m_JobEscalation = jobEscalation;
}
void RCJob::SetInputFileAbsolutePath(QString absolutePath)
{
m_jobDetails.m_jobEntry.m_absolutePathToFile = absolutePath.toUtf8().data();
}
void RCJob::SetCheckExclusiveLock(bool value)
{
m_jobDetails.m_jobEntry.m_checkExclusiveLock = value;
}
QString RCJob::GetStateDescription(const RCJob::JobState& state)
{
switch (state)
{
case RCJob::pending:
return tr("Pending");
case RCJob::processing:
return tr("Processing");
case RCJob::completed:
return tr("Completed");
case RCJob::crashed:
return tr("Crashed");
case RCJob::terminated:
return tr("Terminated");
case RCJob::failed:
return tr("Failed");
case RCJob::cancelled:
return tr("Cancelled");
}
return QString();
}
QString RCJob::GetInputFileAbsolutePath() const
{
return m_jobDetails.m_jobEntry.m_absolutePathToFile;
}
QString RCJob::GetInputFileRelativePath() const
{
return m_jobDetails.m_jobEntry.m_relativePathToFile;
}
QString RCJob::GetFinalOutputPath() const
{
return m_jobDetails.m_destinationPath;
}
QString RCJob::GetPlatform() const
{
return m_jobDetails.m_jobEntry.m_platform;
}
AssetBuilderSDK::ProcessJobResponse& RCJob::GetProcessJobResponse()
{
return m_processJobResponse;
}
void RCJob::PopulateProcessJobRequest(AssetBuilderSDK::ProcessJobRequest& processJobRequest)
{
processJobRequest.m_jobDescription.m_critical = IsCritical();
processJobRequest.m_jobDescription.m_additionalFingerprintInfo = m_jobDetails.m_extraInformationForFingerprinting.toUtf8().data();
processJobRequest.m_jobDescription.m_jobKey = GetJobKey().toUtf8().data();
processJobRequest.m_jobDescription.m_jobParameters = AZStd::move(m_jobDetails.m_jobParam);
processJobRequest.m_jobDescription.m_platform = AssetUtilities::ComputePlatformFlag(GetPlatform());
processJobRequest.m_jobDescription.m_priority = GetPriority();
for (AssetProcessor::SourceFileDependencyInternal& entry : m_jobDetails.m_sourceFileDependencyList)
{
processJobRequest.m_sourceFileDependencyList.push_back(entry.m_sourceFileDependency);
}
processJobRequest.m_builderGuid = GetBuilderGuid();
processJobRequest.m_sourceFile = GetInputFileRelativePath().toUtf8().data();
processJobRequest.m_watchFolder = GetWatchFolder().toUtf8().data();
processJobRequest.m_fullPath = GetInputFileAbsolutePath().toUtf8().data();
processJobRequest.m_jobId = GetJobEntry().m_jobRunKey;
}
QString RCJob::GetJobKey() const
{
return m_jobDetails.m_jobEntry.m_jobKey;
}
QString RCJob::GetWatchFolder() const
{
return m_jobDetails.m_watchFolder;
}
AZ::Uuid RCJob::GetBuilderGuid() const
{
return m_jobDetails.m_jobEntry.m_builderGuid;
}
bool RCJob::IsCritical() const
{
return m_jobDetails.m_critical;
}
int RCJob::GetPriority() const
{
return m_jobDetails.m_priority;
}
void RCJob::Start()
{
// the following trace can be uncommented if there is a need to deeply inspect job running.
//AZ_TracePrintf(AssetProcessor::DebugChannel, "JobTrace Start(%i %s,%s,%s)\n", this, GetInputFileAbsolutePath().toUtf8().data(), GetPlatform().toUtf8().data(), GetJobKey().toUtf8().data());
AssetUtilities::QuitListener listener;
listener.BusConnect();
RCParams rc(this);
BuilderParams builderParams(this);
//Create the process job request
AssetBuilderSDK::ProcessJobRequest processJobRequest;
PopulateProcessJobRequest(processJobRequest);
builderParams.m_processJobRequest = processJobRequest;
builderParams.m_finalOutputDir = GetFinalOutputPath();
builderParams.m_assetBuilderDesc = m_jobDetails.m_assetBuilderDesc;
// when the job finishes, record the results and emit Finished()
connect(this, &RCJob::JobFinished, this, [this](AssetBuilderSDK::ProcessJobResponse result)
{
m_processJobResponse = AZStd::move(result);
switch (m_processJobResponse.m_resultCode)
{
case AssetBuilderSDK::ProcessJobResult_Crashed:
{
SetState(crashed);
}
break;
case AssetBuilderSDK::ProcessJobResult_Success:
{
SetState(completed);
}
break;
case AssetBuilderSDK::ProcessJobResult_Cancelled:
{
SetState(cancelled);
}
break;
default:
{
SetState(failed);
}
break;
}
Q_EMIT Finished();
});
if (!listener.WasQuitRequested())
{
QtConcurrent::run(&RCJob::ExecuteBuilderCommand, builderParams);
}
else
{
AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Job cancelled due to quit being requested.");
SetState(terminated);
Q_EMIT Finished();
}
}
void RCJob::ExecuteBuilderCommand(BuilderParams builderParams)
{
// Setting job id for logging purposes
AssetProcessor::SetThreadLocalJobId(builderParams.m_rcJob->GetJobEntry().m_jobRunKey);
// listen for the user quitting (CTRL-C or otherwise)
AssetUtilities::QuitListener listener;
listener.BusConnect();
QElapsedTimer ticker;
ticker.start();
AssetBuilderSDK::ProcessJobResponse result;
// We are adding a grace time before we check exclusive lock and validate the fingerprint of the file.
// This grace time should prevent multiple jobs from getting added to the queue if the source file is still updating.
qint64 milliSecsDiff = QDateTime::currentMSecsSinceEpoch() - builderParams.m_rcJob->GetJobEntry().m_computedFingerprintTimeStamp;
if (milliSecsDiff < g_graceTimeBeforeLockingAndFingerprintChecking)
{
QThread::msleep(g_graceTimeBeforeLockingAndFingerprintChecking - milliSecsDiff);
}
// Lock and unlock the source file to ensure it is not still open by another process.
// This prevents premature processing of some source files that are opened for writing, but are zero bytes for longer than the modification threshhold
QString inputFile(builderParams.m_rcJob->GetJobEntry().m_absolutePathToFile);
if (builderParams.m_rcJob->GetJobEntry().m_checkExclusiveLock && QFile::exists(inputFile))
{
// We will only continue once we get exclusive lock on the source file
while (!AssetUtilities::CheckCanLock(inputFile))
{
QThread::msleep(g_sleepDurationForLockingAndFingerprintChecking);
if (listener.WasQuitRequested() || (ticker.elapsed() > g_jobMaximumWaitTime))
{
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled;
Q_EMIT builderParams.m_rcJob->JobFinished(result);
return;
}
}
}
unsigned int fingerprint = AssetUtilities::GenerateFingerprint(builderParams.m_rcJob->m_jobDetails);
while (fingerprint != builderParams.m_rcJob->GetOriginalFingerprint())
{
// We will only continue once the fingerprint of the file stops changing
builderParams.m_rcJob->SetOriginalFingerprint(fingerprint);
QThread::msleep(g_sleepDurationForLockingAndFingerprintChecking);
if (listener.WasQuitRequested() || (ticker.elapsed() > g_jobMaximumWaitTime))
{
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled;
Q_EMIT builderParams.m_rcJob->JobFinished(result);
return;
}
}
Q_EMIT builderParams.m_rcJob->BeginWork();
// We will actually start working on the job after this point and even if RcController gets the same job again, we will put it in the queue for processing
builderParams.m_rcJob->DoWork(result, builderParams, listener);
Q_EMIT builderParams.m_rcJob->JobFinished(result);
}
void RCJob::DoWork(AssetBuilderSDK::ProcessJobResponse& result, BuilderParams& builderParams, AssetUtilities::QuitListener& listener)
{
{
AssetBuilderSDK::JobCancelListener JobCancelListener(builderParams.m_rcJob->m_jobDetails.m_jobEntry.m_jobRunKey);
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; // failed by default
// create a temporary directory for Builder to work in.
// lets make it as a subdir of a known temp dir
QString workFolder;
if (!AssetUtilities::CreateTempWorkspace(workFolder))
{
AZ_Error(AssetBuilderSDK::ErrorWindow, false, "Could not create temporary directory for Builder!\n");
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
Q_EMIT builderParams.m_rcJob->JobFinished(result);
return;
}
builderParams.m_processJobRequest.m_tempDirPath = AZStd::string(workFolder.toUtf8().data());
AssetUtilities::JobLogTraceListener jobLogTraceListener(builderParams.m_rcJob->m_jobDetails.m_jobEntry);
QString sourceFullPath(builderParams.m_processJobRequest.m_fullPath.c_str());
if (builderParams.m_rcJob->m_jobDetails.m_autoFail)
{
auto failReason = builderParams.m_processJobRequest.m_jobDescription.m_jobParameters.find(AZ_CRC(AssetProcessor::AutoFailReasonKey));
if (failReason != builderParams.m_processJobRequest.m_jobDescription.m_jobParameters.end())
{
// you are allowed to have many lines in your fail reason.
AZ_Error(AssetBuilderSDK::ErrorWindow, false, "Error processing %s", sourceFullPath.toUtf8().data());
AZStd::vector<AZStd::string> delimited;
AzFramework::StringFunc::Tokenize(failReason->second.c_str(), delimited, "\n");
for (const AZStd::string& token : delimited)
{
AZ_Error(AssetBuilderSDK::ErrorWindow, false, "%s", token.c_str());
}
}
else
{
AZ_Error(AssetBuilderSDK::ErrorWindow, false, "%s failed: auto-failed by builder.\n", sourceFullPath.toUtf8().data());
}
if (builderParams.m_processJobRequest.m_jobDescription.m_jobParameters.find(AZ_CRC(AssetProcessor::AutoFailOmitFromDatabaseKey)) != builderParams.m_processJobRequest.m_jobDescription.m_jobParameters.end())
{
// we don't add Auto-fail jobs to the database if they have asked to be emitted.
builderParams.m_rcJob->m_jobDetails.m_jobEntry.m_addToDatabase = false;
}
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
}
else if (builderParams.m_rcJob->m_jobDetails.m_autoSucceed)
{
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
builderParams.m_rcJob->m_jobDetails.m_jobEntry.m_addToDatabase = false;
}
else if (sourceFullPath.length() >= AP_MAX_PATH_LEN)
{
AZ_Warning(AssetBuilderSDK::WarningWindow, false, "Source Asset: %s filepath length %d exceeds the maximum path length (%d) allowed.\n", sourceFullPath.toUtf8().data(), sourceFullPath.length(), AP_MAX_PATH_LEN);
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
}
else
{
if (!JobCancelListener.IsCancelled())
{
// sending process job command to the builder
builderParams.m_assetBuilderDesc.m_processJobFunction(builderParams.m_processJobRequest, result);
}
}
if (JobCancelListener.IsCancelled())
{
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled;
}
}
bool shouldRemoveTempFolder = true;
switch (result.m_resultCode)
{
case AssetBuilderSDK::ProcessJobResult_Success:
if (!CopyCompiledAssets(builderParams, result))
{
result.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
shouldRemoveTempFolder = false;
}
break;
case AssetBuilderSDK::ProcessJobResult_Crashed:
AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Builder indicated that its process crashed!");
break;
case AssetBuilderSDK::ProcessJobResult_Cancelled:
AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Builder indicates that the job was cancelled.");
break;
case AssetBuilderSDK::ProcessJobResult_Failed:
AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Builder indicated that the job has failed.");
shouldRemoveTempFolder = false;
break;
}
if ((shouldRemoveTempFolder) || (listener.WasQuitRequested()))
{
QDir workingDir(QString(builderParams.m_processJobRequest.m_tempDirPath.c_str()));
workingDir.removeRecursively();
}
// Setting the job id back to zero for error detection
AssetProcessor::SetThreadLocalJobId(0);
listener.BusDisconnect();
}
bool RCJob::CopyCompiledAssets(BuilderParams& params, AssetBuilderSDK::ProcessJobResponse& response)
{
QDir outputDirectory(params.m_finalOutputDir);
QString tempFolder = params.m_processJobRequest.m_tempDirPath.c_str();
QDir tempDir(tempFolder);
//if outputDirectory does not exist then create it
if (!outputDirectory.exists())
{
if (!outputDirectory.mkpath("."))
{
AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Failed to create output directory: %s\n", outputDirectory.absolutePath().toUtf8().data());
return false;
}
}
for (AssetBuilderSDK::JobProduct& product : response.m_outputProducts)
{
// each Output Product communicated by the builder will either be
// * a relative path, which means we assume its relative to the temp folder, and we attempt to move the file
// * an absolute path in the temp folder, and we attempt to move also
// * an absolute path outside the temp folder, in which we assume you'd like to just copy a file somewhere.
QString outputProduct = QString(product.m_productFileName.c_str()); // could be a relative path.
QFileInfo fileInfo(outputProduct);
if (fileInfo.isRelative())
{
// we assume that its relative to the TEMP folder.
fileInfo = QFileInfo(tempDir.absoluteFilePath(outputProduct));
}
QString absolutePathOfSource = fileInfo.absoluteFilePath();
QString outputFilename = fileInfo.fileName();
QString productFile = outputDirectory.filePath(outputFilename.toLower());
// Don't make productFile all lowercase for case-insenstive as this
// breaks macOS. The case is already setup properly when the job
// was created.
if (productFile.length() >= AP_MAX_PATH_LEN)
{
AZ_TracePrintf(AssetBuilderSDK::WarningWindow, "Warning: Product %s path length (%d) exceeds the max path length (%d) allowed.\n", productFile.toUtf8().data(), productFile.length(), AP_MAX_PATH_LEN);
return false;
}
bool isCopyJob = !(absolutePathOfSource.startsWith(tempFolder, Qt::CaseInsensitive));
EBUS_EVENT(AssetProcessor::ProcessingJobInfoBus, BeginIgnoringCacheFileDelete, productFile.toUtf8().data());
if (!MoveCopyFile(absolutePathOfSource, productFile, isCopyJob)) // this has its own traceprintf for failure
{
EBUS_EVENT(AssetProcessor::ProcessingJobInfoBus, StopIgnoringCacheFileDelete, productFile.toUtf8().data(), true);
return false;
}
EBUS_EVENT(AssetProcessor::ProcessingJobInfoBus, StopIgnoringCacheFileDelete, productFile.toUtf8().data(), false);
//we now ensure that the file is writable
if ((QFile::exists(productFile)) && (!AssetUtilities::MakeFileWritable(productFile)))
{
AZ_TracePrintf(AssetBuilderSDK::WarningWindow, "Unable to change permission for the file: %s.\n", productFile.toUtf8().data());
}
// replace the product file name in the result with the lower cased
// output path to the file. Needed since this is stored in the DB and
// the AssetProcessor expects product names to be all lower cased.
product.m_productFileName = productFile.toLower().toUtf8().data();
}
return true;
}
} // namespace AssetProcessor
//////////////////////////////////////////////////////////////////////////
#include <native/resourcecompiler/rcjob.moc>
| 39.092308 | 227 | 0.641961 | [
"vector"
] |
12b317f208b5e03137b90a0a3c93efa930ebdcd3 | 13,569 | cpp | C++ | lab_control_center/src/TimeSeriesAggregator.cpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 9 | 2020-06-24T11:22:15.000Z | 2022-01-13T14:14:13.000Z | lab_control_center/src/TimeSeriesAggregator.cpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 1 | 2021-05-10T13:48:04.000Z | 2021-05-10T13:48:04.000Z | lab_control_center/src/TimeSeriesAggregator.cpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 2 | 2021-11-08T11:59:29.000Z | 2022-03-15T13:50:54.000Z | #include "TimeSeriesAggregator.hpp"
#include "cpm/get_topic.hpp"
#include "cpm/ParticipantSingleton.hpp"
/**
* \file TimeSeriesAggregator.cpp
* \ingroup lcc
*/
TimeSeriesAggregator::TimeSeriesAggregator(uint8_t max_vehicle_id)
{
vehicle_state_reader = make_shared<cpm::AsyncReader<VehicleState>>(
[this](std::vector<VehicleState>& samples){
handle_new_vehicleState_samples(samples);
},
"vehicleState"
);
vehicle_observation_reader = make_shared<cpm::AsyncReader<VehicleObservation>>(
[this](std::vector<VehicleObservation>& samples){
handle_new_vehicleObservation_samples(samples);
},
"vehicleObservation"
);
//Set vehicle IDs to listen to in the aggregator
for (uint8_t i = 1; i < max_vehicle_id; ++i)
{
vehicle_ids.push_back(i);
}
vehicle_commandTrajectory_reader = make_shared<cpm::MultiVehicleReader<VehicleCommandTrajectory>>(
cpm::get_topic<VehicleCommandTrajectory>("vehicleCommandTrajectory"),
vehicle_ids
);
vehicle_commandPathTracking_reader = make_shared<cpm::MultiVehicleReader<VehicleCommandPathTracking>>(
cpm::get_topic<VehicleCommandPathTracking>("vehicleCommandPathTracking"),
vehicle_ids
);
}
void TimeSeriesAggregator::create_vehicle_timeseries(uint8_t vehicle_id)
{
timeseries_vehicles[vehicle_id] = map<string, shared_ptr<TimeSeries>>();
timeseries_vehicles[vehicle_id]["reference_deviation"] = make_shared<TimeSeries>(
"Reference Deviation", "%6.2f", "m");
timeseries_vehicles[vehicle_id]["pose_x"] = make_shared<TimeSeries>(
"Position X", "%6.2f", "m");
timeseries_vehicles[vehicle_id]["pose_y"] = make_shared<TimeSeries>(
"Position Y", "%6.2f", "m");
timeseries_vehicles[vehicle_id]["pose_yaw"] = make_shared<TimeSeries>(
"Yaw", "%6.3f", "rad");
timeseries_vehicles[vehicle_id]["ips_dt"] = make_shared<TimeSeries>(
"IPS age", "%3.0f", "ms");
timeseries_vehicles[vehicle_id]["speed"] = make_shared<TimeSeries>(
"Speed", "%5.2f", "m/s");
timeseries_vehicles[vehicle_id]["battery_level"] = make_shared<TimeSeries>(
"Battery Level", "%3.0f", "%");
timeseries_vehicles[vehicle_id]["clock_delta"] = make_shared<TimeSeries>(
"Clock Delta", "%5.1f", "ms");
timeseries_vehicles[vehicle_id]["ips_x"] = make_shared<TimeSeries>(
"IPS Position X", "%6.2f", "m");
timeseries_vehicles[vehicle_id]["ips_y"] = make_shared<TimeSeries>(
"IPS Position Y", "%6.2f", "m");
timeseries_vehicles[vehicle_id]["ips_yaw"] = make_shared<TimeSeries>(
"IPS Yaw", "%6.3f", "rad");
timeseries_vehicles[vehicle_id]["odometer_distance"] = make_shared<TimeSeries>(
"Odometer Distance", "%7.2f", "m");
timeseries_vehicles[vehicle_id]["imu_acceleration_forward"] = make_shared<TimeSeries>(
"Acceleration Forward", "%4.1f", "m/s^2");
timeseries_vehicles[vehicle_id]["imu_acceleration_left"] = make_shared<TimeSeries>(
"Acceleration Left", "%4.1f", "m/s^2");
timeseries_vehicles[vehicle_id]["battery_voltage"] = make_shared<TimeSeries>(
"Battery Voltage", "%5.2f", "V");
timeseries_vehicles[vehicle_id]["motor_current"] = make_shared<TimeSeries>(
"Motor Current", "%5.2f", "A");
timeseries_vehicles[vehicle_id]["is_real"] = make_shared<TimeSeries>(
"Is Real", "%d", "-");
//To detect deviations from the required message frequency
timeseries_vehicles[vehicle_id]["last_msg_state"] = make_shared<TimeSeries>(
"VehicleState age", "%ull", "ms");
timeseries_vehicles[vehicle_id]["last_msg_observation"] = make_shared<TimeSeries>(
"VehicleObservation age", "%ull", "ms");
}
/**
* \brief return battery level based on voltage. Approximates remaining runtime
see tools/battery_level/main.m
* \param v battery voltage
* \ingroup lcc
*/
static inline double voltage_to_percent(const double& v)
{
double u1 = 8.17;
double l1 = 100;
double u2 = 7.38;
double l2 = 50;
double u3 = 7.3;
double l3 = 12;
double u4 = 6.3;
double l4 = 0;
double battery_level;
if (v >= u2) {
battery_level = std::min(100.0, l2 + (l1-l2)/(u1-u2) * (v-u2));
} else if (v > u3) {
battery_level = l3 + (l2-l3)/(u2-u3) * (v-u3);
} else {
battery_level = std::max(0.0, l4 + (l3-l4)/(u3-u4) * (v-u4));
}
return battery_level;
}
void TimeSeriesAggregator::handle_new_vehicleState_samples(std::vector<VehicleState>& samples)
{
std::lock_guard<std::mutex> lock(_mutex);
const uint64_t now = cpm::get_time_ns();
for(auto& state : samples)
{
if(timeseries_vehicles.count(state.vehicle_id()) == 0)
{
create_vehicle_timeseries(state.vehicle_id());
}
timeseries_vehicles[state.vehicle_id()]["pose_x"] ->push_sample(now, state.pose().x());
timeseries_vehicles[state.vehicle_id()]["pose_y"] ->push_sample(now, state.pose().y());
timeseries_vehicles[state.vehicle_id()]["pose_yaw"] ->push_sample(now, state.pose().yaw());
timeseries_vehicles[state.vehicle_id()]["speed"] ->push_sample(now, state.speed());
timeseries_vehicles[state.vehicle_id()]["battery_level"] ->push_sample(now, voltage_to_percent(state.battery_voltage()));
timeseries_vehicles[state.vehicle_id()]["clock_delta"] ->push_sample(now, double(int64_t(now)- int64_t(state.header().create_stamp().nanoseconds()))/1e6 );
timeseries_vehicles[state.vehicle_id()]["odometer_distance"] ->push_sample(now, state.odometer_distance());
timeseries_vehicles[state.vehicle_id()]["imu_acceleration_forward"] ->push_sample(now, state.imu_acceleration_forward());
timeseries_vehicles[state.vehicle_id()]["imu_acceleration_left"] ->push_sample(now, state.imu_acceleration_left());
timeseries_vehicles[state.vehicle_id()]["battery_voltage"] ->push_sample(now, state.battery_voltage());
timeseries_vehicles[state.vehicle_id()]["motor_current"] ->push_sample(now, state.motor_current());
timeseries_vehicles[state.vehicle_id()]["is_real"] ->push_sample(now, state.is_real());
// initialize reference deviation, since no reference is available at start
timeseries_vehicles[state.vehicle_id()]["reference_deviation"] ->push_sample(now, 0.0);
timeseries_vehicles[state.vehicle_id()]["ips_dt"] ->push_sample(now, static_cast<double>(1e-6*state.IPS_update_age_nanoseconds()));
//To detect deviations from the required message frequency
timeseries_vehicles[state.vehicle_id()]["last_msg_state"] ->push_sample(now, static_cast<double>(1e-6*now)); //Just remember the latest msg time and calculate diff in the UI
//Check for deviation from expected update frequency once, reset if deviation was detected
auto it = last_vehicle_state_time_dev.find(state.vehicle_id());
if (it != last_vehicle_state_time_dev.end())
{
check_for_deviation(now, it, expected_period_nanoseconds + allowed_deviation);
}
//Set (first time) or update the value for this ID
last_vehicle_state_time[state.vehicle_id()] = now;
last_vehicle_state_time_dev[state.vehicle_id()] = now;
}
}
void TimeSeriesAggregator::check_for_deviation(uint64_t t_now, std::unordered_map<uint8_t, uint64_t>::iterator entry, uint64_t allowed_diff)
{
if (entry->second > 0)
{
if (t_now - entry->second > allowed_diff)
{
cpm::Logging::Instance().write(2, "Vehicle %i deviated from expected vehicle state frequency on LCC side or is offline", static_cast<int>(entry->first));
entry->second = 0;
}
else if (t_now < entry->second)
{
//This should never occur, due to the way timestamps are stored, unless the clock values are obtained in a way that negative clock changes of the system change the timestamps
cpm::Logging::Instance().write(1, "Critical error in TimeSeriesAggregator check, this should never happen; (vehicle id %i)", static_cast<int>(entry->second));
}
}
}
void TimeSeriesAggregator::handle_new_vehicleObservation_samples(
std::vector<VehicleObservation>& samples
)
{
std::lock_guard<std::mutex> lock(_mutex);
const uint64_t now = cpm::get_time_ns();
for(auto& state : samples)
{
if(timeseries_vehicles.count(state.vehicle_id()) == 0)
{
create_vehicle_timeseries(state.vehicle_id());
}
timeseries_vehicles[state.vehicle_id()]["ips_x"] ->push_sample(now, state.pose().x());
timeseries_vehicles[state.vehicle_id()]["ips_y"] ->push_sample(now, state.pose().y());
timeseries_vehicles[state.vehicle_id()]["ips_yaw"]->push_sample(now, state.pose().yaw());
// timeseries to check if any IPS data are available, push any data
//timeseries_vehicles[state.vehicle_id()]["ips"] ->push_sample(now, true);
//To detect deviations from the required message frequency
timeseries_vehicles[state.vehicle_id()]["last_msg_observation"] ->push_sample(now, static_cast<double>(1e-6*now)); //Just remember the latest msg time and calculate diff in the UI
//Check for long intervals without new information - TODO: WHICH VALUE MAKES SENSE HERE?
auto it = last_vehicle_observation_time.find(state.vehicle_id());
if (it != last_vehicle_observation_time.end())
{
//Currently: Only warn if no new observation sample has been received for over a second - TODO
check_for_deviation(now, it, expected_period_nanoseconds + allowed_deviation);
}
//Set (first time) or update the value for this ID
last_vehicle_observation_time[state.vehicle_id()] = now;
}
}
VehicleData TimeSeriesAggregator::get_vehicle_data() {
std::lock_guard<std::mutex> lock(_mutex);
const uint64_t now = cpm::get_time_ns();
//--------------------------------------------------------------------------- CHECKS ------------------------------------
//This function is called regularly in the UI, so we make sure that everything is checked regularly just by putting the tests in here as well
// - Check for deviations in vehicle state msgs
for (auto it = last_vehicle_state_time.begin(); it != last_vehicle_state_time.end(); /*No ++ because this depends on whether a deletion took place*/)
{
//We use another structure for check_for_deviation here, because that function manipulates the entries given the iterator (may set to zero)
auto it_dev = last_vehicle_state_time_dev.find(it->first);
if (it_dev != last_vehicle_state_time_dev.end())
{
check_for_deviation(now, it_dev, expected_period_nanoseconds + allowed_deviation);
}
//Remove entry (also from timeseries) if outdated
if (now - it->second > max_allowed_age)
{
last_vehicle_observation_time.erase(it->first);
timeseries_vehicles.erase(it->first);
it = last_vehicle_state_time.erase(it);
}
else
{
++it;
}
}
//--------------------------------------------------------------------------- ------- ------------------------------------
return timeseries_vehicles;
}
VehicleTrajectories TimeSeriesAggregator::get_vehicle_trajectory_commands() {
VehicleTrajectories trajectory_sample;
std::map<uint8_t, uint64_t> trajectory_sample_age;
vehicle_commandTrajectory_reader->get_samples(cpm::get_time_ns(), trajectory_sample, trajectory_sample_age);
//Only return data that is not fully outdated
for(auto it = trajectory_sample.begin(); it != trajectory_sample.end(); /*No ++ because this depends on whether a deletion took place*/)
{
if(trajectory_sample_age.at(it->first) > max_allowed_age)
{
it = trajectory_sample.erase(it);
}
else
{
++it;
}
}
return trajectory_sample;
}
VehiclePathTracking TimeSeriesAggregator::get_vehicle_path_tracking_commands() {
VehiclePathTracking path_tracking_sample;
std::map<uint8_t, uint64_t> path_tracking_sample_age;
vehicle_commandPathTracking_reader->get_samples(cpm::get_time_ns(), path_tracking_sample, path_tracking_sample_age);
//Only return data that is not fully outdated
for(auto it = path_tracking_sample.begin(); it != path_tracking_sample.end(); /*No ++ because this depends on whether a deletion took place*/)
{
if(path_tracking_sample_age.at(it->first) > max_allowed_age)
{
it = path_tracking_sample.erase(it);
}
else
{
++it;
}
}
return path_tracking_sample;
}
void TimeSeriesAggregator::reset_all_data()
{
std::lock_guard<std::mutex> lock(_mutex);
timeseries_vehicles.clear();
vehicle_commandTrajectory_reader = make_shared<cpm::MultiVehicleReader<VehicleCommandTrajectory>>(
cpm::get_topic<VehicleCommandTrajectory>("vehicleCommandTrajectory"),
vehicle_ids
);
vehicle_commandPathTracking_reader = make_shared<cpm::MultiVehicleReader<VehicleCommandPathTracking>>(
cpm::get_topic<VehicleCommandPathTracking>("vehicleCommandPathTracking"),
vehicle_ids
);
} | 43.351438 | 191 | 0.658707 | [
"vector"
] |
12b8752bcc2c95c595e8fab9088ccaf2ded64854 | 10,176 | cpp | C++ | Main.cpp | JasonDeras/P3Lab7_JasonDeras7 | a22e7547d715ba2e8982b151663e120316907820 | [
"MIT"
] | null | null | null | Main.cpp | JasonDeras/P3Lab7_JasonDeras7 | a22e7547d715ba2e8982b151663e120316907820 | [
"MIT"
] | null | null | null | Main.cpp | JasonDeras/P3Lab7_JasonDeras7 | a22e7547d715ba2e8982b151663e120316907820 | [
"MIT"
] | null | null | null | #include"Vector.cpp"
#include"Racional.h"
#include"Complejo.h"
#include <iostream>
#include <vector>
using namespace std;
//Vector de Racionales
vector<Vector<Racional>> lista_Racional;
//Vector de complejo
vector <Vector<Complejo>> lista_Complejo;
//Variables de control
Racional r1,r2,r3;
Complejo c1,c2,c3;
int menu(){
int opcion;
cout<<"Menu"<<endl;
cout<<"1. Crear Vector"<<endl;
cout<<"2. Listar Vectores"<<endl;
cout<<"3. Operar vectores"<<endl;
cout<<"Ingrese una opcion: ";
cin>>opcion;
cout<<endl<<endl;
return opcion;
}//fin del metodo menu
int agregar(){
int opcion;
cout<<"Menu creacion"<<endl;
cout<<"1. Agregar Racional"<<endl;
cout<<"2. Agregar Complejo"<<endl;
cout<<"Ingrese una opcion: ";
cin>>opcion;
cout<<endl<<endl;
return opcion;
}//fin del metodo para agregar
int denominador(int deno){
while(deno==0){
cout<<"El denominador no puede ser cero"<<endl<<endl;
cout<<"Ingrese el denominador: ";
cin>> deno;
}
return deno;
}
void listar_Racional(){
cout<<"\n\nLista de Racionales"<<endl;
if (!lista_Racional.empty()){
for (int i = 0; i < lista_Racional.size(); i++){
cout<<"Posicion "<<i<<": "<<lista_Racional[i].To_string()<<endl;
}
}else{
cout<<"El vector esta vacio"<<endl;
}
}//Fin del metodo para listar racionales
void Listar_Complejo(){
cout<<"\n\nLista de Complejos"<<endl;
if (!lista_Complejo.empty()){
for (int i = 0; i < lista_Complejo.size(); i++){
cout<<"Posicion "<<i<<": "<<lista_Complejo[i].To_string()<<endl;
}
}else{
cout<<"El vector esta vacio"<<endl;
}
}//Fin del metodo para listar complejos
int main(){
int usuario=1;
while(usuario==1){
switch(menu()){
case 1:{
int opcion;
cout<<"1. Racionales"<<endl;
cout<<"2. Complejos"<<endl;
cout<<"Ingrese una opcion: ";
cin>>opcion;
switch(opcion){
case 1:{
int numerador1;
int denominador1;
int numerador2;
int denominador2;
int numerador3;
int denominador3;
cout<<"Ingrese el primer numerador: ";
cin>>numerador1;
cout<<"Ingrese el primer denominador: ";
cin>>denominador1;
denominador(denominador1);
r1=Racional(numerador1,denominador1);
cout<<"Ingrese el segundo numerador: ";
cin>>numerador2;
cout<<"Ingrese el segundo denominador: ";
cin>>denominador2;
denominador(denominador2);
r2=Racional(numerador2,denominador2);
cout<<"Ingrese el tercer numerador: ";
cin>>numerador3;
cout<<"Ingrese el tercer denominador: ";
cin>>denominador3;
denominador(denominador3);
r3=Racional(numerador3,denominador3);
Vector<Racional>v(r1,r2,r3);
lista_Racional.push_back(v);
break;}//fin de la opcion de racionales
case 2:{
int a1;
int b1;
int a2;
int b2;
int a3;
int b3;
cout<<"Ingrese el primer real: ";
cin>>a1;
cout<<"Ingrese el primer imaginario: ";
cin>>b1;
c1=Complejo(a1,b1);
cout<<"Ingrese el segundo real: ";
cin>>a2;
cout<<"Ingrese el segundo imaginario: ";
cin>>b2;
c2=Complejo(a2,b2);
cout<<"Ingrese el tercer real: ";
cin>>a3;
cout<<"Ingrese el tercer imaginario: ";
cin>>b3;
c3=Complejo(a3,b3);
Vector<Complejo>c(c1,c2,c3);
lista_Complejo.push_back(c);
break;}//fin de la opcion de complejos
default:{
cout<<"Opcion no valida"<<endl<<endl;
break;}
}//fin de las opciones de creacion
break;}//Fin del caso 1 del menu principal
case 2:{
int opcion;
cout<<"1. Listar Racionales"<<endl;
cout<<"2. Listar Complejos"<<endl;
cout<<"Ingrese una opcion: ";
cin>>opcion;
switch(opcion){
case 1:{
listar_Racional();
break;}
case 2:{
Listar_Complejo();
break;}
default:{
cout<<"Opcion no valida"<<endl<<endl;
break;}
}//fin del menu de listado
break;}//Fin de la opciones de listar
case 3:{
int opcion;
cout<<"1. Suma"<<endl;
cout<<"2. Multiplicacion"<<endl;
cout<<"Ingrese una opcion: ";
cin>>opcion;
switch(opcion){
case 1:{
int opcion;
cout<<"1. Suma Rcionales"<<endl;
cout<<"2. Suma Complejos"<<endl;
cout<<"Ingrese una opcion: ";
cin>>opcion;
switch(opcion){
case 1:{
listar_Racional();
int num, num2;
cout << "Ingrese el numero del primer vector a sumar: ";
cin >> num;
while(num <0 &&num>lista_Racional.size()){
cout<<"El valor esta fuera del vector"<<endl;
cout << "Ingrese el numero del primer vector a sumar: ";
cin >> num;
}
cout << "Ingrese el numero del segundo vector a sumar: ";
cin >> num2;
while(num2 <0 &&num2>lista_Racional.size()){
cout<<"El valore sta fuera del vector"<<endl;
cout << "Ingrese el numero del primer vector as sumar: ";
cin >> num2;
}
cout<<lista_Racional[num].To_string()<<" + "<<lista_Racional[num2].To_string()<<"= ";
Vector<Racional> suma = lista_Racional[num] + lista_Racional[num2];
cout << "[" << suma.getX().To_string() << ", ";
cout << suma.getY().To_string() << ", ";
cout << suma.getZ().To_string() << "]" << endl<<endl;
break;}
case 2:{
Listar_Complejo();
int num, num2;
cout << "Ingrese el numero del primer vector a sumar: ";
cin >> num;
while(num <0 &&num>lista_Complejo.size()){
cout<<"El valor esta fuera del vector"<<endl;
cout << "Ingrese el numero del primer vector a sumar: ";
cin >> num;
}
cout << "Ingrese el numero del segundo vector a sumar: ";
cin >> num2;
while(num2 <0 &&num2>lista_Complejo.size()){
cout<<"El valor esta fuera del vector"<<endl;
cout << "Ingrese el numero del segundo vector a sumas: ";
cin >> num2;
}
cout<<lista_Complejo[num].To_string()<<"+"<<lista_Complejo[num2].To_string()<<"=";
Vector<Complejo> suma = lista_Complejo[num] + lista_Complejo[num2];
cout<< "[" << suma.getX().To_string() << ", ";
cout<< suma.getY().To_string() << ", ";
cout<< suma.getZ().To_string() << "]" << endl<<endl;
break;}
default:{
cout<<"Opcion no valida"<<endl<<endl;
break;}
}//fin de las opciones para suma
break;}
case 2:{
int opcion;
cout<<"1. Multiplicacion Racionales"<<endl;
cout<<"2. Multiplicacion Complejos"<<endl;
cout<<"Ingrese una opcion: ";
cin>>opcion;
switch(opcion){
case 1:{
listar_Racional();
int num, num2;
cout << "Ingrese el numero del primer vector a multiplicar: ";
cin >> num;
while(num <0 &&num>lista_Racional.size()){
cout<<"El valor esta fuera del vector"<<endl;
cout << "Ingrese el numero del primer vector a multiplicar: ";
cin >> num;
}
cout << "Ingrese el numero del segundo vector a multiplicar: ";
cin >> num2;
while(num2 <0 &&num2>lista_Racional.size()){
cout<<"El valor esta fuera del vector"<<endl;
cout << "Ingrese el numero del segundo vector a multiplicar: ";
cin >> num2;
}
cout<<lista_Racional[num].To_string()<<" * "<<lista_Racional[num2].To_string()<<"= ";
Vector<Racional> suma = lista_Racional[num] * lista_Racional[num2];
cout << "[" << suma.getX().To_string() << ", ";
cout << suma.getY().To_string() << ", ";
cout << suma.getZ().To_string() << "]" << endl<<endl;
break;}
case 2:{
Listar_Complejo();
int num, num2;
cout << "Ingrese el numero del primer vector a multiplicar: ";
cin >> num;
while(num <0 &&num>lista_Complejo.size()){
cout<<"El valor esta fuera del vector"<<endl;
cout << "Ingrese el numero del primer vector a multiplicar: ";
cin >> num;
}
cout << "Ingrese el numero del segundo vector a multiplicar: ";
cin >> num2;
while(num2 <0 &&num2>lista_Complejo.size()){
cout<<"El valor esta fuera del vector"<<endl;
cout << "Ingrese el numero del segundo vector a multiplicar: ";
cin >> num2;
}
cout<<lista_Complejo[num].To_string()<<" * "<<lista_Complejo[num2].To_string()<<"=";
Vector<Complejo> suma = lista_Complejo[num] * lista_Complejo[num2];
cout<< "[" << suma.getX().To_string() << ", ";
cout<< suma.getY().To_string() << ", ";
cout<< suma.getZ().To_string() << "]" << endl<<endl;
break;}
default:{
cout<<"Opcion no valida"<<endl<<endl;
break;}
}//fin de las opciones para suma
break;}
default:{
cout<<"Opcion no valida"<<endl<<endl;
break;}
}//Fin de las opciones de operaciones
break;}//Fin del caso 3 del menu principal
default:{
cout<<"Opcion no valida"<<endl<<endl;
break;}
}//Fin de las opciones del menu
cout<<"Volver al menu [1.-Si/2.-No]: ";
cin>>usuario;
cout<<endl<<endl;
}//fin del while del usuario;
return 0;
}//Fin del main | 26.362694 | 102 | 0.523585 | [
"vector"
] |
5210ba8ca7b46ec93b4b1d770eea749e02b1035d | 2,556 | cpp | C++ | Bomberman_SDL/Game/CommandFactory.cpp | hovhannest/Bomberman_SDL | 8c8680144987471beba47b79afca3980c01a11da | [
"MIT"
] | null | null | null | Bomberman_SDL/Game/CommandFactory.cpp | hovhannest/Bomberman_SDL | 8c8680144987471beba47b79afca3980c01a11da | [
"MIT"
] | null | null | null | Bomberman_SDL/Game/CommandFactory.cpp | hovhannest/Bomberman_SDL | 8c8680144987471beba47b79afca3980c01a11da | [
"MIT"
] | null | null | null |
#include "CommandFactory.h"
#include "../Core/Utils/Exception.h"
#include "../Core/Utils/StringUtils.h"
#include "../Core/LoopQuiter.h"
#include "Constants.h"
#include "Commands/QuitCommand.h"
#include "Commands/GameOverCommand.h"
#include "Commands/PlayerCommand.h"
#include "../Core/Utils/Pointer.h"
using namespace std;
using namespace Bomberman::Constants;
namespace Bomberman {
template <typename T>
bool _lock(weak_ptr<T> in, shared_ptr<T>& out, string component) {
bool result = lockWeakPointer(in, out);
if (!result) {
Log::get() << "No " << component << " for CommandFactory" << LogLevel::error;
}
return result;
}
CommandFactory::~CommandFactory() {
}
void CommandFactory::setPlayer(weak_ptr<Player> player) {
this->player = player;
}
void CommandFactory::setTileMap(weak_ptr<TileMap> tileMap) {
this->tileMap = tileMap;
}
void CommandFactory::setConsole(weak_ptr<Console> console) {
this->console = console;
}
void CommandFactory::setLoopQuiter(weak_ptr<LoopQuiter> loopQuiter) {
this->loopQuiter = loopQuiter;
}
shared_ptr<Command> CommandFactory::call(string function, vector<string> arguments) {
shared_ptr<Command> result;
function = StringUtils::toLower(function);
for (int n = 0; n < int(arguments.size()); ++n) {
arguments[n] = StringUtils::toLower(arguments[n]);
}
if (FUNC_EXIT == function) {
shared_ptr<LoopQuiter> loopQuiter;
if (_lock(this->loopQuiter, loopQuiter, "LoopQuiter")) {
result.reset(new QuitCommand(loopQuiter));
}
}
else if (FUNC_GAME_OVER == function) {
shared_ptr<Console> console;
shared_ptr<TileMap> tileMap;
if (_lock(this->console, console, "Console") &&
_lock(this->tileMap, tileMap, "TileMap")) {
result.reset(new GameOverCommand(console, tileMap));
}
}
else {
throw InvalidFunctionException();
}
return result;
}
shared_ptr<Command> CommandFactory::sendMessage(string receiver, string message, vector<string> arguments) {
shared_ptr<Command> result;
receiver = StringUtils::toLower(receiver);
message = StringUtils::toLower(message);
for (int n = 0; n < int(arguments.size()); ++n) {
arguments[n] = StringUtils::toLower(arguments[n]);
}
if (receiver == OBJ_PLAYER) {
shared_ptr<Player> player;
shared_ptr<TileMap> tileMap;
if (_lock(this->player, player, "Player") &&
_lock(this->tileMap, tileMap, "TileMap")) {
result.reset(new PlayerCommand(player, tileMap, message, arguments));
}
}
else {
throw InvalidReceiverException();
}
return result;
}
}
| 25.306931 | 109 | 0.695227 | [
"vector"
] |
521208181a48f7a160aae8ff5bbac591a1fa92f1 | 709 | cpp | C++ | AlgorithmsandDataStructures/3rdLab/B(LongestIncreasingSubsequence).cpp | ShuffleZZZ/ITMO | 29db54d96afef0558550471c58f695c962e1f747 | [
"MIT"
] | 11 | 2020-04-23T15:48:18.000Z | 2022-02-11T10:16:40.000Z | AlgorithmsandDataStructures/3rdLab/B(LongestIncreasingSubsequence).cpp | ShuffleZZZ/ITMO | 29db54d96afef0558550471c58f695c962e1f747 | [
"MIT"
] | 13 | 2020-02-28T01:16:06.000Z | 2020-07-20T19:05:34.000Z | AlgorithmsandDataStructures/3rdLab/B(LongestIncreasingSubsequence).cpp | ShuffleZZZ/ITMO | 29db54d96afef0558550471c58f695c962e1f747 | [
"MIT"
] | 10 | 2018-12-02T15:03:03.000Z | 2022-01-10T18:31:00.000Z | #include <iostream>
#include <vector>
using namespace std;
int main () {
int n,cur=0;
vector <int> res;
cin>>n;
int d[n],prev[n],a[n];
for (int i=0;i<n;i++) {
cin>>a[i];
}
for (int i=0;i<n;i++) {
d[i]=1;
prev[i]=-1;
for (int j=0;j<i;j++) {
if ((a[j]<a[i]) and (d[j]+1>d[i])) {
d[i]=d[j]+1;
prev[i]=j;
}
}
}
for (int i=0;i<n;i++) {
if (d[i]>d[cur]) {
cur=i;
}
}
cout<<d[cur]<<"\n";
while (cur!=-1) {
res.push_back(a[cur]);
cur=prev[cur];
}
for (int i=res.size()-1;i>=0;i--) {
cout<<res[i]<<' ';
}
}
| 18.657895 | 48 | 0.356841 | [
"vector"
] |
5212fe9a6eba2b034883da93c9ea5d845a63c773 | 6,772 | cc | C++ | lite/api/android/jni/native/tensor_jni.cc | jameswu2014/Paddle-Lite | 827e349ac8eb769a873fe9b3aa961af8b8b20a96 | [
"Apache-2.0"
] | 1 | 2020-03-09T03:51:31.000Z | 2020-03-09T03:51:31.000Z | lite/api/android/jni/native/tensor_jni.cc | jameswu2014/Paddle-Lite | 827e349ac8eb769a873fe9b3aa961af8b8b20a96 | [
"Apache-2.0"
] | null | null | null | lite/api/android/jni/native/tensor_jni.cc | jameswu2014/Paddle-Lite | 827e349ac8eb769a873fe9b3aa961af8b8b20a96 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "lite/api/android/jni/native/tensor_jni.h"
#include <memory>
#include <vector>
#include "lite/api/android/jni/native/convert_util_jni.h"
#ifdef __cplusplus
extern "C" {
#endif
namespace paddle {
namespace lite_api {
inline static int64_t product(const std::vector<int64_t> &vec) {
if (vec.empty()) {
return 0;
}
int64_t result = 1;
for (int64_t d : vec) {
result *= d;
}
return result;
}
inline static bool is_const_tensor(JNIEnv *env, jobject jtensor) {
jclass jclazz = env->GetObjectClass(jtensor);
jfieldID jfield = env->GetFieldID(jclazz, "readOnly", "Z");
jboolean read_only = env->GetBooleanField(jtensor, jfield);
return static_cast<bool>(read_only);
}
inline static std::unique_ptr<Tensor> *get_writable_tensor_pointer(
JNIEnv *env, jobject jtensor) {
jclass jclazz = env->GetObjectClass(jtensor);
jfieldID jfield = env->GetFieldID(jclazz, "cppTensorPointer", "J");
jlong java_pointer = env->GetLongField(jtensor, jfield);
std::unique_ptr<Tensor> *ptr =
reinterpret_cast<std::unique_ptr<Tensor> *>(java_pointer);
return ptr;
}
inline static std::unique_ptr<const Tensor> *get_read_only_tensor_pointer(
JNIEnv *env, jobject jtensor) {
jclass jclazz = env->GetObjectClass(jtensor);
jfieldID jfield = env->GetFieldID(jclazz, "cppTensorPointer", "J");
jlong java_pointer = env->GetLongField(jtensor, jfield);
std::unique_ptr<const Tensor> *ptr =
reinterpret_cast<std::unique_ptr<const Tensor> *>(java_pointer);
return ptr;
}
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_lite_Tensor_nativeResize(
JNIEnv *env, jobject jtensor, jlongArray dims) {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
if (tensor == nullptr || (*tensor == nullptr)) {
return JNI_FALSE;
}
std::vector<int64_t> shape = jlongarray_to_int64_vector(env, dims);
(*tensor)->Resize(shape);
return JNI_TRUE;
}
JNIEXPORT jlongArray JNICALL
Java_com_baidu_paddle_lite_Tensor_shape(JNIEnv *env, jobject jtensor) {
if (is_const_tensor(env, jtensor)) {
std::unique_ptr<const Tensor> *tensor =
get_read_only_tensor_pointer(env, jtensor);
std::vector<int64_t> shape = (*tensor)->shape();
return int64_vector_to_jlongarray(env, shape);
} else {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
std::vector<int64_t> shape = (*tensor)->shape();
return int64_vector_to_jlongarray(env, shape);
}
}
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_lite_Tensor_nativeSetData___3F(
JNIEnv *env, jobject jtensor, jfloatArray buf) {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
if (tensor == nullptr || (*tensor == nullptr)) {
return JNI_FALSE;
}
int64_t buf_size = (int64_t)env->GetArrayLength(buf);
if (buf_size != product((*tensor)->shape())) {
return JNI_FALSE;
}
float *input = (*tensor)->mutable_data<float>();
env->GetFloatArrayRegion(buf, 0, buf_size, input);
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_lite_Tensor_nativeSetData___3B(
JNIEnv *env, jobject jtensor, jbyteArray buf) {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
if (tensor == nullptr || (*tensor == nullptr)) {
return JNI_FALSE;
}
int64_t buf_size = (int64_t)env->GetArrayLength(buf);
if (buf_size != product((*tensor)->shape())) {
return JNI_FALSE;
}
int8_t *input = (*tensor)->mutable_data<int8_t>();
env->GetByteArrayRegion(buf, 0, buf_size, input);
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_lite_Tensor_nativeSetData___3I(
JNIEnv *env, jobject jtensor, jintArray buf) {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
if (tensor == nullptr || (*tensor == nullptr)) {
return JNI_FALSE;
}
int64_t buf_size = (int64_t)env->GetArrayLength(buf);
if (buf_size != product((*tensor)->shape())) {
return JNI_FALSE;
}
int32_t *input = (*tensor)->mutable_data<int32_t>();
env->GetIntArrayRegion(buf, 0, buf_size, input);
return JNI_TRUE;
}
JNIEXPORT jfloatArray JNICALL
Java_com_baidu_paddle_lite_Tensor_getFloatData(JNIEnv *env, jobject jtensor) {
if (is_const_tensor(env, jtensor)) {
std::unique_ptr<const Tensor> *tensor =
get_read_only_tensor_pointer(env, jtensor);
return cpp_array_to_jfloatarray(
env, (*tensor)->data<float>(), product((*tensor)->shape()));
} else {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
return cpp_array_to_jfloatarray(
env, (*tensor)->data<float>(), product((*tensor)->shape()));
}
}
JNIEXPORT jbyteArray JNICALL
Java_com_baidu_paddle_lite_Tensor_getByteData(JNIEnv *env, jobject jtensor) {
if (is_const_tensor(env, jtensor)) {
std::unique_ptr<const Tensor> *tensor =
get_read_only_tensor_pointer(env, jtensor);
return cpp_array_to_jbytearray(
env, (*tensor)->data<int8_t>(), product((*tensor)->shape()));
} else {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
return cpp_array_to_jbytearray(
env, (*tensor)->data<int8_t>(), product((*tensor)->shape()));
}
}
JNIEXPORT jintArray JNICALL
Java_com_baidu_paddle_lite_Tensor_getIntData(JNIEnv *env, jobject jtensor) {
if (is_const_tensor(env, jtensor)) {
std::unique_ptr<const Tensor> *tensor =
get_read_only_tensor_pointer(env, jtensor);
return cpp_array_to_jintarray(
env, (*tensor)->data<int32_t>(), product((*tensor)->shape()));
} else {
std::unique_ptr<Tensor> *tensor = get_writable_tensor_pointer(env, jtensor);
return cpp_array_to_jintarray(
env, (*tensor)->data<int32_t>(), product((*tensor)->shape()));
}
}
JNIEXPORT jboolean JNICALL Java_com_baidu_paddle_lite_Tensor_deleteCppTensor(
JNIEnv *env, jobject jtensor, jlong java_pointer) {
if (java_pointer == 0) {
return JNI_FALSE;
}
std::unique_ptr<Tensor> *ptr =
reinterpret_cast<std::unique_ptr<Tensor> *>(java_pointer);
ptr->reset();
delete ptr;
return JNI_TRUE;
}
} // namespace lite_api
} // namespace paddle
#ifdef __cplusplus
}
#endif
| 34.030151 | 80 | 0.719728 | [
"shape",
"vector"
] |
5219466be7cce045276b83ff1f81a635c65cb9b9 | 11,759 | cc | C++ | connectivity/apmanager/device.cc | Keneral/asystem | df12381b72ef3d629c8efc61100cc8c714195320 | [
"Unlicense"
] | null | null | null | connectivity/apmanager/device.cc | Keneral/asystem | df12381b72ef3d629c8efc61100cc8c714195320 | [
"Unlicense"
] | null | null | null | connectivity/apmanager/device.cc | Keneral/asystem | df12381b72ef3d629c8efc61100cc8c714195320 | [
"Unlicense"
] | null | null | null | //
// Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "apmanager/device.h"
#include <base/strings/stringprintf.h>
#include <brillo/strings/string_utils.h>
#include <shill/net/attribute_list.h>
#include <shill/net/ieee80211.h>
#include "apmanager/config.h"
#include "apmanager/control_interface.h"
#include "apmanager/manager.h"
using shill::ByteString;
using std::string;
namespace apmanager {
Device::Device(Manager* manager,
const string& device_name,
int identifier)
: manager_(manager),
supports_ap_mode_(false),
identifier_(identifier),
adaptor_(manager->control_interface()->CreateDeviceAdaptor(this)) {
SetDeviceName(device_name);
SetInUse(false);
}
Device::~Device() {}
void Device::RegisterInterface(const WiFiInterface& new_interface) {
LOG(INFO) << "RegisteringInterface " << new_interface.iface_name
<< " on device " << GetDeviceName();
for (const auto& interface : interface_list_) {
// Done if interface already in the list.
if (interface.iface_index == new_interface.iface_index) {
LOG(INFO) << "Interface " << new_interface.iface_name
<< " already registered.";
return;
}
}
interface_list_.push_back(new_interface);
UpdatePreferredAPInterface();
}
void Device::DeregisterInterface(const WiFiInterface& interface) {
LOG(INFO) << "DeregisteringInterface " << interface.iface_name
<< " on device " << GetDeviceName();
for (auto it = interface_list_.begin(); it != interface_list_.end(); ++it) {
if (it->iface_index == interface.iface_index) {
interface_list_.erase(it);
UpdatePreferredAPInterface();
return;
}
}
}
void Device::ParseWiphyCapability(const shill::Nl80211Message& msg) {
// Parse NL80211_ATTR_SUPPORTED_IFTYPES for AP mode interface support.
shill::AttributeListConstRefPtr supported_iftypes;
if (!msg.const_attributes()->ConstGetNestedAttributeList(
NL80211_ATTR_SUPPORTED_IFTYPES, &supported_iftypes)) {
LOG(ERROR) << "NL80211_CMD_NEW_WIPHY had no NL80211_ATTR_SUPPORTED_IFTYPES";
return;
}
supported_iftypes->GetFlagAttributeValue(NL80211_IFTYPE_AP,
&supports_ap_mode_);
// Parse WiFi band capabilities.
shill::AttributeListConstRefPtr wiphy_bands;
if (!msg.const_attributes()->ConstGetNestedAttributeList(
NL80211_ATTR_WIPHY_BANDS, &wiphy_bands)) {
LOG(ERROR) << "NL80211_CMD_NEW_WIPHY had no NL80211_ATTR_WIPHY_BANDS";
return;
}
shill::AttributeIdIterator band_iter(*wiphy_bands);
for (; !band_iter.AtEnd(); band_iter.Advance()) {
BandCapability band_cap;
shill::AttributeListConstRefPtr wiphy_band;
if (!wiphy_bands->ConstGetNestedAttributeList(band_iter.GetId(),
&wiphy_band)) {
LOG(WARNING) << "WiFi band " << band_iter.GetId() << " not found";
continue;
}
// ...Each band has a FREQS attribute...
shill::AttributeListConstRefPtr frequencies;
if (!wiphy_band->ConstGetNestedAttributeList(NL80211_BAND_ATTR_FREQS,
&frequencies)) {
LOG(ERROR) << "BAND " << band_iter.GetId()
<< " had no 'frequencies' attribute";
continue;
}
// ...And each FREQS attribute contains an array of information about the
// frequency...
shill::AttributeIdIterator freq_iter(*frequencies);
for (; !freq_iter.AtEnd(); freq_iter.Advance()) {
shill::AttributeListConstRefPtr frequency;
if (frequencies->ConstGetNestedAttributeList(freq_iter.GetId(),
&frequency)) {
// ...Including the frequency, itself (the part we want).
uint32_t frequency_value = 0;
if (frequency->GetU32AttributeValue(NL80211_FREQUENCY_ATTR_FREQ,
&frequency_value)) {
band_cap.frequencies.push_back(frequency_value);
}
}
}
wiphy_band->GetU16AttributeValue(NL80211_BAND_ATTR_HT_CAPA,
&band_cap.ht_capability_mask);
wiphy_band->GetU16AttributeValue(NL80211_BAND_ATTR_VHT_CAPA,
&band_cap.vht_capability_mask);
band_capability_.push_back(band_cap);
}
}
bool Device::ClaimDevice(bool full_control) {
if (GetInUse()) {
LOG(ERROR) << "Failed to claim device [" << GetDeviceName()
<< "]: already in used.";
return false;
}
if (full_control) {
for (const auto& interface : interface_list_) {
manager_->ClaimInterface(interface.iface_name);
claimed_interfaces_.insert(interface.iface_name);
}
} else {
manager_->ClaimInterface(GetPreferredApInterface());
claimed_interfaces_.insert(GetPreferredApInterface());
}
SetInUse(true);
return true;
}
bool Device::ReleaseDevice() {
if (!GetInUse()) {
LOG(ERROR) << "Failed to release device [" << GetDeviceName()
<< "]: not currently in-used.";
return false;
}
for (const auto& interface : claimed_interfaces_) {
manager_->ReleaseInterface(interface);
}
claimed_interfaces_.clear();
SetInUse(false);
return true;
}
bool Device::InterfaceExists(const string& interface_name) {
for (const auto& interface : interface_list_) {
if (interface.iface_name == interface_name) {
return true;
}
}
return false;
}
bool Device::GetHTCapability(uint16_t channel, string* ht_cap) {
// Get the band capability based on the channel.
BandCapability band_cap;
if (!GetBandCapability(channel, &band_cap)) {
LOG(ERROR) << "No band capability found for channel " << channel;
return false;
}
std::vector<string> ht_capability;
// LDPC coding capability.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskLdpcCoding) {
ht_capability.push_back("LDPC");
}
// Supported channel width set.
if (band_cap.ht_capability_mask &
shill::IEEE_80211::kHTCapMaskSupWidth2040) {
// Determine secondary channel is below or above the primary.
bool above = false;
if (!GetHTSecondaryChannelLocation(channel, &above)) {
LOG(ERROR) << "Unable to determine secondary channel location for "
<< "channel " << channel;
return false;
}
if (above) {
ht_capability.push_back("HT40+");
} else {
ht_capability.push_back("HT40-");
}
}
// Spatial Multiplexing (SM) Power Save.
uint16_t power_save_mask =
(band_cap.ht_capability_mask >>
shill::IEEE_80211::kHTCapMaskSmPsShift) & 0x3;
if (power_save_mask == 0) {
ht_capability.push_back("SMPS-STATIC");
} else if (power_save_mask == 1) {
ht_capability.push_back("SMPS-DYNAMIC");
}
// HT-greenfield.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskGrnFld) {
ht_capability.push_back("GF");
}
// Short GI for 20 MHz.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskSgi20) {
ht_capability.push_back("SHORT-GI-20");
}
// Short GI for 40 MHz.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskSgi40) {
ht_capability.push_back("SHORT-GI-40");
}
// Tx STBC.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskTxStbc) {
ht_capability.push_back("TX-STBC");
}
// Rx STBC.
uint16_t rx_stbc =
(band_cap.ht_capability_mask >>
shill::IEEE_80211::kHTCapMaskRxStbcShift) & 0x3;
if (rx_stbc == 1) {
ht_capability.push_back("RX-STBC1");
} else if (rx_stbc == 2) {
ht_capability.push_back("RX-STBC12");
} else if (rx_stbc == 3) {
ht_capability.push_back("RX-STBC123");
}
// HT-delayed Block Ack.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskDelayBA) {
ht_capability.push_back("DELAYED-BA");
}
// Maximum A-MSDU length.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskMaxAmsdu) {
ht_capability.push_back("MAX-AMSDU-7935");
}
// DSSS/CCK Mode in 40 MHz.
if (band_cap.ht_capability_mask & shill::IEEE_80211::kHTCapMaskDsssCck40) {
ht_capability.push_back("DSSS_CCK-40");
}
// 40 MHz intolerant.
if (band_cap.ht_capability_mask &
shill::IEEE_80211::kHTCapMask40MHzIntolerant) {
ht_capability.push_back("40-INTOLERANT");
}
*ht_cap = base::StringPrintf("[%s]",
brillo::string_utils::Join(" ", ht_capability).c_str());
return true;
}
bool Device::GetVHTCapability(uint16_t channel, string* vht_cap) {
// TODO(zqiu): to be implemented.
return false;
}
void Device::SetDeviceName(const std::string& device_name) {
adaptor_->SetDeviceName(device_name);
}
string Device::GetDeviceName() const {
return adaptor_->GetDeviceName();
}
void Device::SetPreferredApInterface(const std::string& interface_name) {
adaptor_->SetPreferredApInterface(interface_name);
}
string Device::GetPreferredApInterface() const {
return adaptor_->GetPreferredApInterface();
}
void Device::SetInUse(bool in_use) {
return adaptor_->SetInUse(in_use);
}
bool Device::GetInUse() const {
return adaptor_->GetInUse();
}
// static
bool Device::GetHTSecondaryChannelLocation(uint16_t channel, bool* above) {
bool ret_val = true;
// Determine secondary channel location base on the channel. Refer to
// ht_cap section in hostapd.conf documentation.
switch (channel) {
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 40:
case 48:
case 56:
case 64:
*above = false;
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 36:
case 44:
case 52:
case 60:
*above = true;
break;
default:
ret_val = false;
break;
}
return ret_val;
}
bool Device::GetBandCapability(uint16_t channel, BandCapability* capability) {
uint32_t frequency;
if (!Config::GetFrequencyFromChannel(channel, &frequency)) {
LOG(ERROR) << "Invalid channel " << channel;
return false;
}
for (const auto& band : band_capability_) {
if (std::find(band.frequencies.begin(),
band.frequencies.end(),
frequency) != band.frequencies.end()) {
*capability = band;
return true;
}
}
return false;
}
void Device::UpdatePreferredAPInterface() {
// Return if device doesn't support AP interface mode.
if (!supports_ap_mode_) {
return;
}
// Use the first registered AP mode interface if there is one, otherwise use
// the first registered managed mode interface. If none are available, then
// no interface can be used for AP operation on this device.
WiFiInterface preferred_interface;
for (const auto& interface : interface_list_) {
if (interface.iface_type == NL80211_IFTYPE_AP) {
preferred_interface = interface;
break;
} else if (interface.iface_type == NL80211_IFTYPE_STATION &&
preferred_interface.iface_name.empty()) {
preferred_interface = interface;
}
// Ignore all other interface types.
}
// Update preferred AP interface property.
SetPreferredApInterface(preferred_interface.iface_name);
}
} // namespace apmanager
| 29.92112 | 80 | 0.66936 | [
"vector"
] |
5223139cef3f4b7c4a09e23669befc31c0f42e9f | 4,136 | cc | C++ | src/objects/module.cc | Cc618/Riddim | da79694b78f854a075632d36e1bd9fa70d744ef2 | [
"MIT"
] | 7 | 2021-06-20T13:40:28.000Z | 2022-01-05T15:49:53.000Z | src/objects/module.cc | Cc618/Riddim | da79694b78f854a075632d36e1bd9fa70d744ef2 | [
"MIT"
] | null | null | null | src/objects/module.cc | Cc618/Riddim | da79694b78f854a075632d36e1bd9fa70d744ef2 | [
"MIT"
] | 1 | 2021-06-27T12:53:20.000Z | 2021-06-27T12:53:20.000Z | #include "module.hh"
#include "doc.hh"
#include "error.hh"
#include "null.hh"
#include "program.hh"
using namespace std;
void merge_frames(Frame *base, Frame *merged) {
for (const auto &[h, kv] : merged->vars->data) {
const auto &[name, value] = kv;
if (name->type != Str::class_type) {
continue;
}
auto name_str = reinterpret_cast<Str *>(name)->data;
// No special names
if (is_special_var(name_str, false)) {
continue;
}
// Merge this pair
base->vars->data[h] = kv;
}
}
Type *Module::class_type = nullptr;
Module::Module(Str *name, Code *code, Frame *frame, const str_t &filepath)
: Object(Module::class_type), name(name), code(code), frame(frame),
filepath(filepath) {}
void Module::init_class_type() {
class_type = new (nothrow) Type("Module");
if (!class_type) {
THROW_MEMORY_ERROR;
return;
}
class_type->fn_traverse_objects = [](Object *self,
const fn_visit_object_t &visit) {
Module *me = reinterpret_cast<Module *>(self);
visit(me->name);
visit(me->code);
visit(me->frame);
};
// @doc
class_type->fn_doc = [](Object *self) -> Object * {
auto me = dynamic_cast<Module *>(self);
if (!me) {
throw_fmt(RuntimeError, "Module.@doc got an invalid self instance");
return nullptr;
}
str_t current_doc;
// The !doc attribute may contain the documentation
auto docattr = Str::New("!doc");
if (!docattr) {
return nullptr;
}
auto it = me->frame->fetch(docattr);
if (it) {
if (it->type != Str::class_type) {
THROW_TYPE_ERROR_PREF("Module!doc", it->type, Str::class_type);
return nullptr;
}
current_doc = reinterpret_cast<Str *>(it)->data;
} else {
clear_error();
}
// Filter what to document
vector<pair<str_t, Object *>> children;
for (const auto &[h, kv] : me->frame->vars->data) {
const auto &[child_name, child] = kv;
if (child_name->type != Str::class_type) {
continue;
}
auto child_name_str = reinterpret_cast<Str *>(child_name)->data;
if (!is_special_var(child_name_str, false)) {
children.push_back({child_name_str, child});
}
}
str_t result = autodoc(1, me->name->data, current_doc, children);
if (on_error()) {
return nullptr;
}
if (result.empty()) {
return null;
}
auto sresult = Str::New(result);
if (!sresult) {
return nullptr;
}
return sresult;
};
// @getattr
class_type->fn_getattr = [](Object *self, Object *key) -> Object * {
Module *me = reinterpret_cast<Module *>(self);
auto result = me->frame->getitem(key);
return result;
};
// @str
class_type->fn_str = [](Object *self) -> Object * {
Module *me = reinterpret_cast<Module *>(self);
auto s = Str::New("Module(" + me->name->data + ")");
if (!s) {
return nullptr;
}
return s;
};
// @setattr
class_type->fn_setattr = [](Object *self, Object *key,
Object *value) -> Object * {
Module *me = reinterpret_cast<Module *>(self);
return me->frame->setitem(key, value);
};
}
Module *Module::New(const str_t &name, const str_t &filepath) {
auto namestr = Str::New(name);
if (!namestr) {
return nullptr;
}
auto code = Code::New(filepath);
if (!code)
return nullptr;
auto frame = Frame::New(name, filepath, Program::instance->top_frame);
if (!frame) {
return nullptr;
}
auto me = new (nothrow) Module(namestr, code, frame, filepath);
if (!me) {
THROW_MEMORY_ERROR;
return nullptr;
}
return me;
}
| 23.367232 | 80 | 0.523936 | [
"object",
"vector"
] |
52244904ad0e6a5721478718968fc3c02e4499bb | 1,906 | cpp | C++ | Backend/Machine Learning/Structure/layerinfo.cpp | Gattic/glades-ml | ee40a31e975456d8bdf101b60a38673403935a57 | [
"MIT"
] | 2 | 2020-02-12T23:02:14.000Z | 2020-02-12T23:22:29.000Z | Backend/Machine Learning/Structure/layerinfo.cpp | MeeseeksLookAtMe/glades-ml | ee40a31e975456d8bdf101b60a38673403935a57 | [
"MIT"
] | null | null | null | Backend/Machine Learning/Structure/layerinfo.cpp | MeeseeksLookAtMe/glades-ml | ee40a31e975456d8bdf101b60a38673403935a57 | [
"MIT"
] | null | null | null | // Copyright 2020 Robert Carneiro, Derek Meer, Matthew Tabak, Eric Lujan
//
// 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 "layerinfo.h"
using namespace glades;
/*!
* @brief LayerInfo constructor
* @details creates a LayerInfo object
* @param newSize desired LayerInfo size
*/
glades::LayerInfo::LayerInfo(int newSize)
{
lSize = newSize;
}
/*!
* @brief LayerInfo destructor
* @details destroys a LayerInfo object
* @param newSize desired LayerInfo size
*/
glades::LayerInfo::~LayerInfo()
{
lSize = 0;
}
/*!
* @brief get size
* @details get LayerInfo's size
* @return the LayerInfo's number of layers
*/
unsigned int glades::LayerInfo::size() const
{
return lSize;
}
/*!
* @brief set size
* @details set LayerInfo's size
* @param newLearningRate the desired size for this LayerInfo object
*/
void glades::LayerInfo::setSize(int newSize)
{
lSize = newSize;
}
| 32.305085 | 100 | 0.747639 | [
"object"
] |
5225fa314d8f88633e41f4ab774b91d6f7163fb8 | 6,012 | cpp | C++ | svntrunk/src/BlueMatter/probspectrans/src/probspectrans_to_MSD.cpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/BlueMatter/probspectrans/src/probspectrans_to_MSD.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/BlueMatter/probspectrans/src/probspectrans_to_MSD.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// ***********************************************************************
// File: probspectrans_to_MSD.cpp
// Author: cwo
// Date: July 13, 2006
// Namespace: probspectrans
// Class: ProbSpecTransToMSD
// Description: Reads DB entry from a run of probspectrans and outputs
// strings with array in MSD file format
// ***********************************************************************
#include <BlueMatter/probspectrans/probspectrans_to_MSD.hpp>
#include <BlueMatter/probspectrans/transform_sysparams.hpp>
//////////////////////////////////////////
// Static globals for this file only
#define SQLCMD_BUFSZ 512
#define SQLVARCHAR_BUFSZ 255
#define STREAM_PRECISION 16
static int verbosity = 0;
static void display_arguments()
{
std::cout << "Usage: probspectrans_to_MSD [ arguments ]" << std::endl;
std::cout << " [-db <string>] : Name of DB to connect to" << std::endl;
std::cout << " [-sysid <int> ] : System ID to transform" << std::endl;
std::cout << " [-verb <int> ] : Verbosity level" << std::endl;
std::cout << " [-o <string>] : Name of Output file" << std::endl;
} //end display_arguments()
int get_sys_id_from_pst_id( char* dbname, int pst_id )
{
db2::ConnHandle& db2conn = db2::DBName::instance( dbname )->connection();
db2::StmtHandle stmt1( db2conn );
char sqlcmd1[ SQLCMD_BUFSZ ];
snprintf( sqlcmd1, SQLCMD_BUFSZ, "select sys_id from MDSYSTEM.PSTID_to_exp "
" where pst_id=%d FOR READ ONLY WITH UR", pst_id);
stmt1.prepare( sqlcmd1 );
int sys_id = -1;
stmt1.bindCol(1, (SQLINTEGER&)sys_id);
try { stmt1.execute(); }
catch(db2::HandleException HE) { std::cerr << HE << " - Caught at Line " << __LINE__ << " in " << __FILE__ << std::endl; }
if( !stmt1.fetch() )
{
std::cerr << "ERROR:: sys_id is not found for pst_id: " << pst_id << std::endl;
}
return sys_id;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
////////////////////////////////////////////////////////////////////////////
// Set command line parameter defaults
////////////////////////////////////////////////////////////////////////////
std::string output_filename = "probspectrans_to_MSD.output";
char dbname[100];
strncpy(dbname, "mdtest", 100);
verbosity = 0;
// int _id = 19531;
int pst_id = -1;
if (argc < 2)
{
display_arguments();
exit(0);
}
////////////////////////////////////////////////////////////////////////////
// Read command line parameters
////////////////////////////////////////////////////////////////////////////
for (int i=1; (i<argc) && ((argv[i])[0])=='-'; i++)
{
if (strcmp("-pstid", argv[i])==0)
{
i++;
pst_id = atoi(argv[i]);
}
else if (strcmp("-verb", argv[i])==0)
{
i++;
verbosity = atoi(argv[i]);
}
else if (strcmp("-db", argv[i])==0)
{
i++;
strncpy(dbname, argv[i], 100);
}
else if (strcmp("-o", argv[i])==0)
{
i++;
output_filename = std::string(argv[i]);
}
else
{
std::cout << "Invalid Arguments." << std::endl;
display_arguments();
exit(1);
}
} //end for each argument
////////////////////////////////////////////////////////////////////////////
// Perform Actual Verification
////////////////////////////////////////////////////////////////////////////
int sys_id = get_sys_id_from_pst_id( dbname, pst_id );
std::cout << "=====================================" << std::endl;
std::cout << "BlueMatter" << std::endl;
std::cout << "Problem Specficiation Transformations" << std::endl;
std::cout << "DB to MSD Conversion Tool" << std::endl;
std::cout << "=====================================" << std::endl;
std::cout << "DB Name : " << dbname << std::endl;
std::cout << "PST ID : " << pst_id << std::endl;
std::cout << "SYS ID : " << sys_id << std::endl;
std::cout << "Verbosity : " << verbosity << std::endl;
std::cout << "Output File : " << output_filename << std::endl;
std::cout << "=====================================" << std::endl;
// int pst_id = rt_params.get_pst_id_from_sysid_and_run_time_options();
probspectrans::ProbSpecTransToMSD *db_to_MSD =
probspectrans::ProbSpecTransToMSD::instance(dbname, pst_id, sys_id);
std::ofstream file_ostream;
file_ostream.open(output_filename.c_str(), std::ios::out);
db_to_MSD->output_entire_MSD(file_ostream);
file_ostream.close();
} //end main()
| 36.436364 | 124 | 0.547738 | [
"transform"
] |
522a2ab07b96b6886ad92b74e7955991480bed32 | 1,605 | hpp | C++ | lib/minpart/minpart-contexts/literals.hpp | sellamiy/GPiD-Framework | f6ed1abb2da6d51639f5ee410b1f9b143a200465 | [
"BSD-3-Clause"
] | 8 | 2018-07-13T07:07:08.000Z | 2021-05-18T17:56:59.000Z | lib/minpart/minpart-contexts/literals.hpp | sellamiy/GPiD-Framework | f6ed1abb2da6d51639f5ee410b1f9b143a200465 | [
"BSD-3-Clause"
] | null | null | null | lib/minpart/minpart-contexts/literals.hpp | sellamiy/GPiD-Framework | f6ed1abb2da6d51639f5ee410b1f9b143a200465 | [
"BSD-3-Clause"
] | null | null | null | /**
* \file minpart-contexts/literals.hpp
* \brief Minimal partitioner literal example context
* \author Yanis Sellami
* \date 2019
*/
#include <vector>
#include <minpart/partitions.hpp>
#ifndef LIB_MINPART_CONTEXT_LITERALS__HEADER
#define LIB_MINPART_CONTEXT_LITERALS__HEADER
namespace minpart {
namespace literals {
struct LiteralProblemOptions {
size_t c_blocksize = 2;
size_t c_depth = 1;
size_t p_blocksize = 2;
size_t p_depth = 1;
size_t max_depth = 10;
size_t min_depth = 0;
bool random = false;
std::vector<uint32_t> problem;
};
class LiteralProblemContext {
public:
using Options = LiteralProblemOptions;
private:
const Options opts;
public:
LiteralProblemContext(const Options& opts)
: opts(opts)
{}
const PartitionGeneratorOptions generate_partition_options() const;
inline size_t get_hypotheses_size() const { return opts.problem.size(); }
inline uint32_t removal_level(uint32_t, size_t) const { return opts.max_depth + 1; }
inline bool is_empty_element(uint32_t element, size_t) const {
return element > opts.max_depth;
}
inline bool is_generalizable_element(uint32_t element, size_t) const {
return element <= opts.max_depth;
}
bool is_valid_hypothesis(const std::vector<uint32_t>& hyp) const;
bool is_coherent_hypothesis(const std::vector<uint32_t>& hyp) const;
void print(uint32_t element, size_t loc) const;
};
}
}
#endif
| 24.692308 | 92 | 0.659813 | [
"vector"
] |
5234a421a7e68ae4ba18422f1960414c2344e852 | 4,444 | cc | C++ | cpp/src/arrow/compute/function_internal.cc | NinaPeng/arrow | 91f261fa9a7841fd914c5ed1d8e747fb4e510a5b | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 1 | 2021-07-12T23:54:47.000Z | 2021-07-12T23:54:47.000Z | cpp/src/arrow/compute/function_internal.cc | NinaPeng/arrow | 91f261fa9a7841fd914c5ed1d8e747fb4e510a5b | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 8 | 2021-01-29T02:43:10.000Z | 2022-03-04T01:50:45.000Z | cpp/src/arrow/compute/function_internal.cc | lidavidm/arrow | c9b9fa4e9964926061ff7c80b09ed22eb0ef77a1 | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/compute/function_internal.h"
#include "arrow/array/util.h"
#include "arrow/compute/function.h"
#include "arrow/compute/registry.h"
#include "arrow/io/memory.h"
#include "arrow/ipc/reader.h"
#include "arrow/ipc/writer.h"
#include "arrow/record_batch.h"
#include "arrow/scalar.h"
#include "arrow/util/checked_cast.h"
namespace arrow {
namespace compute {
namespace internal {
using ::arrow::internal::checked_cast;
constexpr char kTypeNameField[] = "_type_name";
Result<std::shared_ptr<StructScalar>> FunctionOptionsToStructScalar(
const FunctionOptions& options) {
std::vector<std::string> field_names;
std::vector<std::shared_ptr<Scalar>> values;
const auto* options_type =
checked_cast<const GenericOptionsType*>(options.options_type());
RETURN_NOT_OK(options_type->ToStructScalar(options, &field_names, &values));
field_names.push_back(kTypeNameField);
const char* options_name = options.type_name();
values.emplace_back(
new BinaryScalar(Buffer::Wrap(options_name, std::strlen(options_name))));
return StructScalar::Make(std::move(values), std::move(field_names));
}
Result<std::unique_ptr<FunctionOptions>> FunctionOptionsFromStructScalar(
const StructScalar& scalar) {
ARROW_ASSIGN_OR_RAISE(auto type_name_holder, scalar.field(kTypeNameField));
const std::string type_name =
checked_cast<const BinaryScalar&>(*type_name_holder).value->ToString();
ARROW_ASSIGN_OR_RAISE(auto raw_options_type,
GetFunctionRegistry()->GetFunctionOptionsType(type_name));
const auto* options_type = checked_cast<const GenericOptionsType*>(raw_options_type);
return options_type->FromStructScalar(scalar);
}
Result<std::shared_ptr<Buffer>> GenericOptionsType::Serialize(
const FunctionOptions& options) const {
ARROW_ASSIGN_OR_RAISE(auto scalar, FunctionOptionsToStructScalar(options));
ARROW_ASSIGN_OR_RAISE(auto array, MakeArrayFromScalar(*scalar, 1));
auto batch =
RecordBatch::Make(schema({field("", array->type())}), /*num_rows=*/1, {array});
ARROW_ASSIGN_OR_RAISE(auto stream, io::BufferOutputStream::Create());
ARROW_ASSIGN_OR_RAISE(auto writer, ipc::MakeFileWriter(stream, batch->schema()));
RETURN_NOT_OK(writer->WriteRecordBatch(*batch));
RETURN_NOT_OK(writer->Close());
return stream->Finish();
}
Result<std::unique_ptr<FunctionOptions>> GenericOptionsType::Deserialize(
const Buffer& buffer) const {
return DeserializeFunctionOptions(buffer);
}
Result<std::unique_ptr<FunctionOptions>> DeserializeFunctionOptions(
const Buffer& buffer) {
io::BufferReader stream(buffer);
ARROW_ASSIGN_OR_RAISE(auto reader, ipc::RecordBatchFileReader::Open(&stream));
ARROW_ASSIGN_OR_RAISE(auto batch, reader->ReadRecordBatch(0));
if (batch->num_rows() != 1) {
return Status::Invalid(
"serialized FunctionOptions's batch repr was not a single row - had ",
batch->num_rows());
}
if (batch->num_columns() != 1) {
return Status::Invalid(
"serialized FunctionOptions's batch repr was not a single column - had ",
batch->num_columns());
}
auto column = batch->column(0);
if (column->type()->id() != Type::STRUCT) {
return Status::Invalid(
"serialized FunctionOptions's batch repr was not a struct column - was ",
column->type()->ToString());
}
ARROW_ASSIGN_OR_RAISE(auto raw_scalar,
checked_cast<const StructArray&>(*column).GetScalar(0));
auto scalar = checked_cast<const StructScalar&>(*raw_scalar);
return FunctionOptionsFromStructScalar(scalar);
}
} // namespace internal
} // namespace compute
} // namespace arrow
| 40.4 | 87 | 0.738749 | [
"vector"
] |
5235ed0b86731cbb7f46905f669dd5742ffe3d24 | 12,582 | cpp | C++ | applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL_Components/OPENGL_COMPONENT_HEIGHTFIELD_1D.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL_Components/OPENGL_COMPONENT_HEIGHTFIELD_1D.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL_Components/OPENGL_COMPONENT_HEIGHTFIELD_1D.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | //#####################################################################
// Copyright 2004, Eran Guendelman.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Read_Write/Grids_Uniform_Arrays/READ_WRITE_ARRAYS.h>
#include <PhysBAM_Tools/Read_Write/Utilities/FILE_UTILITIES.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_PRIMITIVES.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL_Components/OPENGL_COMPONENT_HEIGHTFIELD_1D.h>
using namespace PhysBAM;
//#####################################################################
template<class T,class RW> OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
OPENGL_COMPONENT_HEIGHTFIELD_1D(const GRID<TV> &grid_input,
const std::string& height_filename_input,
const std::string& x_filename_input,
const std::string& ground_filename_input,
const std::string& u_filename_input)
: OPENGL_COMPONENT("Heightfield 1D"), grid(grid_input), opengl_vector_field(vector_field,vector_locations), scale(1), displacement_scale(1), valid(false),
draw_velocities(true), draw_points(true), selected_index(0)
{
height_filename=height_filename_input;
if(x_filename_input.length()){x=new ARRAY<T,TV_INT>;x_filename=x_filename_input;}
else{x=0;x_filename="";}
if(ground_filename_input.length()){ground=new ARRAY<T,TV_INT>;ground_filename=ground_filename_input;}
else{ground=0;ground_filename="";}
if(u_filename_input.length()){
u = new ARRAY<T,TV_INT>;
vector_field.Resize(grid.counts.x);
vector_locations.Resize(grid.counts.x);
u_filename=u_filename_input;}
else{u=0;u_filename="";}
is_animation=height_filename.find("%d")!=std::string::npos;
frame_loaded = -1;
Reinitialize();
}
template<class T,class RW> OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
~OPENGL_COMPONENT_HEIGHTFIELD_1D()
{
delete x;
delete ground;
delete u;
}
template<class T,class RW> bool OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Valid_Frame(int frame_input) const
{
return FILE_UTILITIES::File_Exists(is_animation?STRING_UTILITIES::string_sprintf(height_filename.c_str(),frame_input):height_filename);
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Set_Frame(int frame_input)
{
OPENGL_COMPONENT::Set_Frame(frame_input);
Reinitialize();
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Set_Draw(bool draw_input)
{
OPENGL_COMPONENT::Set_Draw(draw_input);
Reinitialize();
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Display(const int in_color) const
{
ARRAY<typename OPENGL_POLICY<T>::T_GL> vertices;
OPENGL_COLOR water_color(0,0,1);
OPENGL_COLOR ground_color = OPENGL_COLOR::Gray(0.8f);
OPENGL_COLOR displaced_water(1,0,0);
OPENGL_COLOR points_color(0,1,1);
OPENGL_COLOR selected_point_color = OPENGL_COLOR::Yellow();
GLfloat point_size = 3.0;
GLint mode=0;
#ifndef USE_OPENGLES
glGetIntegerv(GL_RENDER_MODE, &mode);
#endif
if (valid && draw)
{
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
#ifndef USE_OPENGLES
if(mode == GL_SELECT)
{
glPushName(0);
glPushAttrib(GL_POINT_BIT);
glPointSize(point_size);
points_color.Send_To_GL_Pipeline();
for (int i = 1; i <= grid.counts.x; i++)
{
glLoadName(i);
vertices.Resize(0);
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(i,1), scale*height(i)),vertices);
OpenGL_Draw_Arrays(GL_POINTS,2,vertices);
}
glPopAttrib();
glPopName();
}
else
#endif
{
if (x)
{
displaced_water.Send_To_GL_Pipeline();
vertices.Resize(0);
if (displacement_scale == 1)
{
for (int i = 1; i <= x->counts.x; i++)
OpenGL_Vertex(VECTOR<T,2>((*x)(i), scale*height(i)),vertices);
}
else
{
for (int i = 1; i <= x->counts.x; i++)
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(i,1) + displacement_scale*((*x)(i)-grid.Axis_X(i,1)),
scale*height(i)),vertices);
}
OpenGL_Draw_Arrays(GL_LINE_STRIP,2,vertices);
}
// Water
water_color.Send_To_GL_Pipeline();
vertices.Resize(0);
for (int i = 1; i <= grid.counts.x; i++)
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(i,1), scale*height(i)),vertices);
OpenGL_Draw_Arrays(GL_LINE_STRIP,2,vertices);
if (draw_points)
{
glPushAttrib(GL_POINT_BIT);
glPointSize(point_size);
points_color.Send_To_GL_Pipeline();
vertices.Resize(0);
for (int i = 1; i <= grid.counts.x; i++)
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(i,1), scale*height(i)),vertices);
OpenGL_Draw_Arrays(GL_POINTS,2,vertices);
#ifndef USE_OPENGLES
for(int i=1;i<=grid.counts.x;i++)
OpenGL_String(VECTOR<T,2>(grid.Axis_X(i,1),scale*height(i)),STRING_UTILITIES::string_sprintf("%d",i));
#endif
if(selected_index){
selected_point_color.Send_To_GL_Pipeline();
int i=selected_index;
vertices.Resize(0);
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(i,1), scale*height(i)),vertices);
OpenGL_Draw_Arrays(GL_POINTS,2,vertices);
#ifndef USE_OPENGLES
OpenGL_String(VECTOR<T,2>(grid.Axis_X(i,1),scale*height(i)),STRING_UTILITIES::string_sprintf("%d",i));
#endif
}
glPopAttrib();
}
// Ground
ground_color.Send_To_GL_Pipeline();
if (ground)
{
vertices.Resize(0);
for (int i = 1; i <= grid.counts.x; i++)
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(i,1), scale*(*ground)(i)),vertices);
OpenGL_Draw_Arrays(GL_LINE_STRIP,2,vertices);
}
else
{
vertices.Resize(0);
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(1,1), 0),vertices);
OpenGL_Vertex(VECTOR<T,2>(grid.Axis_X(grid.counts.x,1), 0),vertices);
OpenGL_Draw_Arrays(GL_LINE_STRIP,2,vertices);
}
}
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
#ifndef USE_OPENGLES
if (mode != GL_SELECT && draw_velocities) opengl_vector_field.Display(in_color);
#else
if (draw_velocities) opengl_vector_field.Display(in_color);
#endif
}
}
template<class T,class RW> RANGE<VECTOR<float,3> > OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Bounding_Box() const
{
if (valid && draw)
{
T min_height=min((T)0,height.Min());
T max_height=max((T)0,height.Max());
T min_x = grid.domain.min_corner.x, max_x = grid.domain.max_corner.x;
if (x) {
min_x=min(min_x,x->Min());
max_x=max(max_x,x->Max());
}
return RANGE<VECTOR<float,3> >((float)min_x,(float)max_x,(float)min_height,(float)max_height, 0, 0);
}
else return RANGE<VECTOR<float,3> >::Centered_Box();
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Reinitialize(bool force)
{
if(draw){
if(force || (is_animation && frame_loaded != frame) || (!is_animation && frame_loaded < 0)){
bool success = true;
valid = false;
if (success){
std::string filename=FILE_UTILITIES::Get_Frame_Filename(height_filename,frame);
if(FILE_UTILITIES::File_Exists(filename)){
FILE_UTILITIES::Read_From_File<RW>(filename,height);
if(height.counts.x != grid.counts.x) success=false;}
else success=false;}
if(success && x){
std::string filename=FILE_UTILITIES::Get_Frame_Filename(x_filename,frame);
if(FILE_UTILITIES::File_Exists(filename)){
FILE_UTILITIES::Read_From_File<RW>(filename,*x);
if(height.counts.x != x->counts.x) success=false;}
else success=false;}
if(success && ground){
std::string filename=FILE_UTILITIES::Get_Frame_Filename(ground_filename,frame);
if(FILE_UTILITIES::File_Exists(filename)){
FILE_UTILITIES::Read_From_File<RW>(filename,*ground);
if (height.counts.x != ground->counts.x) success = false;
else height += (*ground);}
else success=false;}
if(success && draw_velocities && u_filename.length()){
std::string filename=FILE_UTILITIES::Get_Frame_Filename(u_filename,frame);
if(FILE_UTILITIES::File_Exists(filename)){
FILE_UTILITIES::Read_From_File<RW>(filename,*u);
if (height.counts.x != u->counts.x) success = false;
else for(int i=1;i<=grid.counts.x;i++){
vector_field(i) = VECTOR<T,2>((*u)(i),0);
vector_locations(i) = VECTOR<T,2>(grid.Axis_X(i,1), scale*height(i));}}
else success=false;}
if(success){
frame_loaded = frame;
valid = true;}}}
}
template<class T,class RW> OPENGL_SELECTION *OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Get_Selection(GLuint *buffer,int buffer_size)
{
if (buffer_size == 1)
{
OPENGL_SELECTION_COMPONENT_HEIGHTFIELD_1D<T> *selection = new OPENGL_SELECTION_COMPONENT_HEIGHTFIELD_1D<T>(this);
selection->index = buffer[0];
return selection;
}
else return 0;
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Highlight_Selection(OPENGL_SELECTION *selection)
{
if (selection->type != OPENGL_SELECTION::COMPONENT_HEIGHTFIELD_1D) return;
OPENGL_SELECTION_COMPONENT_HEIGHTFIELD_1D<T> *real_selection = (OPENGL_SELECTION_COMPONENT_HEIGHTFIELD_1D<T>*)selection;
selected_index = real_selection->index;
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Clear_Highlight()
{
selected_index = 0;
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Set_Scale(T scale_input)
{
scale = scale_input;
Reinitialize(true); // To recompute velocity vector positions correctly
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Increase_Scale()
{
scale *= (T)1.1;
Reinitialize(true); // To recompute velocity vector positions correctly
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Decrease_Scale()
{
scale *= 1/(T)1.1;
Reinitialize(true); // To recompute velcity vector positions correctly
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Increase_Displacement_Scale()
{
displacement_scale *= (T)1.1;
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Decrease_Displacement_Scale()
{
displacement_scale *= 1/(T)1.1;
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Increase_Velocity_Scale()
{
opengl_vector_field.size *= (T)1.1;
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Decrease_Velocity_Scale()
{
opengl_vector_field.size *= 1/(T)1.1;
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Toggle_Draw_Velocities()
{
draw_velocities = !draw_velocities;
Reinitialize(true);
}
template<class T,class RW> void OPENGL_COMPONENT_HEIGHTFIELD_1D<T,RW>::
Toggle_Draw_Points()
{
draw_points = !draw_points;
}
template<class T> RANGE<VECTOR<float,3> > OPENGL_SELECTION_COMPONENT_HEIGHTFIELD_1D<T>::
Bounding_Box() const
{
PHYSBAM_WARN_IF_NOT_OVERRIDDEN();
return RANGE<VECTOR<float,3> >::Empty_Box();
}
template class OPENGL_COMPONENT_HEIGHTFIELD_1D<float,float>;
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
template class OPENGL_COMPONENT_HEIGHTFIELD_1D<double,double>;
#endif
| 36.051576 | 159 | 0.616436 | [
"vector"
] |
5236fe955e1268f4f5eb80cb8069194fb4df0d5e | 2,825 | hpp | C++ | cpp/include/data_structure/set/disjoint_set.hpp | rohithv999/ProAlgos-Cpp | 36dcb1706e464bdbabfb949ac194b4db12aead3d | [
"MIT"
] | 222 | 2020-05-12T23:33:21.000Z | 2022-03-31T16:57:43.000Z | cpp/include/data_structure/set/disjoint_set.hpp | rohithv999/ProAlgos-Cpp | 36dcb1706e464bdbabfb949ac194b4db12aead3d | [
"MIT"
] | 93 | 2020-05-07T21:08:41.000Z | 2022-03-28T00:40:04.000Z | cpp/include/data_structure/set/disjoint_set.hpp | rohithv999/ProAlgos-Cpp | 36dcb1706e464bdbabfb949ac194b4db12aead3d | [
"MIT"
] | 95 | 2020-05-07T22:22:11.000Z | 2022-02-01T08:39:25.000Z | /*
Disjoint-set
------------
A disjoint-set data structure (also called a union–find data structure or
merge–find set) keeps track of a set of elements partitioned into a number
of disjoint (non-overlapping) subsets.
*/
#ifndef DISJOINT_SET_HPP
#define DISJOINT_SET_HPP
#include <cstddef>
#include <vector>
struct Element {
int parent;
int rank;
};
/*
DisjointSet
-----------
Class implementing the disjoint-set data structure.
*/
class DisjointSet {
std::vector<Element> set;
public:
DisjointSet(size_t);
int find(int);
void join(int, int);
size_t size() const;
};
/*
Constructor
-----------
*/
DisjointSet::DisjointSet(size_t num_nodes) {
set.resize(num_nodes);
// initially all elements are parents of themselves, with rank 0
for (size_t element = 0; element < set.size(); element++) {
set[element].parent = element;
set[element].rank = 0;
}
}
/*
find
----
Returns the representative (root) element of the given element, while also
performing path compression - making the representative the parent of all
elements in the "path".
Time complexity
---------------
log*(N), where N is the number of elements in the disjoint-set.
Space complexity
----------------
O(1).
*/
int DisjointSet::find(int x) {
// recursively travel to the representative element while also performing
// path compression
if (set[x].parent != x)
set[x].parent = find(set[x].parent);
return set[x].parent;
}
/*
join
----
Joins the subsets to which the given elements belong to, depending on the
rank of their representative elements.
Time complexity
---------------
log*(N), where N is the number of elements in the disjoint-set.
Space complexity
----------------
O(1).
*/
void DisjointSet::join(int x, int y) {
// find the representatives (roots) of the given elements
int x_root = find(x);
int y_root = find(y);
if (x_root == y_root) // if x and y are already in the same set
return; // nothing to do
// otherwise, join them depending on their representative's rank
if (set[x_root].rank < set[y_root].rank) // if x's rank is less than y's
set[x_root].parent = y_root; // join x's root to y's
else { // if y's rank is less than (or equal to) x's
set[y_root].parent = x_root; // join y's root to x's
if (set[x_root].rank == set[y_root].rank) // if the ranks are equal
++set[x_root].rank; // increase the rank of x's representative
}
}
/*
size
----
Returns the number of elements in the set.
*/
size_t DisjointSet::size() const {
return set.size();
}
#endif // DISJOINT_SET_HPP
| 22.070313 | 79 | 0.604956 | [
"vector"
] |
5237d09a33f72f813e38ba131ad364c57736c6dd | 1,240 | cpp | C++ | codeforces/C - Obtain The String/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/C - Obtain The String/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/C - Obtain The String/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Jan/29/2020 21:02
* solution_verdict: Accepted language: GNU C++14
* run_time: 31 ms memory_used: 1500 KB
* problem: https://codeforces.com/contest/1295/problem/C
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
vector<int>po[26+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
string s,t;cin>>s>>t;for(int i=0;i<26;i++)po[i].clear();
int i=0;
for(auto x:s)po[x-'a'].push_back(i++);
int ans=1,pt=-1;
for(int j=0;j<t.size();j++)
{
int c=t[j]-'a';
int i=upper_bound(po[c].begin(),po[c].end(),pt)-po[c].begin();
if(i<po[c].size())pt=po[c][i];
else
{
ans++;pt=-1;j--;
}
if(ans>t.size())
{
ans=-1;break;
}
}
cout<<ans<<"\n";
}
return 0;
} | 31.794872 | 111 | 0.381452 | [
"vector"
] |
523ab0c4037b6d8f81c8e75d422c1ad613a642e0 | 20,945 | cpp | C++ | Engine/Source/Runtime/Windows/AudioMixerXAudio2/Private/AudioMixerPlatformXAudio2.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Windows/AudioMixerXAudio2/Private/AudioMixerPlatformXAudio2.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Windows/AudioMixerXAudio2/Private/AudioMixerPlatformXAudio2.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/**
Concrete implementation of FAudioDevice for XAudio2
See https://msdn.microsoft.com/en-us/library/windows/desktop/hh405049%28v=vs.85%29.aspx
*/
#include "AudioMixerPlatformXAudio2.h"
#include "AudioMixer.h"
#include "AudioMixerDevice.h"
#include "HAL/PlatformAffinity.h"
#ifndef WITH_XMA2
#define WITH_XMA2 0
#endif
#if WITH_XMA2
#include "XMAAudioInfo.h"
#endif //#if WITH_XMA2
#include "OpusAudioInfo.h"
#include "VorbisAudioInfo.h"
#include "CoreGlobals.h"
#include "Misc/ConfigCacheIni.h"
// Macro to check result code for XAudio2 failure, get the string version, log, and goto a cleanup
#define XAUDIO2_CLEANUP_ON_FAIL(Result) \
if (FAILED(Result)) \
{ \
const TCHAR* ErrorString = GetErrorString(Result); \
AUDIO_PLATFORM_ERROR(ErrorString); \
goto Cleanup; \
}
// Macro to check result for XAudio2 failure, get string version, log, and return false
#define XAUDIO2_RETURN_ON_FAIL(Result) \
if (FAILED(Result)) \
{ \
const TCHAR* ErrorString = GetErrorString(Result); \
AUDIO_PLATFORM_ERROR(ErrorString); \
return false; \
}
namespace Audio
{
void FXAudio2VoiceCallback::OnBufferEnd(void* BufferContext)
{
check(BufferContext);
IAudioMixerPlatformInterface* MixerPlatform = (IAudioMixerPlatformInterface*)BufferContext;
MixerPlatform->ReadNextBuffer();
}
FMixerPlatformXAudio2::FMixerPlatformXAudio2()
: bDeviceChanged(false)
, XAudio2System(nullptr)
, OutputAudioStreamMasteringVoice(nullptr)
, OutputAudioStreamSourceVoice(nullptr)
, bMoveAudioStreamToNewAudioDevice(false)
, bIsComInitialized(false)
, bIsInitialized(false)
, bIsDeviceOpen(false)
{
// Build the channel map. Index corresponds to unreal audio mixer channel enumeration.
ChannelTypeMap.Add(SPEAKER_FRONT_LEFT);
ChannelTypeMap.Add(SPEAKER_FRONT_RIGHT);
ChannelTypeMap.Add(SPEAKER_FRONT_CENTER);
ChannelTypeMap.Add(SPEAKER_LOW_FREQUENCY);
ChannelTypeMap.Add(SPEAKER_BACK_LEFT);
ChannelTypeMap.Add(SPEAKER_BACK_RIGHT);
ChannelTypeMap.Add(SPEAKER_FRONT_LEFT_OF_CENTER);
ChannelTypeMap.Add(SPEAKER_FRONT_RIGHT_OF_CENTER);
ChannelTypeMap.Add(SPEAKER_BACK_CENTER);
ChannelTypeMap.Add(SPEAKER_SIDE_LEFT);
ChannelTypeMap.Add(SPEAKER_SIDE_RIGHT);
ChannelTypeMap.Add(SPEAKER_TOP_CENTER);
ChannelTypeMap.Add(SPEAKER_TOP_FRONT_LEFT);
ChannelTypeMap.Add(SPEAKER_TOP_FRONT_CENTER);
ChannelTypeMap.Add(SPEAKER_TOP_FRONT_RIGHT);
ChannelTypeMap.Add(SPEAKER_TOP_BACK_LEFT);
ChannelTypeMap.Add(SPEAKER_TOP_BACK_CENTER);
ChannelTypeMap.Add(SPEAKER_TOP_BACK_RIGHT);
ChannelTypeMap.Add(SPEAKER_RESERVED); // Speaker type EAudioMixerChannel::Unused,
// Make sure the above mappings line up with our enumerations since we loop below
check(ChannelTypeMap.Num() == EAudioMixerChannel::ChannelTypeCount);
}
FMixerPlatformXAudio2::~FMixerPlatformXAudio2()
{
}
const TCHAR* FMixerPlatformXAudio2::GetErrorString(HRESULT Result)
{
switch (Result)
{
case HRESULT(XAUDIO2_E_INVALID_CALL): return TEXT("XAUDIO2_E_INVALID_CALL");
case HRESULT(XAUDIO2_E_XMA_DECODER_ERROR): return TEXT("XAUDIO2_E_XMA_DECODER_ERROR");
case HRESULT(XAUDIO2_E_XAPO_CREATION_FAILED): return TEXT("XAUDIO2_E_XAPO_CREATION_FAILED");
case HRESULT(XAUDIO2_E_DEVICE_INVALIDATED): return TEXT("XAUDIO2_E_DEVICE_INVALIDATED");
#if PLATFORM_WINDOWS
case REGDB_E_CLASSNOTREG: return TEXT("REGDB_E_CLASSNOTREG");
case CLASS_E_NOAGGREGATION: return TEXT("CLASS_E_NOAGGREGATION");
case E_NOINTERFACE: return TEXT("E_NOINTERFACE");
case E_POINTER: return TEXT("E_POINTER");
case E_INVALIDARG: return TEXT("E_INVALIDARG");
case E_OUTOFMEMORY: return TEXT("E_OUTOFMEMORY");
#endif
default: return TEXT("UKNOWN");
}
}
bool FMixerPlatformXAudio2::InitializeHardware()
{
if (bIsInitialized)
{
AUDIO_PLATFORM_ERROR(TEXT("XAudio2 already initialized."));
return false;
}
#if PLATFORM_WINDOWS
bIsComInitialized = FWindowsPlatformMisc::CoInitialize();
#endif //#if PLATFORM_WINDOWS
uint32 Flags = 0;
#if WITH_XMA2
// We need to raise this flag explicitly to prevent initializing SHAPE twice, because we are allocating SHAPE in FXMAAudioInfo
Flags |= XAUDIO2_DO_NOT_USE_SHAPE;
#endif
XAUDIO2_RETURN_ON_FAIL(XAudio2Create(&XAudio2System, Flags, (XAUDIO2_PROCESSOR)FPlatformAffinity::GetAudioThreadMask()));
#if WITH_XMA2
//Initialize our XMA2 decoder context
FXMAAudioInfo::Initialize();
#endif //#if WITH_XMA2
// Load ogg and vorbis dlls if they haven't been loaded yet
LoadVorbisLibraries();
bIsInitialized = true;
return true;
}
bool FMixerPlatformXAudio2::TeardownHardware()
{
if (!bIsInitialized)
{
AUDIO_PLATFORM_ERROR(TEXT("XAudio2 was already tore down."));
return false;
}
SAFE_RELEASE(XAudio2System);
#if PLATFORM_WINDOWS
if (bIsComInitialized)
{
FWindowsPlatformMisc::CoUninitialize();
}
#endif
bIsInitialized = false;
return true;
}
bool FMixerPlatformXAudio2::IsInitialized() const
{
return bIsInitialized;
}
bool FMixerPlatformXAudio2::GetNumOutputDevices(uint32& OutNumOutputDevices)
{
if (!bIsInitialized)
{
AUDIO_PLATFORM_ERROR(TEXT("XAudio2 was not initialized."));
return false;
}
#if PLATFORM_WINDOWS
check(XAudio2System);
XAUDIO2_RETURN_ON_FAIL(XAudio2System->GetDeviceCount(&OutNumOutputDevices));
#else
OutNumOutputDevices = 1;
#endif
return true;
}
bool FMixerPlatformXAudio2::GetOutputDeviceInfo(const uint32 InDeviceIndex, FAudioPlatformDeviceInfo& OutInfo)
{
if (!bIsInitialized)
{
AUDIO_PLATFORM_ERROR(TEXT("XAudio2 was not initialized."));
return false;
}
#if PLATFORM_WINDOWS
check(XAudio2System);
XAUDIO2_DEVICE_DETAILS DeviceDetails;
XAUDIO2_RETURN_ON_FAIL(XAudio2System->GetDeviceDetails(InDeviceIndex, &DeviceDetails));
OutInfo.Name = FString(DeviceDetails.DisplayName);
OutInfo.DeviceId = FString(DeviceDetails.DeviceID);
OutInfo.bIsSystemDefault = (InDeviceIndex == 0);
// Get the wave format to parse there rest of the device details
const WAVEFORMATEX& WaveFormatEx = DeviceDetails.OutputFormat.Format;
OutInfo.SampleRate = WaveFormatEx.nSamplesPerSec;
OutInfo.NumChannels = WaveFormatEx.nChannels;
// XAudio2 automatically converts the audio format to output device us so we don't need to do any format conversions
OutInfo.Format = EAudioMixerStreamDataFormat::Float;
OutInfo.OutputChannelArray.Reset();
// Extensible format supports surround sound so we need to parse the channel configuration to build our channel output array
if (WaveFormatEx.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
{
// Cast to the extensible format to get access to extensible data
const WAVEFORMATEXTENSIBLE* WaveFormatExtensible = (WAVEFORMATEXTENSIBLE*)&WaveFormatEx;
// Loop through the extensible format channel flags in the standard order and build our output channel array
// From https://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
// The channels in the interleaved stream corresponding to these spatial positions must appear in the order specified above. This holds true even in the
// case of a non-contiguous subset of channels. For example, if a stream contains left, bass enhance and right, then channel 1 is left, channel 2 is right,
// and channel 3 is bass enhance. This enables the linkage of multi-channel streams to well-defined multi-speaker configurations.
check(EAudioMixerChannel::ChannelTypeCount == ChannelTypeMap.Num());
uint32 ChanCount = 0;
for (uint32 ChannelTypeIndex = 0; ChannelTypeIndex < EAudioMixerChannel::ChannelTypeCount && ChanCount < WaveFormatEx.nChannels; ++ChannelTypeIndex)
{
if (WaveFormatExtensible->dwChannelMask & ChannelTypeMap[ChannelTypeIndex])
{
OutInfo.OutputChannelArray.Add((EAudioMixerChannel::Type)ChannelTypeIndex);
}
else
{
EAudioMixerChannel::Type ChannelType;
bool bSuccess = GetChannelTypeAtIndex(ChanCount, ChannelType);
check(bSuccess);
OutInfo.OutputChannelArray.Add(ChannelType);
}
++ChanCount;
}
}
else
{
// Non-extensible formats only support mono or stereo channel output
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::FrontLeft);
if (OutInfo.NumChannels == 2)
{
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::FrontRight);
}
}
UE_LOG(LogAudioMixerDebug, Log, TEXT("Audio Device Output Speaker Info:"));
UE_LOG(LogAudioMixerDebug, Log, TEXT("Name: %s"), *OutInfo.Name);
UE_LOG(LogAudioMixerDebug, Log, TEXT("Is Default: %s"), OutInfo.bIsSystemDefault ? TEXT("Yes") : TEXT("No"));
UE_LOG(LogAudioMixerDebug, Log, TEXT("Sample Rate: %d"), OutInfo.SampleRate);
UE_LOG(LogAudioMixerDebug, Log, TEXT("Channel Count: %d"), OutInfo.NumChannels);
UE_LOG(LogAudioMixerDebug, Log, TEXT("Channel Order:"));
for (int32 i = 0; i < OutInfo.NumChannels; ++i)
{
if (i < OutInfo.OutputChannelArray.Num())
{
UE_LOG(LogAudioMixerDebug, Log, TEXT("%d: %s"), i, EAudioMixerChannel::ToString(OutInfo.OutputChannelArray[i]));
}
}
#else // #if PLATFORM_WINDOWS
OutInfo.bIsSystemDefault = true;
OutInfo.SampleRate = 44100;
OutInfo.DeviceId = 0;
OutInfo.Format = EAudioMixerStreamDataFormat::Float;
OutInfo.Name = TEXT("XboxOne Audio Device.");
OutInfo.NumChannels = 8;
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::FrontLeft);
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::FrontRight);
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::FrontCenter);
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::LowFrequency);
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::BackLeft);
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::BackRight);
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::SideLeft);
OutInfo.OutputChannelArray.Add(EAudioMixerChannel::SideRight);
#endif // #else // #if PLATFORM_WINDOWS
return true;
}
bool FMixerPlatformXAudio2::GetDefaultOutputDeviceIndex(uint32& OutDefaultDeviceIndex) const
{
OutDefaultDeviceIndex = 0;
return true;
}
bool FMixerPlatformXAudio2::OpenAudioStream(const FAudioMixerOpenStreamParams& Params)
{
if (!bIsInitialized)
{
AUDIO_PLATFORM_ERROR(TEXT("XAudio2 was not initialized."));
return false;
}
if (bIsDeviceOpen)
{
AUDIO_PLATFORM_ERROR(TEXT("XAudio2 audio stream already opened."));
return false;
}
check(XAudio2System);
check(OutputAudioStreamMasteringVoice == nullptr);
WAVEFORMATEX Format = { 0 };
OpenStreamParams = Params;
// On windows, default device index is 0
if (Params.OutputDeviceIndex == AUDIO_MIXER_DEFAULT_DEVICE_INDEX)
{
OpenStreamParams.OutputDeviceIndex = 0;
}
AudioStreamInfo.Reset();
AudioStreamInfo.OutputDeviceIndex = OpenStreamParams.OutputDeviceIndex;
AudioStreamInfo.NumOutputFrames = OpenStreamParams.NumFrames;
AudioStreamInfo.NumBuffers = OpenStreamParams.NumBuffers;
AudioStreamInfo.AudioMixer = OpenStreamParams.AudioMixer;
if (!GetOutputDeviceInfo(AudioStreamInfo.OutputDeviceIndex, AudioStreamInfo.DeviceInfo))
{
return false;
}
// Store the device ID here in case it is removed. We can switch back if the device comes back.
if (Params.bRestoreIfRemoved)
{
OriginalAudioDeviceId = AudioStreamInfo.DeviceInfo.DeviceId;
}
#if PLATFORM_WINDOWS
HRESULT Result = XAudio2System->CreateMasteringVoice(&OutputAudioStreamMasteringVoice, AudioStreamInfo.DeviceInfo.NumChannels, AudioStreamInfo.DeviceInfo.SampleRate, 0, AudioStreamInfo.OutputDeviceIndex, nullptr);
#elif PLATFORM_XBOXONE
HRESULT Result = XAudio2System->CreateMasteringVoice(&OutputAudioStreamMasteringVoice, AudioStreamInfo.DeviceInfo.NumChannels, AudioStreamInfo.DeviceInfo.SampleRate, 0, nullptr, nullptr);
#endif // #if PLATFORM_WINDOWS
XAUDIO2_CLEANUP_ON_FAIL(Result);
// Start the xaudio2 engine running, which will now allow us to start feeding audio to it
XAudio2System->StartEngine();
// Setup the format of the output source voice
Format.nChannels = AudioStreamInfo.DeviceInfo.NumChannels;
Format.nSamplesPerSec = Params.SampleRate;
Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
Format.nAvgBytesPerSec = Format.nSamplesPerSec * sizeof(float) * Format.nChannels;
Format.nBlockAlign = sizeof(float) * Format.nChannels;
Format.wBitsPerSample = sizeof(float) * 8;
// Create the output source voice
Result = XAudio2System->CreateSourceVoice(&OutputAudioStreamSourceVoice, &Format, XAUDIO2_VOICE_NOPITCH, 2.0f, &OutputVoiceCallback);
XAUDIO2_RETURN_ON_FAIL(Result);
AudioStreamInfo.StreamState = EAudioOutputStreamState::Open;
bIsDeviceOpen = true;
Cleanup:
if (FAILED(Result))
{
CloseAudioStream();
}
return SUCCEEDED(Result);
}
FAudioPlatformDeviceInfo FMixerPlatformXAudio2::GetPlatformDeviceInfo() const
{
return AudioStreamInfo.DeviceInfo;
}
bool FMixerPlatformXAudio2::CloseAudioStream()
{
if (!bIsInitialized || AudioStreamInfo.StreamState == EAudioOutputStreamState::Closed)
{
return false;
}
if (bIsDeviceOpen && !StopAudioStream())
{
return false;
}
check(XAudio2System);
XAudio2System->StopEngine();
if (OutputAudioStreamSourceVoice)
{
OutputAudioStreamSourceVoice->DestroyVoice();
OutputAudioStreamSourceVoice = nullptr;
}
check(OutputAudioStreamMasteringVoice);
OutputAudioStreamMasteringVoice->DestroyVoice();
OutputAudioStreamMasteringVoice = nullptr;
bIsDeviceOpen = false;
AudioStreamInfo.StreamState = EAudioOutputStreamState::Closed;
return true;
}
bool FMixerPlatformXAudio2::StartAudioStream()
{
// Start generating audio with our output source voice
BeginGeneratingAudio();
// If we already have a source voice, we can just restart it
if (OutputAudioStreamSourceVoice)
{
AudioStreamInfo.StreamState = EAudioOutputStreamState::Running;
OutputAudioStreamSourceVoice->Start();
return true;
}
return false;
}
bool FMixerPlatformXAudio2::StopAudioStream()
{
if (!bIsInitialized)
{
AUDIO_PLATFORM_ERROR(TEXT("XAudio2 was not initialized."));
return false;
}
check(XAudio2System);
if (AudioStreamInfo.StreamState != EAudioOutputStreamState::Stopped && AudioStreamInfo.StreamState != EAudioOutputStreamState::Closed)
{
if (AudioStreamInfo.StreamState == EAudioOutputStreamState::Running)
{
StopGeneratingAudio();
}
// Signal that the thread that is running the update that we're stopping
if (OutputAudioStreamSourceVoice)
{
OutputAudioStreamSourceVoice->DestroyVoice();
OutputAudioStreamSourceVoice = nullptr;
}
check(AudioStreamInfo.StreamState == EAudioOutputStreamState::Stopped);
}
return true;
}
bool FMixerPlatformXAudio2::CheckAudioDeviceChange()
{
if (bMoveAudioStreamToNewAudioDevice)
{
bMoveAudioStreamToNewAudioDevice = false;
return MoveAudioStreamToNewAudioDevice(NewAudioDeviceId);
}
return false;
}
bool FMixerPlatformXAudio2::MoveAudioStreamToNewAudioDevice(const FString& InNewDeviceId)
{
#if PLATFORM_WINDOWS
UE_LOG(LogTemp, Log, TEXT("Resetting audio stream to device id %s"), *InNewDeviceId);
// Not initialized!
if (!bIsInitialized)
{
return true;
}
// Flag that we're changing audio devices so we stop submitting audio in the callbacks
bAudioDeviceChanging = true;
if (OutputAudioStreamSourceVoice)
{
// Then destroy the current audio stream source voice
OutputAudioStreamSourceVoice->DestroyVoice();
OutputAudioStreamSourceVoice = nullptr;
}
// Don't let the audio stream process while switching to new audio device!
//FScopeLock Lock(&AudioRenderCritSect); XXX - Audio should be stopped then the device switched then audio started again
// Now destroy the mastering voice
if (OutputAudioStreamMasteringVoice)
{
OutputAudioStreamMasteringVoice->DestroyVoice();
OutputAudioStreamMasteringVoice = nullptr;
}
// Stop the engine from generating audio
if (XAudio2System)
{
XAudio2System->StopEngine();
SAFE_RELEASE(XAudio2System);
}
uint32 Flags = 0;
#if WITH_XMA2
// We need to raise this flag explicitly to prevent initializing SHAPE twice, because we are allocating SHAPE in FXMAAudioInfo
Flags |= XAUDIO2_DO_NOT_USE_SHAPE;
#endif
// Create a new xaudio2 system
XAUDIO2_RETURN_ON_FAIL(XAudio2Create(&XAudio2System, Flags, (XAUDIO2_PROCESSOR)FPlatformAffinity::GetAudioThreadMask()));
uint32 NumDevices = 0;
XAUDIO2_RETURN_ON_FAIL(XAudio2System->GetDeviceCount(&NumDevices));
// Now get info on the new audio device we're trying to reset to
uint32 DeviceIndex = 0;
if (!InNewDeviceId.IsEmpty())
{
XAUDIO2_DEVICE_DETAILS DeviceDetails;
for (uint32 i = 0; i < NumDevices; ++i)
{
XAudio2System->GetDeviceDetails(i, &DeviceDetails);
if (DeviceDetails.DeviceID == InNewDeviceId)
{
DeviceIndex = i;
break;
}
}
}
// Update the audio stream info to the new device info
AudioStreamInfo.OutputDeviceIndex = DeviceIndex;
// Get the output device info at this new index
GetOutputDeviceInfo(AudioStreamInfo.OutputDeviceIndex, AudioStreamInfo.DeviceInfo);
// Create a new master voice
XAUDIO2_RETURN_ON_FAIL(XAudio2System->CreateMasteringVoice(&OutputAudioStreamMasteringVoice, AudioStreamInfo.DeviceInfo.NumChannels, AudioStreamInfo.DeviceInfo.SampleRate, 0, AudioStreamInfo.OutputDeviceIndex, nullptr));
// Setup the format of the output source voice
WAVEFORMATEX Format = { 0 };
Format.nChannels = AudioStreamInfo.DeviceInfo.NumChannels;
Format.nSamplesPerSec = OpenStreamParams.SampleRate;
Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
Format.nAvgBytesPerSec = Format.nSamplesPerSec * sizeof(float) * Format.nChannels;
Format.nBlockAlign = sizeof(float) * Format.nChannels;
Format.wBitsPerSample = sizeof(float) * 8;
// Create the output source voice
XAUDIO2_RETURN_ON_FAIL(XAudio2System->CreateSourceVoice(&OutputAudioStreamSourceVoice, &Format, XAUDIO2_VOICE_NOPITCH, 2.0f, &OutputVoiceCallback));
// Start the xaudio2 system back up
XAudio2System->StartEngine();
const int32 NewNumSamples = OpenStreamParams.NumFrames * AudioStreamInfo.DeviceInfo.NumChannels;
// Clear the output buffers with zero's and submit one
for (int32 Index = 0; Index < OutputBuffers.Num(); ++Index)
{
OutputBuffers[Index].Reset(NewNumSamples);
}
bAudioDeviceChanging = false;
#endif // #if PLATFORM_WINDOWS
return true;
}
void FMixerPlatformXAudio2::ResumePlaybackOnNewDevice()
{
if (OutputAudioStreamSourceVoice)
{
CurrentBufferReadIndex = 0;
CurrentBufferWriteIndex = 1;
SubmitBuffer(OutputBuffers[CurrentBufferReadIndex].GetBufferData());
AudioRenderEvent->Trigger();
// Start the voice streaming
OutputAudioStreamSourceVoice->Start();
}
}
void FMixerPlatformXAudio2::SubmitBuffer(const uint8* Buffer)
{
// Create a new xaudio2 buffer submission
XAUDIO2_BUFFER XAudio2Buffer = { 0 };
XAudio2Buffer.AudioBytes = OpenStreamParams.NumFrames * AudioStreamInfo.DeviceInfo.NumChannels * sizeof(float);
XAudio2Buffer.pAudioData = (const BYTE*)Buffer;
XAudio2Buffer.pContext = this;
// Submit buffer to the output streaming voice
OutputAudioStreamSourceVoice->SubmitSourceBuffer(&XAudio2Buffer);
}
FName FMixerPlatformXAudio2::GetRuntimeFormat(USoundWave* InSoundWave)
{
if (InSoundWave->IsStreaming())
{
static FName NAME_OPUS(TEXT("OPUS"));
return NAME_OPUS;
}
#if WITH_XMA2
if (InSoundWave->NumChannels <= 2)
{
static FName NAME_XMA(TEXT("XMA"));
return NAME_XMA;
}
#endif //#if WITH_XMA2
static FName NAME_OGG(TEXT("OGG"));
return NAME_OGG;
}
bool FMixerPlatformXAudio2::HasCompressedAudioInfoClass(USoundWave* InSoundWave)
{
return true;
}
ICompressedAudioInfo* FMixerPlatformXAudio2::CreateCompressedAudioInfo(USoundWave* InSoundWave)
{
check(InSoundWave);
if (InSoundWave->IsStreaming())
{
return new FOpusAudioInfo();
}
static const FName NAME_OGG(TEXT("OGG"));
if (FPlatformProperties::RequiresCookedData() ? InSoundWave->HasCompressedData(NAME_OGG) : (InSoundWave->GetCompressedData(NAME_OGG) != nullptr))
{
return new FVorbisAudioInfo();
}
#if WITH_XMA2
static const FName NAME_XMA(TEXT("XMA"));
if (FPlatformProperties::RequiresCookedData() ? InSoundWave->HasCompressedData(NAME_XMA) : (InSoundWave->GetCompressedData(NAME_XMA) != nullptr))
{
return new FXMAAudioInfo();
}
#endif
return nullptr;
}
FString FMixerPlatformXAudio2::GetDefaultDeviceName()
{
//GConfig->GetString(TEXT("/Script/WindowsTargetPlatform.WindowsTargetSettings"), TEXT("AudioDevice"), WindowsAudioDeviceName, GEngineIni);
return FString();
}
FAudioPlatformSettings FMixerPlatformXAudio2::GetPlatformSettings() const
{
return FAudioPlatformSettings::GetPlatformSettings(TEXT("/Script/WindowsTargetPlatform.WindowsTargetSettings"));
}
} | 31.02963 | 222 | 0.760659 | [
"shape"
] |
523b1f69f8b2e557c100ab0ca50f0415b3bc298a | 536 | hpp | C++ | cpp_src/data_structure/DisjointSetUnion.hpp | satashun/algorithm | ac844a9d3bff9dfa2f755fe92a28e1972cd7bbf4 | [
"MIT"
] | null | null | null | cpp_src/data_structure/DisjointSetUnion.hpp | satashun/algorithm | ac844a9d3bff9dfa2f755fe92a28e1972cd7bbf4 | [
"MIT"
] | 4 | 2020-04-07T16:11:30.000Z | 2021-02-23T23:26:03.000Z | cpp_src/data_structure/DisjointSetUnion.hpp | satashun/algorithm | ac844a9d3bff9dfa2f755fe92a28e1972cd7bbf4 | [
"MIT"
] | null | null | null | class unionfind {
vector<int> par, rank;
public:
void init(int n) {
par.resize(n);
rank.resize(n);
for (int i = 0; i < n; i++) {
par[i] = i;
rank[i] = 0;
}
}
int find(int x) {
if (par[x] == x) return x;
else return par[x] = find(par[x]);
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return false;
if (rank[x] < rank[y]) par[x] = y;
else {
par[y] = x;
if (rank[x] == rank[y]) ++rank[x];
}
return true;
}
bool same(int x, int y) { return (find(x) == find(y)); }
}; | 15.764706 | 57 | 0.498134 | [
"vector"
] |
523ca8106596c03935d4e22338d7b1ce5bfe2f7d | 96,320 | cpp | C++ | Engine/Source/ThirdParty/PhysX/PhysX-3.3/Source/PhysX/src/NpScene.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/ThirdParty/PhysX/PhysX-3.3/Source/PhysX/src/NpScene.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/ThirdParty/PhysX/PhysX-3.3/Source/PhysX/src/NpScene.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxString.h"
#include "PxSimulationEventCallback.h"
#include "NpScene.h"
#include "NpRigidStatic.h"
#include "NpRigidDynamic.h"
#include "NpArticulation.h"
#include "NpArticulationLink.h"
#include "NpArticulationJoint.h"
// PX_AGGREGATE
#include "NpAggregate.h"
//~PX_AGGREGATE
#include "NpVolumeCache.h"
#include "NpBatchQuery.h"
#if PX_USE_PARTICLE_SYSTEM_API
#include "particles/NpParticleSystem.h"
#include "particles/NpParticleFluid.h"
#include "ScbParticleSystem.h"
#endif
#if PX_USE_CLOTH_API
#include "NpCloth.h"
#endif
#if PX_SUPPORT_VISUAL_DEBUGGER
#include "PvdVisualDebugger.h"
#endif
#include "ScbNpDeps.h"
#include "CmCollection.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxGpuDispatcher.h"
#endif
using namespace physx;
#if (USE_GRB_INTEROP == 1)
#include "GrbStackAllocator.h"
#include "GrbSceneEventDescs.h"
using GrbInterop3::StackAllocator;
#endif
// enable thread checks in all debug builds
#if defined(PX_DEBUG) || defined(PX_CHECKED)
#define NP_ENABLE_THREAD_CHECKS 1
#else
#define NP_ENABLE_THREAD_CHECKS 0
#endif
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE bool removeFromSceneCheck(NpScene* npScene, PxScene* scene, const char* name)
{
if (scene == static_cast<PxScene*>(npScene))
{
return true;
}
else
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "%s not assigned to scene or assigned to another scene. Call will be ignored!", name);
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
NpSceneQueries::NpSceneQueries(const PxSceneDesc& desc) :
mScene (desc, Cm::EventProfiler( &NpPhysics::getInstance().getProfileZone(), getPvdId() ) ),
mSceneQueryManager (mScene, desc)
#if PX_SUPPORT_VISUAL_DEBUGGER
, mSingleSqCollector (mScene, false),
mBatchedSqCollector (mScene, true)
#endif
{
}
NpScene::NpScene(const PxSceneDesc& desc) :
NpSceneQueries (desc),
mConstraints (PX_DEBUG_EXP("sceneConstraints")),
mRigidActorArray (PX_DEBUG_EXP("sceneRigidActorArray")),
mArticulations (PX_DEBUG_EXP("sceneArticulations")),
mAggregates (PX_DEBUG_EXP("sceneAggregates")),
#if PX_USE_PARTICLE_SYSTEM_API
mPxParticleBaseArray (PX_DEBUG_EXP("sceneParticles")),
#endif
#if PX_USE_CLOTH_API
mPxClothArray (PX_DEBUG_EXP("sceneCloths")),
#endif
mSanityBounds (desc.sanityBounds),
mPhysicsRunning (false),
mIsBuffering (desc.simulationOrder == PxSimulationOrder::eSOLVE_COLLIDE),
mCollisionRunning (false),
mNbClients (1), //we always have the default client.
mClientBehaviorFlags (PX_DEBUG_EXP("sceneBehaviorFlags")),
mSceneCompletion (mPhysicsDone),
mCollisionCompletion (mCollisionDone),
mSceneExecution (0, "NpScene.execution"),
mSceneCollide (0, "NpScene.collide"),
mSceneSolve (0, "NpScene.solve"),
mControllingSimulation (false),
mSimThreadStackSize (0),
mConcurrentWriteCount (0),
mConcurrentReadCount (0),
mConcurrentErrorCount (0),
mCurrentWriter (0),
mHasSimulated (false)
{
mSceneExecution.setObject(this);
mSceneCollide.setObject(this);
mSceneSolve.setObject(this);
mTaskManager = mScene.getScScene().getTaskManagerPtr();
#if PX_SUPPORT_VISUAL_DEBUGGER
PxProfileZoneManager* pzm = NpPhysics::getInstance().getProfileZoneManager();
if (pzm)
mTaskManager->initializeProfiling(*pzm);
#endif
#if USE_GRB_INTEROP
mGrbEventPools = PX_NEW(GrbInterop3::PoolSet);
#endif
mThreadReadWriteDepth = TlsAlloc();
}
NpSceneQueries::~NpSceneQueries()
{
}
NpScene::~NpScene()
{
#if USE_GRB_INTEROP
PX_DELETE(mGrbEventPools);
#endif
// PT: we need to do that one first, now that we don't release the objects anymore. Otherwise we end up with a sequence like:
// - actor is part of an aggregate, and part of a scene
// - actor gets removed from the scene. This does *not* remove it from the aggregate.
// - aggregate gets removed from the scene, sees that one contained actor ain't in the scene => we get a warning message
while(!mAggregates.empty())
removeAggregate(*mAggregates[0], false);
#if PX_USE_PARTICLE_SYSTEM_API
while(!mPxParticleBaseArray.empty())
removeActor(*mPxParticleBaseArray[0], false);
#endif
#if PX_USE_CLOTH_API
while(!mPxClothArray.empty())
removeActor(*mPxClothArray[0], false);
#endif
while(!mRigidActorArray.empty())
removeActor(*mRigidActorArray[0], false);
while(!mArticulations.empty())
removeArticulation(*mArticulations[0], false);
// release volume caches
Array<NpVolumeCache*> caches; caches.reserve(mVolumeCaches.size());
for(HashSet<NpVolumeCache*>::Iterator iter = mVolumeCaches.getIterator(); !iter.done(); ++iter)
caches.pushBack(*iter);
for(PxU32 i = 0; i < caches.size(); i++)
releaseVolumeCache(caches[i]);
bool unlock = mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK;
#if PX_SUPPORT_VISUAL_DEBUGGER
getSingleSqCollector().release();
getBatchedSqCollector().release();
#endif
// release batch queries
PxU32 numSq = mBatchQueries.size();
while(numSq--)
PX_DELETE(mBatchQueries[numSq]);
mBatchQueries.clear();
mScene.release();
// unlock the lock taken in release(), must unlock before
// mRWLock is destroyed otherwise behavior is undefined
if (unlock)
unlockWrite();
TlsFree(mThreadReadWriteDepth);
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::release()
{
// need to acquire lock for release, note this is unlocked in the destructor
if (mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK)
lockWrite(__FILE__, __LINE__);
// It will be hard to do a write check here since all object release calls in the scene destructor do it and would mess
// up the test. If we really want it on scene destruction as well, we need to either have internal and external release
// calls or come up with a different approach (for example using thread ID as detector variable).
if (isPhysicsRunning() || mIsBuffering)
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::release(): Scene is still being simulated! PxScene::fetchResults() is called implicitly.");
fetchResults(true, NULL);
}
NpPhysics::getInstance().releaseSceneInternal(*this);
}
///////////////////////////////////////////////////////////////////////////////
PxScene* physx::NpGetPxScene(Scb::Scene& scene)
{
char* p = reinterpret_cast<char*>(&scene);
size_t scbOffset = reinterpret_cast<size_t>(&(reinterpret_cast<NpScene*>(0)->getScene()));
return reinterpret_cast<NpScene*>(p - scbOffset);
}
///////////////////////////////////////////////////////////////////////////////
bool NpScene::loadFromDesc(const PxSceneDesc& desc)
{
{
if(desc.limits.maxNbActors)
mRigidActorArray.reserve(desc.limits.maxNbActors);
//const PxU32 totalNbShapes = desc.limits.maxNbStaticShapes + desc.limits.maxNbDynamicShapes;
mScene.getScScene().preAllocate(desc.limits.maxNbActors, desc.limits.maxNbBodies, desc.limits.maxNbStaticShapes, desc.limits.maxNbDynamicShapes, desc.limits.maxNbAggregates);
}
userData = desc.userData;
return true;
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::setGravity(const PxVec3& g)
{
NP_WRITE_CHECK(this);
mScene.setGravity(g);
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneSetGravity, g);
}
PxVec3 NpScene::getGravity() const
{
NP_READ_CHECK(this);
return mScene.getGravity();
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::setBounceThresholdVelocity(const PxReal t)
{
NP_WRITE_CHECK(this);
mScene.setBounceThresholdVelocity(t);
}
PxReal NpScene::getBounceThresholdVelocity() const
{
NP_READ_CHECK(this)
return mScene.getBounceThresholdVelocity();
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::setLimits(const PxSceneLimits& limits)
{
NP_WRITE_CHECK(this);
if(limits.maxNbActors)
mRigidActorArray.reserve(limits.maxNbActors);
mScene.getScScene().preAllocate(limits.maxNbActors, limits.maxNbBodies, limits.maxNbStaticShapes, limits.maxNbDynamicShapes, limits.maxNbAggregates);
mScene.setLimits(limits);
mSceneQueryManager.preallocate(limits.maxNbStaticShapes, limits.maxNbDynamicShapes);
}
//////////////////////////////////////////////////////////////////////////
PxSceneLimits NpScene::getLimits() const
{
NP_READ_CHECK(this);
return mScene.getLimits();
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::setFlag(PxSceneFlag::Enum flag, bool value)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(flag & (PxU16)( PxSceneFlag::eENABLE_CCD|PxSceneFlag::eDISABLE_CCD_RESWEEP|PxSceneFlag::eADAPTIVE_FORCE|
PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS|PxSceneFlag::eENABLE_KINEMATIC_PAIRS|
PxSceneFlag::eREQUIRE_RW_LOCK|PxSceneFlag::eDISABLE_CONTACT_REPORT_BUFFER_RESIZE|
PxSceneFlag::eENABLE_PCM),"NpScene::setFlag: This flag is not mutable - you can only set it once in PxSceneDesc at startup!");
PxSceneFlags currentFlags = mScene.getFlags();
if(value)
currentFlags |= flag;
else
currentFlags &= ~PxSceneFlags(flag);
mScene.setFlags(currentFlags);
}
PxSceneFlags NpScene::getFlags() const
{
NP_READ_CHECK(this);
return mScene.getFlags();
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::addActor(PxActor& actor)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addActor);
NP_WRITE_CHECK(this);
PxRigidStatic* staticActor = actor.is<PxRigidStatic>();
if(staticActor && !static_cast<NpRigidStatic*>(staticActor)->checkConstraintValidity())
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::addActor(): actor has invalid constraint and may not be added to scene");
return;
}
Scb::ControlState::Enum cs = NpActor::getScbFromPxActor(actor).getControlState();
if ((cs == Scb::ControlState::eNOT_IN_SCENE) || ((cs == Scb::ControlState::eREMOVE_PENDING) && (NpActor::getOwnerScene(actor) == this)))
addActorInternal(actor);
else
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::addActor(): Actor already assigned to a scene. Call will be ignored!");
}
void NpScene::addActorInternal(PxActor& actor)
{
switch(actor.getConcreteType())
{
case PxConcreteType::eRIGID_STATIC:
{
NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor);
if(!npStatic.getShapeManager().getNbShapes())
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::addActor(): Static actor with no shapes added to scene");
#ifdef PX_CHECKED
checkPositionSanity(npStatic, npStatic.getGlobalPose(), "PxScene::addActor or PxScene::addAggregate");
#endif
addRigidStatic(npStatic);
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneAddRigidStatic, &npStatic);
}
break;
case PxConcreteType::eRIGID_DYNAMIC:
{
NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor);
#ifdef PX_CHECKED
checkPositionSanity(npDynamic, npDynamic.getGlobalPose(), "PxScene::addActor or PxScene::addAggregate");
#endif
addRigidDynamic(npDynamic);
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneAddRigidDynamic, &npDynamic);
}
break;
#if PX_USE_PARTICLE_SYSTEM_API
case PxConcreteType::ePARTICLE_SYSTEM:
{
NpParticleSystem& npSystem = static_cast<NpParticleSystem&>(actor);
addParticleSystem(npSystem);
}
break;
case PxConcreteType::ePARTICLE_FLUID:
{
NpParticleFluid& npFluid = static_cast<NpParticleFluid&>(actor);
addParticleFluid(npFluid);
}
break;
#endif
#if PX_USE_CLOTH_API
case PxConcreteType::eCLOTH:
{
NpCloth& npCloth = static_cast<NpCloth&>(actor);
addCloth(npCloth);
}
break;
#endif
case PxConcreteType::eARTICULATION_LINK:
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::addActor(): Individual articulation links can not be added to the scene");
}
break;
default:
PX_ASSERT(0);
}
}
void NpScene::updateScbStateAndSetupSq(const PxRigidActor& rigidActor, Scb::Actor& scbActor, NpShapeManager& shapeManager, bool actorDynamic, PxBounds3* bounds)
{
// all the things Scb does in non-buffered insertion
Sq::SceneQueryManager& sqManager = getSceneQueryManagerFast();
scbActor.setScbScene(&getScene());
scbActor.setControlState(Scb::ControlState::eIN_SCENE);
NpShape*const * shapes = shapeManager.getShapes();
PxU32 nbShapes = shapeManager.getNbShapes();
for(PxU32 i=0;i<nbShapes;i++)
{
NpShape& shape = *shapes[i];
const PxShapeFlags& shapeFlags = shape.getFlagsUnbuffered();
shape.incRefCount();
if(shape.NpShape::isExclusive())
{
shape.getScbShape().setScbScene(&getScene());
shape.getScbShape().setControlState(Scb::ControlState::eIN_SCENE);
}
if(shapeFlags & PxShapeFlag::eSCENE_QUERY_SHAPE)
{
Sq::ActorShape* data = sqManager.addShape(*shapes[i], rigidActor, actorDynamic, shapeFlags&(PxShapeFlag::eSIMULATION_SHAPE|PxShapeFlag::eTRIGGER_SHAPE)? bounds+i : NULL);
shapeManager.setSceneQueryData(i, data);
}
}
}
PX_FORCE_INLINE void NpScene::updateScbStateAndSetupSq(const PxRigidActor& rigidActor, Scb::Body& body, NpShapeManager& shapeManager, bool actorDynamic, PxBounds3* bounds)
{
body.initBufferedState();
updateScbStateAndSetupSq(rigidActor, static_cast<Scb::Actor&>(body), shapeManager, actorDynamic, bounds);
}
void NpScene::addActors(PxActor*const* PX_RESTRICT actors, PxU32 nbActors)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addActors);
NP_WRITE_CHECK(this);
if (mPhysicsRunning)
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__,
"PxScene::addActors() not allowed while simulation is running.");
return;
}
Sc::Scene& scScene = mScene.getScScene();
PxU32 actorsDone;
Sc::BatchInsertionState scState;
scScene.startBatchInsertion(scState);
scState.staticActorOffset = ptrdiff_t(size_t(&(reinterpret_cast<NpRigidStatic*>(0)->getScbRigidStaticFast().getScStatic())));
scState.staticShapeTableOffset = ptrdiff_t(size_t(&(reinterpret_cast<NpRigidStatic*>(0)->getShapeManager().getShapeTable())));
scState.dynamicActorOffset = ptrdiff_t(size_t(&(reinterpret_cast<NpRigidDynamic*>(0)->getScbBodyFast().getScBody())));
scState.dynamicShapeTableOffset = ptrdiff_t(size_t(&(reinterpret_cast<NpRigidDynamic*>(0)->getShapeManager().getShapeTable())));
scState.shapeOffset = (ptrdiff_t)NpShapeGetScPtrOffset();
Ps::InlineArray<PxBounds3, 8> shapeBounds;
for(actorsDone=0; actorsDone<nbActors; actorsDone++)
{
if(actorsDone+1<nbActors)
Ps::prefetch(actors[actorsDone+1], sizeof(NpRigidDynamic)); // worst case: PxRigidStatic is smaller
PxType type = actors[actorsDone]->getConcreteType();
Scb::ControlState::Enum cs = NpActor::getScbFromPxActor(*actors[actorsDone]).getControlState();
if (!((cs == Scb::ControlState::eNOT_IN_SCENE) || ((cs == Scb::ControlState::eREMOVE_PENDING) && (NpActor::getOwnerScene(*actors[actorsDone]) == this))))
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::addActors(): Actor already assigned to a scene. Call will be ignored!");
break;
}
if(type == PxConcreteType::eRIGID_STATIC)
{
NpRigidStatic& a = *static_cast<NpRigidStatic*>(actors[actorsDone]);
#ifdef PX_CHECKED
if(!a.checkConstraintValidity())
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::addActors(): actor has invalid constraint and may not be added to scene");
break;
}
checkPositionSanity(a, a.getGlobalPose(), "PxScene::addActors");
#endif
if (!(a.getScbRigidStaticFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION))
{
shapeBounds.resizeUninitialized(a.NpRigidStatic::getNbShapes());
scScene.addStatic(&a, scState, shapeBounds.begin());
updateScbStateAndSetupSq(a, a.getScbActorFast(), a.getShapeManager(), false, shapeBounds.begin());
a.setRigidActorArrayIndex(mRigidActorArray.size());
mRigidActorArray.pushBack(&a);
a.addConstraintsToScene();
}
else
addRigidStatic(a);
}
else if(type == PxConcreteType::eRIGID_DYNAMIC)
{
NpRigidDynamic& a = *static_cast<NpRigidDynamic*>(actors[actorsDone]);
#ifdef PX_CHECKED
checkPositionSanity(a, a.getGlobalPose(), "PxScene::addActors");
#endif
if (!(a.getScbBodyFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION))
{
shapeBounds.resizeUninitialized(a.NpRigidDynamic::getNbShapes());
scScene.addBody(&a, scState, shapeBounds.begin());
updateScbStateAndSetupSq(a, a.getScbBodyFast(), a.getShapeManager(), true, shapeBounds.begin());
a.setRigidActorArrayIndex(mRigidActorArray.size());
mRigidActorArray.pushBack(&a);
a.addConstraintsToScene();
}
else
addRigidDynamic(a);
}
else if(type == PxConcreteType::eCLOTH || type == PxConcreteType::ePARTICLE_SYSTEM || type == PxConcreteType::ePARTICLE_FLUID)
{
addActorInternal(*actors[actorsDone]);
}
else
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::addRigidActors(): articulation link not permitted");
break;
}
}
scScene.finishBatchInsertion(scState);
// if we failed, still complete everything for the successful inserted actors before backing out
#if PX_SUPPORT_VISUAL_DEBUGGER
for(PxU32 i=0;i<actorsDone;i++)
{
if ((actors[i]->getConcreteType()==PxConcreteType::eRIGID_STATIC) && (!(static_cast<NpRigidStatic*>(actors[i])->getScbRigidStaticFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION)))
mScene.addStaticAndShapesToPvd(static_cast<NpRigidStatic*>(actors[i])->getScbRigidStaticFast());
else if ((actors[i]->getConcreteType() == PxConcreteType::eRIGID_DYNAMIC) && (!(static_cast<NpRigidDynamic*>(actors[i])->getScbBodyFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION)))
mScene.addBodyAndShapesToPvd(static_cast<NpRigidDynamic*>(actors[i])->getScbBodyFast());
}
#endif
if(actorsDone<nbActors) // Everything is consistent up to the failure point, so just use removeActor to back out gracefully if necessary
{
for(PxU32 j=0;j<actorsDone;j++)
removeActorInternal(*actors[j], false, true);
return;
}
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneAddRigidActors, actors, nbActors);
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::removeActors(PxActor*const* PX_RESTRICT actors, PxU32 nbActors, bool wakeOnLostTouch)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,removeActors);
NP_WRITE_CHECK(this);
Sc::Scene& scScene = mScene.getScScene();
// resize the bitmap so it does not allocate each remove actor call
scScene.resizeReleasedBodyIDMaps(mRigidActorArray.size(),nbActors);
Sc::BatchRemoveState removeState;
scScene.setBatchRemove(&removeState);
for(PxU32 actorsDone=0; actorsDone<nbActors; actorsDone++)
{
if(actorsDone+1<nbActors)
Ps::prefetch(actors[actorsDone+1], sizeof(NpRigidDynamic)); // worst case: PxRigidStatic is smaller
PxType type = actors[actorsDone]->getConcreteType();
if (!removeFromSceneCheck(this, actors[actorsDone]->getScene(), "PxScene::removeActors(): Actor"))
{
break;
}
removeState.bufferedShapes.clear();
removeState.removedShapes.clear();
if(type == PxConcreteType::eRIGID_STATIC)
{
NpRigidStatic& actor = *static_cast<NpRigidStatic*>(actors[actorsDone]);
const PxActorFlags actorFlags = actor.getActorFlags();
if(actor.getShapeManager().getNbShapes())
Ps::prefetch(actor.getShapeManager().getShapes()[0],sizeof(NpShape));
scScene.prefetchForRemove(actor.getScbRigidStaticFast().getScStatic());
Ps::prefetch(mRigidActorArray[mRigidActorArray.size()-1],sizeof(NpRigidDynamic));
bool noSimBuffered = actorFlags.isSet(PxActorFlag::eDISABLE_SIMULATION);
if (!noSimBuffered)
actor.removeConstraintsFromScene();
actor.getShapeManager().teardownAllSceneQuery(getSceneQueryManagerFast());
Scb::RigidStatic& rs = actor.getScbRigidStaticFast();
mScene.removeRigidStatic(rs, wakeOnLostTouch, rs.isSimDisabledInternally());
removeFromRigidActorList(actor.getRigidActorArrayIndex());
}
else if(type == PxConcreteType::eRIGID_DYNAMIC)
{
NpRigidDynamic& actor = *static_cast<NpRigidDynamic*>(actors[actorsDone]);
const PxActorFlags actorFlags = actor.getActorFlags();
if(actor.getShapeManager().getNbShapes())
Ps::prefetch(actor.getShapeManager().getShapes()[0],sizeof(NpShape));
scScene.prefetchForRemove(actor.getScbBodyFast().getScBody());
Ps::prefetch(mRigidActorArray[mRigidActorArray.size()-1],sizeof(NpRigidDynamic));
bool noSimBuffered = actorFlags.isSet(PxActorFlag::eDISABLE_SIMULATION);
if (!noSimBuffered)
actor.removeConstraintsFromScene();
actor.getShapeManager().teardownAllSceneQuery(getSceneQueryManagerFast());
Scb::Body& b = actor.getScbBodyFast();
mScene.removeRigidBody(b, wakeOnLostTouch, b.isSimDisabledInternally());
removeFromRigidActorList(actor.getRigidActorArrayIndex());
}
else if(type == PxConcreteType::eCLOTH || type == PxConcreteType::ePARTICLE_SYSTEM || type == PxConcreteType::ePARTICLE_FLUID)
{
removeActorInternal(*actors[actorsDone],wakeOnLostTouch, true);
}
else
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::removeActor(): Individual articulation links can not be removed from the scene");
break;
}
}
scScene.setBatchRemove(NULL);
}
void NpScene::removeActor(PxActor& actor, bool wakeOnLostTouch)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,removeActor);
NP_WRITE_CHECK(this);
if (removeFromSceneCheck(this, actor.getScene(), "PxScene::removeActor(): Actor"))
{
removeActorInternal(actor, wakeOnLostTouch, true);
}
}
void NpScene::removeActorInternal(PxActor& actor, bool wakeOnLostTouch, bool removeFromAggregate)
{
switch(actor.getType())
{
case PxActorType::eRIGID_STATIC:
{
NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor);
removeRigidStatic(npStatic, wakeOnLostTouch, removeFromAggregate);
}
break;
case PxActorType::eRIGID_DYNAMIC:
{
NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor);
removeRigidDynamic(npDynamic, wakeOnLostTouch, removeFromAggregate);
}
break;
#if PX_USE_PARTICLE_SYSTEM_API
case PxActorType::ePARTICLE_SYSTEM:
{
NpParticleSystem& npSystem = static_cast<NpParticleSystem&>(actor);
removeParticleSystem(npSystem);
}
break;
case PxActorType::ePARTICLE_FLUID:
{
NpParticleFluid& npFluid = static_cast<NpParticleFluid&>(actor);
removeParticleFluid(npFluid);
}
break;
#endif
#if PX_USE_CLOTH_API
case PxActorType::eCLOTH:
{
NpCloth& npCloth = static_cast<NpCloth&>(actor);
removeCloth(npCloth);
}
break;
#endif
case PxActorType::eARTICULATION_LINK:
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::removeActor(): Individual articulation links can not be removed from the scene");
}
break;
case PxActorType::eACTOR_COUNT:
case PxActorType::eACTOR_FORCE_DWORD:
default:
PX_ASSERT(0);
}
}
///////////////////////////////////////////////////////////////////////////////
// PT: TODO: inline this one in the header for consistency
void NpScene::removeFromRigidActorList(const PxU32& index)
{
PX_ASSERT(index != 0xFFFFFFFF);
PX_ASSERT(index < mRigidActorArray.size());
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneRemoveActor, mRigidActorArray[index]);
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene, API, findAndReplaceWithLast);
PxU32 size = mRigidActorArray.size() - 1;
mRigidActorArray.replaceWithLast(index);
if(size && size != index)
{
PxRigidActor& rigidActor = *mRigidActorArray[index];
switch(rigidActor.getType())
{
case PxActorType::eRIGID_STATIC:
{
NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(rigidActor);
npStatic.setRigidActorArrayIndex(index);
}
break;
case PxActorType::eRIGID_DYNAMIC:
{
NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(rigidActor);
npDynamic.setRigidActorArrayIndex(index); }
break;
#if PX_USE_CLOTH_API
case PxActorType::eCLOTH:
#endif
#if PX_USE_PARTICLE_SYSTEM_API
case PxActorType::ePARTICLE_FLUID:
case PxActorType::ePARTICLE_SYSTEM:
#endif
case PxActorType::eARTICULATION_LINK:
case PxActorType::eACTOR_COUNT:
case PxActorType::eACTOR_FORCE_DWORD:
default:
PX_ASSERT(0);
break;
}
}
}
}
void NpScene::addRigidStatic(NpRigidStatic& actor)
{
bool noSimBuffered = actor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION);
mScene.addRigidStatic(actor.getScbRigidStaticFast(), noSimBuffered);
actor.getShapeManager().setupAllSceneQuery(actor);
if (!noSimBuffered)
actor.addConstraintsToScene();
actor.setRigidActorArrayIndex(mRigidActorArray.size());
mRigidActorArray.pushBack(&actor);
}
void NpScene::removeRigidStatic(NpRigidStatic& actor, bool wakeOnLostTouch, bool removeFromAggregate)
{
PX_ASSERT(NpActor::getAPIScene(actor) == this);
bool noSimBuffered = actor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION);
if(removeFromAggregate && actor.getAggregate())
{
((NpAggregate*)actor.getAggregate())->removeActorAndReinsert(actor, false);
PX_ASSERT(!actor.getAggregate());
}
actor.getShapeManager().teardownAllSceneQuery(getSceneQueryManagerFast());
if (!noSimBuffered)
actor.removeConstraintsFromScene();
Scb::RigidStatic& rs = actor.getScbRigidStaticFast();
mScene.removeRigidStatic(rs, wakeOnLostTouch, rs.isSimDisabledInternally());
removeFromRigidActorList(actor.getRigidActorArrayIndex());
}
void NpScene::addRigidDynamic(NpRigidDynamic& body)
{
bool noSimBuffered = body.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION);
mScene.addRigidBody(body.getScbBodyFast(), noSimBuffered);
body.getShapeManager().setupAllSceneQuery(body);
if (!noSimBuffered)
body.addConstraintsToScene();
body.setRigidActorArrayIndex(mRigidActorArray.size());
mRigidActorArray.pushBack(&body);
}
void NpScene::removeRigidDynamic(NpRigidDynamic& body, bool wakeOnLostTouch, bool removeFromAggregate)
{
PX_ASSERT(NpActor::getAPIScene(body) == this);
bool noSimBuffered = body.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION);
if(removeFromAggregate && body.getAggregate())
{
((NpAggregate*)body.getAggregate())->removeActorAndReinsert(body, false);
PX_ASSERT(!body.getAggregate());
}
body.getShapeManager().teardownAllSceneQuery(getSceneQueryManagerFast());
if (!noSimBuffered)
body.removeConstraintsFromScene();
Scb::Body& b = body.getScbBodyFast();
mScene.removeRigidBody(b, wakeOnLostTouch, b.isSimDisabledInternally());
removeFromRigidActorList(body.getRigidActorArrayIndex());
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::addArticulation(PxArticulation& articulation)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addArticulation);
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(articulation.getNbLinks()>0, "PxScene::addArticulation: empty articulations may not be added to simulation.");
Scb::Articulation& art = static_cast<NpArticulation&>(articulation).getArticulation();
Scb::ControlState::Enum cs = art.getControlState();
if ((cs == Scb::ControlState::eNOT_IN_SCENE) || ((cs == Scb::ControlState::eREMOVE_PENDING) && (art.getScbScene()->getPxScene() == this)))
addArticulationInternal(articulation);
else
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::addArticulation(): Articulation already assigned to a scene. Call will be ignored!");
}
void NpScene::addArticulationInternal(PxArticulation& articulation)
{
NpArticulation& npa = static_cast<NpArticulation&>(articulation);
// Add root link first
PxU32 nbLinks = npa.getNbLinks();
PX_ASSERT(nbLinks > 0);
NpArticulationLink* rootLink = npa.getLinks()[0];
#ifdef PX_CHECKED
checkPositionSanity(*rootLink, rootLink->getGlobalPose(), "PxScene::addArticulation or PxScene::addAggregate");
#endif
if(rootLink->getMass()==0)
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::addArticulation(): Articulation link with zero mass added to scene; defaulting mass to 1");
rootLink->setMass(1.0f);
}
PxVec3 inertia0 = rootLink->getMassSpaceInertiaTensor();
if(inertia0.x == 0.0f || inertia0.y == 0.0f || inertia0.z == 0.0f)
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::addArticulation(): Articulation link with zero moment of inertia added to scene; defaulting inertia to (1,1,1)");
rootLink->setMassSpaceInertiaTensor(PxVec3(1.0f, 1.0f, 1.0f));
}
bool linkTriggersWakeUp = !rootLink->getScbBodyFast().checkSleepReadinessBesidesWakeCounter();
addArticulationLinkBody(*rootLink);
// Add articulation
Scb::Articulation& scbArt = npa.getArticulation();
mScene.addArticulation(scbArt);
addArticulationLinkConstraint(*rootLink);
// Add links & joints
PX_ALLOCA(linkStack, NpArticulationLink*, nbLinks);
linkStack[0] = rootLink;
PxU32 curLink = 0;
PxU32 stackSize = 1;
while(curLink < (nbLinks-1))
{
PX_ASSERT(curLink < stackSize);
NpArticulationLink* l = linkStack[curLink];
NpArticulationLink*const* children = l->getChildren();
for(PxU32 i=0; i < l->getNbChildren(); i++)
{
NpArticulationLink* child = children[i];
#ifdef PX_CHECKED
checkPositionSanity(*rootLink, rootLink->getGlobalPose(), "PxScene::addArticulation");
#endif
if(child->getMass()==0)
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::addArticulation(): Articulation link with zero mass added to scene; defaulting mass to 1");
child->setMass(1.0f);
}
PxVec3 inertia = child->getMassSpaceInertiaTensor();
if(inertia.x == 0.0f || inertia.y == 0.0f || inertia.z == 0.0f)
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::addArticulation(): Articulation link with zero moment of inertia added to scene; defaulting inertia to (1,1,1)");
child->setMassSpaceInertiaTensor(PxVec3(1.0f, 1.0f, 1.0f));
}
linkTriggersWakeUp = linkTriggersWakeUp || (!child->getScbBodyFast().checkSleepReadinessBesidesWakeCounter());
addArticulationLink(*child); // Adds joint too
linkStack[stackSize] = child;
stackSize++;
}
curLink++;
}
if ((scbArt.getWakeCounter() == 0.0f) && linkTriggersWakeUp)
{
// this is for the buffered insert case, where the articulation needs to wake up, if one of the links triggers activation.
npa.wakeUpInternal(true, false);
}
mArticulations.pushBack(&npa);
}
void NpScene::removeArticulation(PxArticulation& articulation, bool wakeOnLostTouch)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,removeArticulation);
NP_WRITE_CHECK(this);
if (removeFromSceneCheck(this, articulation.getScene(), "PxScene::removeArticulation(): Articulation"))
{
removeArticulationInternal(articulation, wakeOnLostTouch, true);
}
}
void NpScene::removeArticulationInternal(PxArticulation& articulation, bool wakeOnLostTouch, bool removeFromAggregate)
{
NpArticulation& npa = static_cast<NpArticulation&>(articulation);
PxU32 nbLinks = npa.getNbLinks();
PX_ASSERT(nbLinks > 0);
if(removeFromAggregate && articulation.getAggregate())
{
((NpAggregate*)articulation.getAggregate())->removeArticulationAndReinsert(articulation, false);
PX_ASSERT(!articulation.getAggregate());
}
//!!!AL
// Inefficient. We might want to introduce a LL method to kill the whole LL articulation together with all joints in one go, then
// the order of removing the links/joints does not matter anymore.
// Remove links & joints
PX_ALLOCA(linkStack, NpArticulationLink*, nbLinks);
linkStack[0] = npa.getLinks()[0];
PxU32 curLink = 0, stackSize = 1;
while(curLink < (nbLinks-1))
{
PX_ASSERT(curLink < stackSize);
NpArticulationLink* l = linkStack[curLink];
NpArticulationLink*const* children = l->getChildren();
for(PxU32 i=0; i < l->getNbChildren(); i++)
{
linkStack[stackSize] = children[i];
stackSize++;
}
curLink++;
}
for(PxI32 j=(PxI32)nbLinks; j-- > 0; )
{
removeArticulationLink(*linkStack[j], wakeOnLostTouch);
}
// Remove articulation
mScene.removeArticulation(npa.getArticulation());
removeFromArticulationList(articulation);
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::addArticulationLinkBody(NpArticulationLink& link)
{
mScene.addRigidBody(link.getScbBodyFast(), false);
link.getShapeManager().setupAllSceneQuery(link);
}
void NpScene::addArticulationLinkConstraint(NpArticulationLink& link)
{
NpArticulationJoint* j = static_cast<NpArticulationJoint*>(link.getInboundJoint());
if (j)
mScene.addArticulationJoint(j->getScbArticulationJoint());
link.addConstraintsToScene();
}
void NpScene::addArticulationLink(NpArticulationLink& link)
{
addArticulationLinkBody(link);
addArticulationLinkConstraint(link);
}
void NpScene::removeArticulationLink(NpArticulationLink& link, bool wakeOnLostTouch)
{
NpArticulationJoint* j = static_cast<NpArticulationJoint*>(link.getInboundJoint());
link.removeConstraintsFromScene();
link.getShapeManager().teardownAllSceneQuery(getSceneQueryManagerFast());
if (j)
mScene.removeArticulationJoint(j->getScbArticulationJoint());
mScene.removeRigidBody(link.getScbBodyFast(), wakeOnLostTouch, false);
}
///////////////////////////////////////////////////////////////////////////////
// PX_AGGREGATE
void NpScene::addAggregate(PxAggregate& aggregate)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addAggregate);
NP_WRITE_CHECK(this);
NpAggregate& np = static_cast<NpAggregate&>(aggregate);
const PxU32 nb = np.getCurrentSizeFast();
#ifdef PX_CHECKED
for(PxU32 i=0;i<nb;i++)
{
PxRigidStatic* a = np.getActorFast(i)->is<PxRigidStatic>();
if(a && !static_cast<NpRigidStatic*>(a)->checkConstraintValidity())
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::addAggregate(): Aggregate contains an actor with an invalid constraint!");
return;
}
}
#endif
Scb::Aggregate& agg = np.getScbAggregate();
Scb::ControlState::Enum cs = agg.getControlState();
if ((cs == Scb::ControlState::eNOT_IN_SCENE) || ((cs == Scb::ControlState::eREMOVE_PENDING) && (agg.getScbScene()->getPxScene() == this)))
{
mScene.addAggregate(agg);
for(PxU32 i=0;i<nb;i++)
{
PX_ASSERT(np.getActorFast(i));
np.addActorInternal(*np.getActorFast(i), *this);
}
mAggregates.pushBack(&aggregate);
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneAddAggregate, &aggregate);
}
else
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::addAggregate(): Aggregate already assigned to a scene. Call will be ignored!");
}
void NpScene::removeAggregate(PxAggregate& aggregate, bool wakeOnLostTouch)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,removeAggregate);
NP_WRITE_CHECK(this);
if(!removeFromSceneCheck(this, aggregate.getScene(), "PxScene::removeAggregate(): Aggregate"))
return;
NpAggregate& np = static_cast<NpAggregate&>(aggregate);
if(np.getScene()!=this)
return;
const PxU32 nb = np.getCurrentSizeFast();
for(PxU32 j=0;j<nb;j++)
{
PxActor* a = np.getActorFast(j);
PX_ASSERT(a);
if (a->getType() != PxActorType::eARTICULATION_LINK)
{
Scb::Actor& scb = NpActor::getScbFromPxActor(*a);
np.getScbAggregate().removeActor(scb, false); // This is only here to make sure the aggregateID gets set to invalid on sync
removeActorInternal(*a, wakeOnLostTouch, false);
}
else if (a->getScene())
{
NpArticulationLink& al = static_cast<NpArticulationLink&>(*a);
NpArticulation& npArt = al.getRoot();
NpArticulationLink* const* links = npArt.getLinks();
for(PxU32 i=0; i < npArt.getNbLinks(); i++)
{
np.getScbAggregate().removeActor(links[i]->getScbActorFast(), false); // This is only here to make sure the aggregateID gets set to invalid on sync
}
removeArticulationInternal(npArt, wakeOnLostTouch, false);
}
}
mScene.removeAggregate(np.getScbAggregate());
removeFromAggregateList(aggregate);
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneRemoveAggregate, &aggregate, 1);
}
PxU32 NpScene::getNbAggregates() const
{
NP_READ_CHECK(this);
return mAggregates.size();
}
PxU32 NpScene::getAggregates(PxAggregate** buffer, PxU32 bufferSize, PxU32 startIndex) const
{
NP_READ_CHECK(this);
const PxU32 size = mAggregates.size();
const PxU32 remainder = (PxU32)PxMax<PxI32>(PxI32(size - startIndex), 0);
const PxU32 writeCount = PxMin(remainder, bufferSize);
for(PxU32 i=0; i<writeCount; i++)
buffer[i] = mAggregates[i+startIndex];
return writeCount;
}
//~PX_AGGREGATE
void NpScene::addCollection(const PxCollection& collection)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addCollection);
const Cm::Collection& col = static_cast<const Cm::Collection&>(collection);
PxU32 nb = col.internalGetNbObjects();
#ifdef PX_CHECKED
for(PxU32 i=0;i<nb;i++)
{
PxRigidStatic* a = col.internalGetObject(i)->is<PxRigidStatic>();
if(a && !static_cast<NpRigidStatic*>(a)->checkConstraintValidity())
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "NpScene::addCollection(): collection contains an actor with an invalid constraint!");
return;
}
}
#endif
struct Local
{
static void addActorIfNeeded(NpScene& scene, PxActor* actor)
{
PxAggregate* aggregate = actor->getAggregate();
if(aggregate)
return; // The actor will be added when the aggregate is added
scene.addActor(*actor);
}
};
for(PxU32 i=0;i<nb;i++)
{
PxBase* s = col.internalGetObject(i);
const PxType serialType = s->getConcreteType();
//NpArticulationLink, NpArticulationJoint are added with the NpArticulation
//Actors and Articulations that are members of an Aggregate are added with the NpAggregate
if(serialType==PxConcreteType::eRIGID_DYNAMIC)
{
NpRigidDynamic* np = static_cast<NpRigidDynamic*>(s);
Local::addActorIfNeeded(*this, np);
}
else if(serialType==PxConcreteType::eRIGID_STATIC)
{
NpRigidStatic* np = static_cast<NpRigidStatic*>(s);
Local::addActorIfNeeded(*this, np);
}
else if(serialType==PxConcreteType::eSHAPE)
{
}
#if PX_USE_CLOTH_API
else if (serialType==PxConcreteType::eCLOTH)
{
NpCloth* np = static_cast<NpCloth*>(s);
Local::addActorIfNeeded(*this, np);
}
#endif
#if PX_USE_PARTICLE_SYSTEM_API
else if(serialType==PxConcreteType::ePARTICLE_SYSTEM)
{
NpParticleSystem* np = static_cast<NpParticleSystem*>(s);
Local::addActorIfNeeded(*this, np);
}
else if(serialType==PxConcreteType::ePARTICLE_FLUID)
{
NpParticleFluid* np = static_cast<NpParticleFluid*>(s);
Local::addActorIfNeeded(*this, np);
}
#endif
else if(serialType==PxConcreteType::eARTICULATION)
{
NpArticulation* np = static_cast<NpArticulation*>(s);
if(!np->getAggregate()) // The actor will be added when the aggregate is added
addArticulation(*np);
}
else if(serialType==PxConcreteType::eAGGREGATE)
{
NpAggregate* np = static_cast<NpAggregate*>(s);
addAggregate(*np);
}
}
}
///////////////////////////////////////////////////////////////////////////////
PxU32 NpScene::getNbActors(PxActorTypeFlags types) const
{
NP_READ_CHECK(this);
PxU32 nbActors = 0;
if (types & PxActorTypeFlag::eRIGID_STATIC)
{
for(PxU32 i=mRigidActorArray.size(); i--;)
{
if (mRigidActorArray[i]->is<PxRigidStatic>())
nbActors++;
}
}
if (types & PxActorTypeFlag::eRIGID_DYNAMIC)
{
for(PxU32 i=mRigidActorArray.size(); i--;)
{
if (mRigidActorArray[i]->is<PxRigidDynamic>())
nbActors++;
}
}
#if PX_USE_PARTICLE_SYSTEM_API
if (types & PxActorTypeFlag::ePARTICLE_SYSTEM)
{
for(PxU32 i=0; i < mPxParticleBaseArray.size(); i++)
{
if (mPxParticleBaseArray[i]->is<PxParticleSystem>())
nbActors++;
}
}
if (types & PxActorTypeFlag::ePARTICLE_FLUID)
{
for(PxU32 i=0; i < mPxParticleBaseArray.size(); i++)
{
if (mPxParticleBaseArray[i]->is<PxParticleFluid>())
nbActors++;
}
}
#endif
#if PX_USE_CLOTH_API
if (types & PxActorTypeFlag::eCLOTH)
{
nbActors += mPxClothArray.size();
}
#endif
return nbActors;
}
PxU32 NpScene::getActors(PxActorTypeFlags types, PxActor** buffer, PxU32 bufferSize, PxU32 startIndex) const
{
NP_READ_CHECK(this);
PxU32 writeCount = 0;
PxU32 virtualIndex = 0; // PT: virtual index of actor, continuous across different actor containers.
if(types & (PxActorTypeFlag::eRIGID_STATIC | PxActorTypeFlag::eRIGID_DYNAMIC))
{
const PxU32 size = mRigidActorArray.size();
for(PxU32 i=0; (i < size) && (writeCount < bufferSize); i++)
{
if ((types & PxActorTypeFlag::eRIGID_STATIC ) && mRigidActorArray[i]->is<PxRigidStatic>())
{
if (virtualIndex >= startIndex)
buffer[writeCount++] = mRigidActorArray[i];
virtualIndex++;
}
else if ((types & PxActorTypeFlag::eRIGID_DYNAMIC) && mRigidActorArray[i]->is<PxRigidDynamic>())
{
if (virtualIndex >= startIndex)
buffer[writeCount++] = mRigidActorArray[i];
virtualIndex++;
}
}
}
#if PX_USE_PARTICLE_SYSTEM_API
if (types & (PxActorTypeFlag::ePARTICLE_SYSTEM | PxActorTypeFlag::ePARTICLE_FLUID))
{
const PxU32 size = mPxParticleBaseArray.size();
for(PxU32 i=0; (i < size) && (writeCount < bufferSize); i++)
{
if ((types & PxActorTypeFlag::ePARTICLE_SYSTEM ) && mPxParticleBaseArray[i]->is<PxParticleSystem>())
{
if (virtualIndex >= startIndex)
buffer[writeCount++] = mPxParticleBaseArray[i];
virtualIndex++;
}
else if ((types & PxActorTypeFlag::ePARTICLE_FLUID) && mPxParticleBaseArray[i]->is<PxParticleFluid>())
{
if (virtualIndex >= startIndex)
buffer[writeCount++] = mPxParticleBaseArray[i];
virtualIndex++;
}
}
}
#endif
#if PX_USE_CLOTH_API
if (types & PxActorTypeFlag::eCLOTH)
{
const PxU32 size = mPxClothArray.size();
for(PxU32 i=0; (i < size) && (writeCount < bufferSize); i++)
{
if(virtualIndex>=startIndex)
buffer[writeCount++] = mPxClothArray[i];
virtualIndex++;
}
}
#endif
return writeCount;
}
///////////////////////////////////////////////////////////////////////////////
const PxActiveTransform* NpScene::getActiveTransforms(PxU32& nbTransformsOut, PxClientID client)
{
NP_READ_CHECK(this);
return mScene.getActiveTransforms(nbTransformsOut, client);
}
///////////////////////////////////////////////////////////////////////////////
PxU32 NpScene::getNbArticulations() const
{
NP_READ_CHECK(this);
return mArticulations.size();
}
PxU32 NpScene::getArticulations(PxArticulation** buffer, PxU32 bufferSize, PxU32 startIndex) const
{
NP_READ_CHECK(this);
const PxU32 size = mArticulations.size();
const PxU32 remainder = (PxU32)PxMax<PxI32>(PxI32(size - startIndex), 0);
const PxU32 writeCount = PxMin(remainder, bufferSize);
for(PxU32 i=0; i<writeCount; i++)
buffer[i] = mArticulations[i+startIndex];
return writeCount;
}
///////////////////////////////////////////////////////////////////////////////
PxU32 NpScene::getNbConstraints() const
{
NP_READ_CHECK(this);
return mConstraints.size();
}
PxU32 NpScene::getConstraints(PxConstraint** buffer, PxU32 bufferSize, PxU32 startIndex) const
{
NP_READ_CHECK(this);
const PxU32 size = mConstraints.size();
const PxU32 remainder = (PxU32)PxMax<PxI32>(PxI32(size - startIndex), 0);
const PxU32 writeCount = PxMin(remainder, bufferSize);
for(PxU32 i=0; i<writeCount; i++)
buffer[i] = mConstraints[i+startIndex];
return writeCount;
}
///////////////////////////////////////////////////////////////////////////////
const PxRenderBuffer& NpScene::getRenderBuffer()
{
if (mPhysicsRunning)
{
// will be reading the Sc::Scene renderable which is getting written
// during the sim, hence, avoid call while simulation is running.
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__,
"PxScene::getRenderBuffer() not allowed while simulation is running.");
}
return mRenderBuffer;
}
void NpScene::visualize()
{
NP_READ_CHECK(this);
mRenderBuffer.clear(); // clear last frame visualizations
#if PX_ENABLE_DEBUG_VISUALIZATION
if(getVisualizationParameter(PxVisualizationParameter::eSCALE) == 0.0f)
return;
Cm::RenderOutput out(mRenderBuffer);
// Visualize scene axis
const PxReal worldAxes = getVisualizationParameter(PxVisualizationParameter::eWORLD_AXES);
if (worldAxes != 0)
out << Cm::DebugBasis(PxVec3(worldAxes));
// Visualize articulations
for(PxU32 i=0;i<mArticulations.size();i++)
static_cast<NpArticulation *>(mArticulations[i])->visualize(out, this);
// Visualize rigid actors and rigid bodies
PxRigidActor** actorIt = mRigidActorArray.begin();
PxRigidActor** actorEnd = mRigidActorArray.end();
#if PX_USE_CLOTH_API
// Visualize cloths
for(PxU32 i=0;i<mPxClothArray.size();i++)
static_cast<NpCloth*>(mPxClothArray[i])->visualize(out, this);
#endif
for(; actorIt != actorEnd; ++actorIt)
{
if ((*actorIt)->getType() == PxActorType::eRIGID_DYNAMIC)
static_cast<NpRigidDynamic*>(*actorIt)->visualize(out, this);
else
static_cast<NpRigidStatic*>(*actorIt)->visualize(out, this);
}
// Visualize pruning structures
const bool visStatic = getVisualizationParameter(PxVisualizationParameter::eCOLLISION_STATIC) != 0.0f;
const bool visDynamic = getVisualizationParameter(PxVisualizationParameter::eCOLLISION_DYNAMIC) != 0.0f;
//flushQueryUpdates(); // DE7834
if(visStatic && mSceneQueryManager.getStaticPruner())
mSceneQueryManager.getStaticPruner()->visualize(out, PxU32(PxDebugColor::eARGB_BLUE));
if(visDynamic && mSceneQueryManager.getDynamicPruner())
mSceneQueryManager.getDynamicPruner()->visualize(out, PxU32(PxDebugColor::eARGB_RED));
if(getVisualizationParameter(PxVisualizationParameter::eMBP_REGIONS) != 0.0f)
{
out << PxTransform(PxIdentity);
const PxU32 nbRegions = mScene.getNbBroadPhaseRegions();
for(PxU32 i=0;i<nbRegions;i++)
{
PxBroadPhaseRegionInfo info;
mScene.getBroadPhaseRegions(&info, 1, i);
if(info.active)
out << PxU32(PxDebugColor::eARGB_YELLOW);
else
out << PxU32(PxDebugColor::eARGB_BLACK);
out << DebugBox(info.region.bounds);
}
}
#endif
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::getSimulationStatistics(PxSimulationStatistics& s) const
{
NP_READ_CHECK(this);
if (!mPhysicsRunning)
{
#if PX_ENABLE_SIM_STATS
mScene.getStats(s);
#endif
}
else
{
//will be reading data that is getting written during the sim, hence, avoid call while simulation is running.
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::getSimulationStatistics() not allowed while simulation is running. Call will be ignored.");
}
}
///////////////////////////////////////////////////////////////////////////////
//Multiclient
PxClientID NpScene::createClient()
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN_NULL(mNbClients < PX_MAX_CLIENTS, "Scene::createClient: Maximum number of clients reached! No new client created.");
mNbClients++; //track this just for error checking
return mScene.createClient();
}
void NpScene::setClientBehaviorFlags(PxClientID client, PxClientBehaviorFlags clientBehaviorFlags)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(client < mNbClients, "Scene::setClientBehaviorFlags: bad clientID! Please create clientIDs with PxScene::createClient().");
mScene.setClientBehaviorFlags(client, clientBehaviorFlags);
}
PxClientBehaviorFlags NpScene::getClientBehaviorFlags(PxClientID client) const
{
NP_READ_CHECK(this);
PX_CHECK_AND_RETURN_VAL(client < mNbClients, "Scene::getClientBehaviorFlags: bad clientID! Please create clientIDs with PxScene::createClient().", PxClientBehaviorFlags());
return mScene.getClientBehaviorFlags(client);
}
///////////////////////////////////////////////////////////////////////////////
//FrictionModel
void NpScene::setFrictionType(PxFrictionType::Enum frictionType)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(!mHasSimulated, "NpScene::setFrictionType: This flag can only be set before calling Simulate() or Solve() or Collide() for the first time");
mScene.setFrictionType(frictionType);
}
PxFrictionType::Enum NpScene::getFrictionType() const
{
NP_READ_CHECK(this);
return mScene.getFrictionType();
}
#if PX_USE_CLOTH_API
///////////////////////////////////////////////////////////////////////////////
//Cloth
void NpScene::setClothInterCollisionDistance(PxF32 distance)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(distance >= 0.0f, "Scene::setClothInterCollisionDistance: distance must be non-negative.");
mScene.setClothInterCollisionDistance(distance);
}
PxF32 NpScene::getClothInterCollisionDistance() const
{
NP_READ_CHECK(this);
return mScene.getClothInterCollisionDistance();
}
void NpScene::setClothInterCollisionStiffness(PxF32 stiffness)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(stiffness >= 0.0f, "Scene::setClothInterCollisionStiffness: stiffness must be non-negative.");
return mScene.setClothInterCollisionStiffness(stiffness);
}
PxF32 NpScene::getClothInterCollisionStiffness() const
{
NP_READ_CHECK(this);
return mScene.getClothInterCollisionStiffness();
}
void NpScene::setClothInterCollisionNbIterations(PxU32 nbIterations)
{
NP_WRITE_CHECK(this);
mScene.setClothInterCollisionNbIterations(nbIterations);
}
PxU32 NpScene::getClothInterCollisionNbIterations() const
{
NP_READ_CHECK(this);
return mScene.getClothInterCollisionNbIterations();
}
#endif
///////////////////////////////////////////////////////////////////////////////
// Callbacks
void NpScene::setSimulationEventCallback(PxSimulationEventCallback* callback, PxClientID client)
{
NP_WRITE_CHECK(this);
mScene.setSimulationEventCallback(callback, client);
}
PxSimulationEventCallback* NpScene::getSimulationEventCallback(PxClientID client) const
{
NP_READ_CHECK(this);
return mScene.getSimulationEventCallback(client);
}
void NpScene::setContactModifyCallback(PxContactModifyCallback* callback)
{
NP_WRITE_CHECK(this);
mScene.setContactModifyCallback(callback);
}
PxContactModifyCallback* NpScene::getContactModifyCallback() const
{
NP_READ_CHECK(this);
return mScene.getContactModifyCallback();
}
void NpScene::setCCDContactModifyCallback(PxCCDContactModifyCallback* callback)
{
NP_WRITE_CHECK(this);
mScene.setCCDContactModifyCallback(callback);
}
PxCCDContactModifyCallback* NpScene::getCCDContactModifyCallback() const
{
NP_READ_CHECK(this);
return mScene.getCCDContactModifyCallback();
}
void NpScene::setBroadPhaseCallback(PxBroadPhaseCallback* callback, PxClientID client)
{
NP_WRITE_CHECK(this);
mScene.setBroadPhaseCallback(callback, client);
}
PxBroadPhaseCallback* NpScene::getBroadPhaseCallback(PxClientID client) const
{
NP_READ_CHECK(this);
return mScene.getBroadPhaseCallback(client);
}
void NpScene::setCCDMaxPasses(PxU32 ccdMaxPasses)
{
NP_WRITE_CHECK(this);
mScene.setCCDMaxPasses(ccdMaxPasses);
}
PxU32 NpScene::getCCDMaxPasses() const
{
NP_READ_CHECK(this);
return mScene.getCCDMaxPasses();
}
PxBroadPhaseType::Enum NpScene::getBroadPhaseType() const
{
NP_READ_CHECK(this);
return mScene.getBroadPhaseType();
}
bool NpScene::getBroadPhaseCaps(PxBroadPhaseCaps& caps) const
{
NP_READ_CHECK(this);
return mScene.getBroadPhaseCaps(caps);
}
PxU32 NpScene::getNbBroadPhaseRegions() const
{
NP_READ_CHECK(this);
return mScene.getNbBroadPhaseRegions();
}
PxU32 NpScene::getBroadPhaseRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex) const
{
NP_READ_CHECK(this);
return mScene.getBroadPhaseRegions(userBuffer, bufferSize, startIndex);
}
PxU32 NpScene::addBroadPhaseRegion(const PxBroadPhaseRegion& region, bool populateRegion)
{
NP_WRITE_CHECK(this);
PX_CHECK_MSG(region.bounds.isValid(), "PxScene::addBroadPhaseRegion(): invalid bounds provided!");
if(region.bounds.isEmpty())
{
Ps::getFoundation().error(PxErrorCode::eINVALID_PARAMETER, __FILE__, __LINE__, "PxScene::addBroadPhaseRegion(): region bounds are empty. Call will be ignored.");
return 0xffffffff;
}
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneAddBroadphaseRegion, ®ion, populateRegion);
return mScene.addBroadPhaseRegion(region, populateRegion);
}
bool NpScene::removeBroadPhaseRegion(PxU32 handle)
{
NP_WRITE_CHECK(this);
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneRemoveBroadphaseRegion, handle);
return mScene.removeBroadPhaseRegion(handle);
}
///////////////////////////////////////////////////////////////////////////////
// Filtering
const void* NpScene::getFilterShaderData() const
{
NP_READ_CHECK(this);
return mScene.getFilterShaderData();
}
PxU32 NpScene::getFilterShaderDataSize() const
{
NP_READ_CHECK(this);
return mScene.getFilterShaderDataSize();
}
PxSimulationFilterShader NpScene::getFilterShader() const
{
NP_READ_CHECK(this);
return mScene.getFilterShader();
}
PxSimulationFilterCallback* NpScene::getFilterCallback() const
{
NP_READ_CHECK(this);
return mScene.getFilterCallback();
}
void NpScene::resetFiltering(PxActor& actor)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(NpActor::getAPIScene(actor) && (NpActor::getAPIScene(actor) == this), "Scene::resetFiltering(): actor not in scene!");
switch(actor.getConcreteType())
{
case PxConcreteType::eRIGID_STATIC:
{
NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor);
npStatic.resetFiltering(npStatic.getScbRigidStaticFast(), NULL, 0);
}
break;
case PxConcreteType::eRIGID_DYNAMIC:
{
NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor);
if (npDynamic.resetFiltering(npDynamic.getScbBodyFast(), NULL, 0))
npDynamic.wakeUpInternal();
}
break;
case PxConcreteType::eARTICULATION_LINK:
{
NpArticulationLink& npLink = static_cast<NpArticulationLink&>(actor);
if (npLink.resetFiltering(npLink.getScbBodyFast(), NULL, 0))
npLink.getRoot().wakeUpInternal(false, true);
}
break;
#if PX_USE_PARTICLE_SYSTEM_API
case PxConcreteType::ePARTICLE_SYSTEM:
{
NpParticleSystem& npSystem = static_cast<NpParticleSystem&>(actor);
npSystem.getScbParticleSystem().resetFiltering();
}
break;
case PxConcreteType::ePARTICLE_FLUID:
{
NpParticleFluid& npFluid = static_cast<NpParticleFluid&>(actor);
npFluid.getScbParticleSystem().resetFiltering();
}
break;
#endif
default:
Ps::getFoundation().error(PxErrorCode::eINVALID_PARAMETER, __FILE__, __LINE__, "Scene::resetFiltering(): only PxParticleBase and PxRigidActor support this operation!");
}
}
void NpScene::resetFiltering(PxRigidActor& actor, PxShape*const* shapes, PxU32 shapeCount)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(NpActor::getAPIScene(actor) && (NpActor::getAPIScene(actor) == this), "Scene::resetFiltering(): actor not in scene!");
switch(actor.getConcreteType())
{
case PxConcreteType::eRIGID_STATIC:
{
NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor);
npStatic.resetFiltering(npStatic.getScbRigidStaticFast(), shapes, shapeCount);
}
break;
case PxConcreteType::eRIGID_DYNAMIC:
{
NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor);
if (npDynamic.resetFiltering(npDynamic.getScbBodyFast(), shapes, shapeCount))
npDynamic.wakeUpInternal();
}
break;
case PxConcreteType::eARTICULATION_LINK:
{
NpArticulationLink& npLink = static_cast<NpArticulationLink&>(actor);
if (npLink.resetFiltering(npLink.getScbBodyFast(), shapes, shapeCount))
npLink.getRoot().wakeUpInternal(false, true);
}
break;
}
}
///////////////////////////////////////////////////////////////////////////////
PxPhysics& NpScene::getPhysics()
{
return NpPhysics::getInstance();
}
void NpScene::updateDirtyShaders()
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,updateDirtyShaders);
// this should continue to be done in the Np layer even after SC has taken over
// all vital simulation functions, because it needs to complete before simulate()
// returns to the application
// However, the implementation needs fixing so that it does work proportional to
// the number of dirty shaders
for(PxU32 i=0;i<mConstraints.size();i++)
{
static_cast<NpConstraint*>(mConstraints[i])->updateConstants();
}
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::simulate(PxReal _elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation)
{
{
CM_PROFILE_START_CROSSTHREAD(mScene.getEventProfiler(), Cm::ProfileEventId::Basic::Getsimulate());
// write guard must end before simulation kicks off worker threads
// otherwise the simulation callbacks could overlap with this function
// and peform API reads,triggering an error
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(_elapsedTime > 0, "Scene::simulate: The elapsed time must be positive!");
PX_CHECK_AND_RETURN(!isPhysicsRunning(), "Scene::simulate: Simulation is still processing last simulate call, you should call fetchResults()!");
PX_CHECK_AND_RETURN((reinterpret_cast<size_t>(scratchBlock)&15) == 0, "Scene::simulate: scratch block must be 16-byte aligned!");
PX_CHECK_AND_RETURN((scratchBlockSize&16383) == 0, "Scene::simulate: scratch block size must be a multiple of 16K");
PX_SIMD_GUARD;
#if PX_SUPPORT_VISUAL_DEBUGGER
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene, Basic, pvdFrameStart);
//This call pauses us if PVD sent a pause command
PxVisualDebugger* theDebugger = NpPhysics::getInstance().getVisualDebugger();
if ( theDebugger != NULL )
theDebugger->checkConnection();
//Flush the pvd commands before the simulate()
mScene.getSceneVisualDebugger().flushPendingCommands();
//signal the frame is starting.
mScene.getSceneVisualDebugger().frameStart(_elapsedTime);
}
#endif
#ifdef PHYSX_STATS
PhysX_Simulate(this, _elapsedTime);
#endif
#if PX_ENABLE_DEBUG_VISUALIZATION
visualize();
#endif
// signal thread
mPhysicsRunning = true;
mIsBuffering = true;
mCollisionRunning = true;
elapsedTime = _elapsedTime;
mHasSimulated = true;
//mScene.setSceneMaterialTableBuffered();
updateDirtyShaders();
#if PX_SUPPORT_VISUAL_DEBUGGER
{
mScene.getSceneVisualDebugger().updateJoints();
}
#endif
NpPhysics& physics = (NpPhysics&)this->getPhysics();
NpMaterialManager& manager = physics.getMaterialManager();
NpMaterial** materials = manager.getMaterials();
mScene.updateLowLevelMaterial(materials);
mScene.preSimulateUpdateAppThread(_elapsedTime);
mScene.setPhysicsRunning(true);
mScene.setPhysicsBuffering(true); // Clear the buffering flag to allow buffered writes to execute immediately. Once collision detection is running, buffering is automatically forced on
mScene.getScScene().setScratchBlock(scratchBlock, scratchBlockSize);
}
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,taskFrameworkSetup);
if (controlSimulation)
{
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,resetDependencies);
// Only reset dependencies, etc if we own the TaskManager. Will be false
// when an NpScene is controlled by an APEX scene.
mTaskManager->resetDependencies();
}
mTaskManager->startSimulation();
}
mControllingSimulation = controlSimulation;
mSceneCompletion.setContinuation(*mTaskManager, completionTask);
mSceneExecution.setContinuation(*mTaskManager, &mSceneCompletion);
#if PX_SUPPORT_GPU_PHYSX
//workaround to prevent premature launching of gpu launch task
if (PxGpuDispatcher* gpuDispatcher = getGpuDispatcher())
{
gpuDispatcher->addPreLaunchDependent(mSceneCompletion);
}
#endif
mSceneCompletion.removeReference();
mSceneExecution.removeReference();
}
}
void NpScene::prepareSolve(PxReal _elapsedTime, void* scratchBlock, PxU32 scratchBlockSize)
{
CM_PROFILE_START_CROSSTHREAD(mScene.getEventProfiler(), Cm::ProfileEventId::Basic::Getsimulate());
// write guard must end before simulation kicks off worker threads
// otherwise the simulation callbacks could overlap with this function
// and peform API reads,triggering an error
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN(_elapsedTime > 0, "Scene::simulate: The elapsed time must be non-negative!");
PX_CHECK_AND_RETURN(!isPhysicsRunning(), "Scene::simulate: Simulation is still processing last simulate call, you should call fetchResults()!");
PX_CHECK_AND_RETURN((reinterpret_cast<size_t>(scratchBlock)&15) == 0, "Scene::simulate: scratch block must be 16-byte aligned!");
PX_CHECK_AND_RETURN((scratchBlockSize&16383) == 0, "Scene::simulate: scratch block size must be a multiple of 16K");
#if PX_SUPPORT_VISUAL_DEBUGGER
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene, Basic, pvdFrameStart);
//This call pauses us if PVD sent a pause command
PxVisualDebugger* theDebugger = NpPhysics::getInstance().getVisualDebugger();
if ( theDebugger != NULL )
theDebugger->checkConnection();
//signal the frame is starting.
mScene.getSceneVisualDebugger().frameStart(_elapsedTime);
}
#endif
#ifdef PHYSX_STATS
PhysX_Simulate(this, _elapsedTime);
#endif
// signal thread
mPhysicsRunning = true;
elapsedTime = _elapsedTime;
#if PX_ENABLE_DEBUG_VISUALIZATION
visualize();
#endif
//mScene.setSceneMaterialTableBuffered();
updateDirtyShaders();
#if PX_SUPPORT_VISUAL_DEBUGGER
{
mScene.getSceneVisualDebugger().updateJoints();
}
#endif
//mScene.preSimulateUpdateAppThread(_elapsedTime);
mScene.setPhysicsRunning(true);
if(!mCollisionRunning)
{
mScene.getScScene().setScratchBlock(scratchBlock, scratchBlockSize);
}
#ifdef SERIALIZE_SCENE_EXECUTION
NpPhysics::getInstance().lockScene();
#endif
}
void NpScene::prepareCollide(PxReal _elapsedTime)
{
NP_WRITE_CHECK(this);
mScene.preSimulateUpdateAppThread(_elapsedTime);
elapsedTime = _elapsedTime;
NpPhysics& physics = (NpPhysics&)this->getPhysics();
NpMaterialManager& manager = physics.getMaterialManager();
NpMaterial** materials = manager.getMaterials();
mScene.getScScene().setElapsedTime(_elapsedTime);
//sync all the material events
mScene.updateLowLevelMaterial(materials);
}
void NpScene::solve(PxReal _elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation)
{
#if !PX_ENABLE_INVERTED_STEPPER_FEATURE
PX_UNUSED(_elapsedTime);
PX_UNUSED(completionTask);
PX_UNUSED(scratchBlock);
PX_UNUSED(scratchBlockSize);
PX_UNUSED(controlSimulation);
Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, "Not implemented in this release!");
return;
#else
//ML:we need to wait for the collision finish before we can solve the contacts
if( !mCollisionRunning || checkCollisionInternal(true) )
{
#ifdef AG_PERFMON
Ps::Foundation::getInstance().getPAUtils().startEvent( gPerfMonSimulate, 0 );
#endif // AG_PERFMON
prepareSolve(_elapsedTime, scratchBlock, scratchBlockSize);
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,taskFrameworkSetup);
//if (controlSimulation)
//{
// // Only reset dependencies, etc if we own the TaskManager. Will be false
// // when an NpScene is controlled by an APEX scene.
// mTaskManager->resetDependencies();
// mTaskManager->startSimulation();
//}
mControllingSimulation = controlSimulation;
mSceneCompletion.setContinuation(*mTaskManager, completionTask);
mSceneSolve.setContinuation(*mTaskManager, &mSceneCompletion);
mSceneCompletion.removeReference();
mSceneSolve.removeReference();
}
#ifdef AG_PERFMON
getFoundation().getPAUtils().stopEvent( gPerfMonSimulate, 0 );
#endif // AG_PERFMON
}
mHasSimulated = true;
#endif
}
void NpScene::collide(PxReal _elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize)
{
#if !PX_ENABLE_INVERTED_STEPPER_FEATURE
PX_UNUSED(_elapsedTime);
PX_UNUSED(completionTask);
PX_UNUSED(scratchBlock);
PX_UNUSED(scratchBlockSize);
Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, "Not implemented in this release!");
return;
#else
mScene.getScScene().setScratchBlock(scratchBlock, scratchBlockSize);
prepareCollide(_elapsedTime);
mIsBuffering = true;
mCollisionRunning = true;
mScene.setPhysicsBuffering(true);
mHasSimulated = true;
if (1)//controlSimulation)
{
// Only reset dependencies, etc if we own the TaskManager. Will be false
// when an NpScene is controlled by an APEX scene.
mTaskManager->resetDependencies();
mTaskManager->startSimulation();
}
mScene.stepSetupCollide();
mCollisionCompletion.setContinuation(*mTaskManager, completionTask);
mSceneCollide.setContinuation(&mCollisionCompletion);
mCollisionCompletion.removeReference();
mSceneCollide.removeReference();
#endif
}
bool NpScene::checkResultsInternal(bool block)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Basic,checkResults);
return mPhysicsDone.wait(block ? Ps::Sync::waitForever : 0);
}
bool NpScene::checkCollisionInternal(bool block)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Basic,checkCollision);
return mCollisionDone.wait(block ? Ps::Sync::waitForever : 0);
}
bool NpScene::checkResults(bool block)
{
return checkResultsInternal(block);
}
bool NpScene::checkCollision(bool block)
{
return checkCollisionInternal(block);
}
struct NpSceneFetchResultsScope
{
Scb::Scene& mScene;
NpSceneFetchResultsScope(Scb::Scene& inScene)
: mScene( inScene )
{
}
~NpSceneFetchResultsScope()
{
#if PX_SUPPORT_VISUAL_DEBUGGER
mScene.getSceneVisualDebugger().frameEnd();
#endif
}
private:
NpSceneFetchResultsScope& operator=(const NpSceneFetchResultsScope&);
};
void NpScene::fireCallBacksPreSync()
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,fireCallBacksPreSync);
// Fire broad-phase callbacks
{
Sc::Scene& scene = mScene.getScScene();
using namespace physx::Sc;
bool outputWarning = scene.fireOutOfBoundsCallbacks();
// Aggregates
{
Ps::Array<void*>& outAgg = scene.getOutOfBoundsAggregates();
const PxU32 nbOut1 = outAgg.size();
for(PxU32 i=0;i<nbOut1;i++)
{
PxAggregate* px = (PxAggregate*)outAgg[i];
NpAggregate* np = static_cast<NpAggregate*>(px);
if(np->getScbAggregate().getControlState()==Scb::ControlState::eREMOVE_PENDING)
continue;
// PT: used to avoid calling the callback twice for the same client
bool flags[PX_MAX_CLIENTS];
PxMemZero(flags, PX_MAX_CLIENTS*sizeof(bool));
PxU32 nbActors = np->getCurrentSizeFast();
for(PxU32 j=0;j<nbActors;j++)
{
PxActor* pxActor = np->getActorFast(j);
const PxClientID clientID = pxActor->getOwnerClient();
if(!flags[clientID])
{
flags[clientID] = true;
PxBroadPhaseCallback* cb = scene.getBroadPhaseCallback(clientID);
if(cb)
{
cb->onObjectOutOfBounds(*px);
}
else
{
outputWarning = true;
}
}
}
}
outAgg.reset();
}
if(outputWarning)
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "At least one object is out of the broadphase bounds. To manage those objects, define a PxBroadPhaseCallback for each used client.");
}
mScene.fireCallBacksPreSync(); // fire all callbacks which need the data in a state which is not synchronized with the latest simulation results
}
//extern PxU32 gContactCache_NbCalls;
//extern PxU32 gContactCache_NbHits;
bool NpScene::fetchResults(bool block, PxU32* errorState)
{
if(!mPhysicsRunning && mCollisionRunning)
{
if(!checkCollisionInternal(block))
return false;
}
PX_SIMD_GUARD;
if (!mPhysicsRunning && !mCollisionRunning && !mIsBuffering)
{
return false;
}
else if (mPhysicsRunning && !checkResultsInternal(block))
{
return false;
}
// take write check *after* simulation has finished, otherwise
// we will block simulation callbacks from using the API
// disallow re-entry to detect callbacks making write calls
NP_WRITE_CHECK_NOREENTRY(this);
//We always need to indicate a frame end and we always need to flush the profile events.
//these things need to happen *after* everything else has happened.
NpSceneFetchResultsScope fetchResultsScope(mScene);
// we use cross thread profile here, to show the event in cross thread view
CM_PROFILE_START_CROSSTHREAD(mScene.getEventProfiler(), Cm::ProfileEventId::Basic::GetfetchResults());
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,fetchResults);
// The order of the following operations is important!
// 1. Process object deletions which were carried out while the simulation was running (since these effect contact and trigger reports)
// 2. Write contact reports to global stream (taking pending deletions into account), clear some simulation buffers (deleted objects etc.), ...
// 3. Send reports which have to be done before the data is synced (contact & trigger reports etc.) such that the user gets the old state.
// 4. Mark the simulation as not running internally to allow reading data which should not be read otherwise
// 5. Synchronize the simulation and user state
// 6. Fire callbacks which need to reflect the synchronized object state
#if PX_SUPPORT_VISUAL_DEBUGGER
mScene.getSceneVisualDebugger().updateContacts();
#endif
mScene.prepareOutOfBoundsCallbacks();
mScene.processPendingRemove();
mScene.endSimulation();
fireCallBacksPreSync(); // fire all callbacks which need the data in a state which is not synchronized with the latest simulation results
mScene.postCallbacksPreSync();
mScene.setPhysicsRunning(false); // This is ok since fetchResults() is blocking, so no user changes will come in at that point
mScene.setPhysicsBuffering(false); // Clear the buffering flag to allow buffered writes to execute immediately. Once collision detection is running, buffering is automatically forced on
mScene.syncEntireScene(errorState); // double buffering
mSceneQueryManager.processSimUpdates();
#if PX_SUPPORT_VISUAL_DEBUGGER
mScene.getSceneVisualDebugger().updateSceneQueries();
getSingleSqCollector().clear();
getBatchedSqCollector().clear();
#endif
// fire sleep and wake-up events
// we do this after buffer-swapping so that the events have the new state
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,fireCallBacksPostSync);
mScene.fireCallBacksPostSync();
}
mScene.postReportsCleanup();
// build the list of active transforms
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,Sim,buildActiveTransforms);
if(mScene.getFlags() & PxSceneFlag::eENABLE_ACTIVETRANSFORMS)
mScene.buildActiveTransforms();
}
mRenderBuffer.append(mScene.getScScene().getRenderBuffer());
if (mPhysicsRunning && mControllingSimulation)
{
mTaskManager->stopSimulation();
}
mPhysicsRunning = false; // allows reading mPhysicsRunning in a threadsafer way
mIsBuffering = false;
mCollisionRunning = false;
mPhysicsDone.reset(); // allow Physics to run again
mCollisionDone.reset();
CM_PROFILE_STOP_CROSSTHREAD(mScene.getEventProfiler(), Cm::ProfileEventId::Basic::GetfetchResults());
CM_PROFILE_STOP_CROSSTHREAD(mScene.getEventProfiler(), Cm::ProfileEventId::Basic::Getsimulate());
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneFetchResults, *mGrbEventPools, *this);
// if(gContactCache_NbCalls)
// printf("%d | %d | %f\n", gContactCache_NbCalls, gContactCache_NbHits, float(gContactCache_NbHits)/float(gContactCache_NbCalls));
// gContactCache_NbCalls = 0;
// gContactCache_NbHits = 0;
return true;
}
void NpScene::flushSimulation(bool sendPendingReports)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,flushSimulation);
NP_WRITE_CHECK(this);
PX_SIMD_GUARD;
if (mPhysicsRunning)
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__,
"Scene::flushSimulation(): This call is not allowed while the simulation is running. Call will be ignored");
return;
}
//!!! TODO: send joint break events?
mScene.flush(sendPendingReports);
//!!! TODO: Shrink all NpObject lists?
}
void NpScene::flushQueryUpdates()
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,flushQueryUpdates);
NP_WRITE_CHECK(this);
PX_SIMD_GUARD;
if (mPhysicsRunning)
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__,
"Scene::flushQueryUpdates(): This call is not allowed while the simulation is running. Call will be ignored");
return;
}
mSceneQueryManager.flushUpdates();
}
/*
Replaces finishRun() with the addition of appropriate thread sync(pulled out of PhysicsThread())
Note: this function can be called from the application thread or the physics thread, depending on the
scene flags.
*/
void NpScene::executeScene(PxBaseTask* continuation)
{
mScene.simulate(elapsedTime, continuation);
}
void NpScene::executeCollide(PxBaseTask* continuation)
{
mScene.collide(elapsedTime, continuation);
}
void NpScene::executeSolve(PxBaseTask* continuation)
{
mScene.solve(elapsedTime, continuation);
}
///////////////////////////////////////////////////////////////////////////////
bool NpScene::addMaterial(NpMaterial& mat)
{
return mScene.addMaterial(mat.getScMaterial());
}
void NpScene::updateMaterial(NpMaterial& mat)
{
//PxU32 index = mat.getTableIndex();
mScene.updateMaterial(mat.getScMaterial());
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneUpdateMaterial, &mat);
}
void NpScene::removeMaterial(NpMaterial& mat)
{
GRB_EVENT(this, GrbInteropEvent3, GrbInteropEvent3::PxSceneRemoveMaterial, &mat, 1);
//PxU32 index = mat.getTableIndex();
mScene.removeMaterial(mat.getScMaterial());
}
///////////////////////////////////////////////////////////////////////////////
void NpScene::setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN((group1 < PX_MAX_DOMINANCE_GROUP && group2 < PX_MAX_DOMINANCE_GROUP),
"Scene::setDominanceGroupPair: invalid params! Groups must be <= 31!");
//can't change matrix diagonal
PX_CHECK_AND_RETURN(group1 != group2, "Scene::setDominanceGroupPair: invalid params! Groups must be unequal! Can't change matrix diagonal!");
PX_CHECK_AND_RETURN(
((dominance.dominance0) == 1.0f && (dominance.dominance1 == 1.0f))
|| ((dominance.dominance0) == 1.0f && (dominance.dominance1 == 0.0f))
|| ((dominance.dominance0) == 0.0f && (dominance.dominance1 == 1.0f))
, "Scene::setDominanceGroupPair: invalid params! dominance must be one of (1,1), (1,0), or (0,1)!");
mScene.setDominanceGroupPair(group1, group2, dominance);
}
PxDominanceGroupPair NpScene::getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const
{
NP_READ_CHECK(this);
PX_CHECK_AND_RETURN_VAL((group1 < PX_MAX_DOMINANCE_GROUP && group2 < PX_MAX_DOMINANCE_GROUP),
"Scene::getDominanceGroupPair: invalid params! Groups must be <= 31!", PxDominanceGroupPair(1.0f, 1.0f));
return mScene.getDominanceGroupPair(group1, group2);
}
///////////////////////////////////////////////////////////////////////////////
#if PX_USE_PARTICLE_SYSTEM_API
void NpScene::addParticleSystem(NpParticleSystem& system)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addParticleSystem);
mScene.addParticleSystem(system.getScbParticleSystem());
mPxParticleBaseArray.pushBack(&system);
updatePhysXIndicator();
}
void NpScene::removeParticleSystem(NpParticleSystem& system)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,removeParticleSystem);
PX_ASSERT(system.getNpScene() == this);
mScene.removeParticleSystem(system.getScbParticleSystem(), false);
removeFromParticleBaseList(system);
updatePhysXIndicator();
}
void NpScene::addParticleFluid(NpParticleFluid& fluid)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addParticleFluid);
mScene.addParticleSystem(fluid.getScbParticleSystem());
mPxParticleBaseArray.pushBack(&fluid);
updatePhysXIndicator();
}
void NpScene::removeParticleFluid(NpParticleFluid& fluid)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,removeParticleFluid);
PX_ASSERT(fluid.getNpScene() == this);
mScene.removeParticleSystem(fluid.getScbParticleSystem(), false);
removeFromParticleBaseList(fluid);
updatePhysXIndicator();
}
// PT: TODO: inline this one in the header for consistency
void NpScene::removeFromParticleBaseList(PxParticleBase& particleBase)
{
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,findAndReplaceWithLast);
bool status = mPxParticleBaseArray.findAndReplaceWithLast(&particleBase);
PX_ASSERT(status);
PX_UNUSED(status);
}
}
#endif // PX_USE_PARTICLE_SYSTEM_API
///////////////////////////////////////////////////////////////////////////////
#if PX_USE_CLOTH_API
void NpScene::addCloth(NpCloth& cloth)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,addCloth);
mScene.addCloth(cloth.getScbCloth());
mPxClothArray.pushBack(&cloth);
updatePhysXIndicator();
}
void NpScene::removeCloth(NpCloth& cloth)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,removeCloth);
PX_ASSERT(NpActor::getAPIScene(cloth) == this);
mScene.removeCloth(cloth.getScbCloth());
removeFromClothList(cloth);
updatePhysXIndicator();
}
#endif // PX_USE_CLOTH_API
///////////////////////////////////////////////////////////////////////////////
#if PX_SUPPORT_GPU_PHYSX
void NpScene::updatePhysXIndicator()
{
Ps::IntBool isGpu = 0;
#if PX_USE_PARTICLE_SYSTEM_API
for (PxU32 i = 0; !isGpu && i < mPxParticleBaseArray.size(); i++)
{
NpParticleSystem* particles = (NpParticleSystem*)mPxParticleBaseArray[i]->is<PxParticleSystem>();
NpParticleFluid* fluid = (NpParticleFluid*)mPxParticleBaseArray[i]->is<PxParticleFluid>();
isGpu |= particles && particles->getScbParticleSystem().getScParticleSystem().isGpu();
isGpu |= fluid && fluid->getScbParticleSystem().getScParticleSystem().isGpu();
}
#endif
#if PX_USE_CLOTH_API
for (PxU32 i = 0; !isGpu && i < mPxClothArray.size(); i++)
{
NpCloth* pCloth = (NpCloth*)mPxClothArray[i]->is<PxCloth>();
isGpu = pCloth->getScbCloth().getScCloth().isGpu();
}
#endif
mPhysXIndicator.setIsGpu(isGpu != 0);
}
#endif //PX_SUPPORT_GPU_PHYSX
///////////////////////////////////////////////////////////////////////////////
PxVolumeCache* NpScene::createVolumeCache(PxU32 maxStaticShapes, PxU32 maxDynamicShapes)
{
NpVolumeCache* cache = PX_NEW(NpVolumeCache)(&mSceneQueryManager, maxStaticShapes, maxDynamicShapes);
mVolumeCaches.insert(cache);
return cache;
}
void NpScene::releaseVolumeCache(NpVolumeCache* volumeCache)
{
bool found = mVolumeCaches.erase(volumeCache); PX_UNUSED(found);
PX_ASSERT_WITH_MESSAGE(found, "volume cache not found in releaseVolumeCache");
PX_DELETE(static_cast<NpVolumeCache*>(volumeCache));
}
void NpScene::setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint)
{
PX_CHECK_AND_RETURN((dynamicTreeRebuildRateHint >= 4), "Scene::setDynamicTreeRebuildRateHint(): Param has to be >= 4!");
mSceneQueryManager.setDynamicTreeRebuildRateHint(dynamicTreeRebuildRateHint);
}
PxU32 NpScene::getDynamicTreeRebuildRateHint() const
{
NP_READ_CHECK(this);
return mSceneQueryManager.getDynamicTreeRebuildRateHint();
}
void NpScene::forceDynamicTreeRebuild(bool rebuildStaticStructure, bool rebuildDynamicStructure)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,forceDynamicTreeRebuild);
NP_WRITE_CHECK(this);
PX_SIMD_GUARD;
mSceneQueryManager.forceDynamicTreeRebuild(rebuildStaticStructure, rebuildDynamicStructure);
}
void NpScene::setSolverBatchSize(PxU32 solverBatchSize)
{
NP_WRITE_CHECK(this);
mScene.setSolverBatchSize(solverBatchSize);
}
PxU32 NpScene::getSolverBatchSize(void) const
{
NP_READ_CHECK(this);
// get from our local copy
return mScene.getSolverBatchSize();
}
///////////////////////////////////////////////////////////////////////////////
bool NpScene::setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value)
{
NP_WRITE_CHECK(this);
PX_CHECK_AND_RETURN_VAL(PxIsFinite(value), "NpScene::setVisualizationParameter: value is not valid.", false);
if (param >= PxVisualizationParameter::eNUM_VALUES)
{
Ps::getFoundation().error(PxErrorCode::eINVALID_PARAMETER, __FILE__, __LINE__, "setVisualizationParameter: parameter out of range.");
return false;
}
else if (value < 0.0f)
{
Ps::getFoundation().error(PxErrorCode::eINVALID_PARAMETER, __FILE__, __LINE__, "setVisualizationParameter: value must be larger or equal to 0.");
return false;
}
else
{
mScene.setVisualizationParameter(param, value);
return true;
}
}
PxReal NpScene::getVisualizationParameter(PxVisualizationParameter::Enum param) const
{
if (param < PxVisualizationParameter::eNUM_VALUES)
return mScene.getVisualizationParameter(param);
else
Ps::getFoundation().error(PxErrorCode::eINVALID_PARAMETER, __FILE__, __LINE__, "getVisualizationParameter: param is not an enum.");
return 0.0f;
}
void NpScene::setVisualizationCullingBox(const PxBounds3& box)
{
NP_WRITE_CHECK(this);
PX_CHECK_MSG(box.isValid(), "PxScene::setVisualizationCullingBox(): invalid bounds provided!");
mScene.setVisualizationCullingBox(box);
}
const PxBounds3& NpScene::getVisualizationCullingBox() const
{
NP_READ_CHECK(this);
const PxBounds3& bounds = mScene.getVisualizationCullingBox();
PX_ASSERT(bounds.isValid());
return bounds;
}
#ifdef PX_PS3
void NpScene::setSceneParamInt(PxPS3ConfigParam::Enum param, PxU32 value)
{
NP_WRITE_CHECK(this);
mScene.setSceneParamInt(param,value);
}
PxU32 NpScene::getSceneParamInt(PxPS3ConfigParam::Enum param)
{
NP_READ_CHECK(this);
return mScene.getSceneParamInt(param);
}
void NpScene::getSpuMemBlockCounters(PxU32& numNpContactStreamBlocks, PxU32& numNpCacheBlocks, PxU32& numDyFrictionBlocks, PxU32& numDyConstraintBlocks)
{
NP_READ_CHECK(this);
return mScene.getScScene().getSpuMemBlockCounters(numNpContactStreamBlocks, numNpCacheBlocks, numDyFrictionBlocks, numDyConstraintBlocks);
}
#endif
void NpScene::setNbContactDataBlocks(PxU32 numBlocks)
{
PX_CHECK_AND_RETURN((mPhysicsRunning == false),
"Scene::setNbContactDataBlock: This call is not allowed while the simulation is running. Call will be ignored!");
mScene.getScScene().setNbContactDataBlocks(numBlocks);
}
PxU32 NpScene::getNbContactDataBlocksUsed() const
{
PX_CHECK_AND_RETURN_VAL((mPhysicsRunning == false),
"Scene::getNbContactDataBlocksUsed: This call is not allowed while the simulation is running. Returning 0.", 0);
return mScene.getScScene().getNbContactDataBlocksUsed();
}
PxU32 NpScene::getMaxNbContactDataBlocksUsed() const
{
PX_CHECK_AND_RETURN_VAL((mPhysicsRunning == false),
"Scene::getMaxNbContactDataBlocksUsed: This call is not allowed while the simulation is running. Returning 0.", 0);
return mScene.getScScene().getMaxNbContactDataBlocksUsed();
}
PxU32 NpScene::getTimestamp() const
{
return mScene.getScScene().getTimeStamp();
}
PxU32 NpScene::getSceneQueryStaticTimestamp() const
{
return mSceneQueryManager.getStaticTimestamp();
}
PxReal NpScene::getMeshContactMargin() const
{
return mScene.getScScene().getMeshContactMargin();
}
PxCpuDispatcher* NpScene::getCpuDispatcher() const
{
return getTaskManager()->getCpuDispatcher();
}
PxGpuDispatcher* NpScene::getGpuDispatcher() const
{
return getTaskManager()->getGpuDispatcher();
}
PxSpuDispatcher* NpScene::getSpuDispatcher() const
{
return getTaskManager()->getSpuDispatcher();
}
PxPruningStructure::Enum NpScene::getStaticStructure() const
{
return mSceneQueryManager.getStaticStructure();
}
PxPruningStructure::Enum NpScene::getDynamicStructure() const
{
return mSceneQueryManager.getDynamicStructure();
}
PxF32 NpScene::getContactCorrelationDistance() const
{
return mScene.getScScene().getContactCorrelationDistance();
}
PxReal NpScene::getFrictionOffsetThreshold() const
{
return mScene.getScScene().getFrictionOffsetThreshold();
}
PxU32 NpScene::getContactReportStreamBufferSize() const
{
return mScene.getScScene().getDefaultContactReportStreamBufferSize();
}
void NpScene::checkPositionSanity(const PxRigidActor& a, const PxTransform& pose, const char* fnName) const
{
if(!mSanityBounds.contains(pose.p))
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__,
"%s: actor pose for %lp is outside sanity bounds\n", fnName, &a);
}
namespace
{
struct ThreadReadWriteCount
{
PxU8 readDepth; // depth of re-entrant reads
PxU8 writeDepth; // depth of re-entrant writes
PxU8 readLockDepth; // depth of read-locks
PxU8 writeLockDepth; // depth of write-locks
};
}
#if NP_ENABLE_THREAD_CHECKS
bool NpScene::startWrite(bool allowReentry)
{
PX_COMPILE_TIME_ASSERT(sizeof(ThreadReadWriteCount) == 4);
if (mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK)
{
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
// ensure we already have the write lock
return localCounts.writeLockDepth > 0;
}
else
{
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
bool error = false;
// check that we are the only thread reading (this allows read->write order on a single thread)
error |= mConcurrentReadCount != localCounts.readDepth;
// check no other threads are writing
error |= mConcurrentWriteCount != localCounts.writeDepth;
// increment shared write counter
Ps::atomicIncrement(&mConcurrentWriteCount);
// in the normal case (re-entry is allowed) then we simply increment
// the writeDepth by 1, otherwise (re-entry is not allowed) increment
// by 2 to force subsequent writes to fail by creating a mismatch between
// the concurrent write counter and the local counter, any value > 1 will do
if (allowReentry)
localCounts.writeDepth++;
else
localCounts.writeDepth+=2;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
if (error)
Ps::atomicIncrement(&mConcurrentErrorCount);
return !error;
}
}
void NpScene::stopWrite(bool allowReentry)
{
if (!(mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK))
{
Ps::atomicDecrement(&mConcurrentWriteCount);
// decrement depth of writes for this thread
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
// see comment in startWrite()
if (allowReentry)
localCounts.writeDepth--;
else
localCounts.writeDepth-=2;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
}
}
bool NpScene::startRead() const
{
if (mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK)
{
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
// ensure we already have the write or read lock
return localCounts.writeLockDepth > 0 || localCounts.readLockDepth > 0;
}
else
{
Ps::atomicIncrement(&mConcurrentReadCount);
// update current threads read depth
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
localCounts.readDepth++;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
// success if the current thread is already performing a write (API re-entry) or no writes are in progress
bool success = (localCounts.writeDepth > 0 || mConcurrentWriteCount == 0);
if (!success)
Ps::atomicIncrement(&mConcurrentErrorCount);
return success;
}
}
void NpScene::stopRead() const
{
if (!(mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK))
{
Ps::atomicDecrement(&mConcurrentReadCount);
// update local threads read depth
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
localCounts.readDepth--;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
}
}
#else
bool NpScene::startWrite(bool) { PX_ASSERT(0); return false; }
void NpScene::stopWrite(bool) {}
bool NpScene::startRead() const { PX_ASSERT(0); return false; }
void NpScene::stopRead() const {}
#endif // NP_ENABLE_THREAD_CHECKS
void NpScene::lockRead(const char* /*file*/, PxU32 /*line*/)
{
// increment this threads read depth
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
localCounts.readLockDepth++;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
// if we are the current writer then do nothing (allow reading from threads with write ownership)
if (mCurrentWriter == Thread::getId())
return;
// only lock on first read
if (localCounts.readLockDepth == 1)
mRWLock.lockReader();
}
void NpScene::unlockRead()
{
// increment this threads read depth
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
if (localCounts.readLockDepth < 1)
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::unlockRead() called without matching call to PxScene::lockRead(), behaviour will be undefined.");
return;
}
localCounts.readLockDepth--;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
// if we are the current writer then do nothing (allow reading from threads with write ownership)
if (mCurrentWriter == Thread::getId())
return;
// only unlock on last read
if (localCounts.readLockDepth == 0)
mRWLock.unlockReader();
}
void NpScene::lockWrite(const char* file, PxU32 line)
{
// increment this threads write depth
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
if (localCounts.writeLockDepth == 0 && localCounts.readLockDepth > 0)
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, file?file:__FILE__, file?int(line):__LINE__, "PxScene::lockWrite() detected after a PxScene::lockRead(), lock upgrading is not supported, behaviour will be undefined.");
return;
}
localCounts.writeLockDepth++;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
// only lock on first call
if (localCounts.writeLockDepth == 1)
mRWLock.lockWriter();
PX_ASSERT(mCurrentWriter == 0 || mCurrentWriter == Thread::getId());
// set ourselves as the current writer
mCurrentWriter = Thread::getId();
}
void NpScene::unlockWrite()
{
// increment this thread's write depth
ThreadReadWriteCount localCounts = PxUnionCast<ThreadReadWriteCount>(TlsGet(mThreadReadWriteDepth));
if (localCounts.writeLockDepth < 1)
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxScene::unlockWrite() called without matching call to PxScene::lockWrite(), behaviour will be undefined.");
return;
}
localCounts.writeLockDepth--;
TlsSet(mThreadReadWriteDepth, PxUnionCast<void*>(localCounts));
PX_ASSERT(mCurrentWriter == Thread::getId());
if (localCounts.writeLockDepth == 0)
{
mCurrentWriter = 0;
mRWLock.unlockWriter();
}
}
PxReal NpScene::getWakeCounterResetValue() const
{
NP_READ_CHECK(this);
return getWakeCounterResetValueInteral();
}
static PX_FORCE_INLINE void shiftRigidActor(PxRigidActor* a, const PxVec3& shift)
{
PxActorType::Enum t = a->getType();
if (t == PxActorType::eRIGID_DYNAMIC)
{
NpRigidDynamic* rd = static_cast<NpRigidDynamic*>(a);
rd->getScbBodyFast().onOriginShift(shift);
}
else if (t == PxActorType::eRIGID_STATIC)
{
NpRigidStatic* rs = static_cast<NpRigidStatic*>(a);
rs->getScbRigidStaticFast().onOriginShift(shift);
}
else
{
PX_ASSERT(t == PxActorType::eARTICULATION_LINK);
NpArticulationLink* al = static_cast<NpArticulationLink*>(a);
al->getScbBodyFast().onOriginShift(shift);
}
}
void NpScene::shiftOrigin(const PxVec3& shift)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,shiftOrigin);
NP_WRITE_CHECK(this);
if(mScene.isPhysicsBuffering())
{
Ps::getFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxScene::shiftOrigin() not allowed while simulation is running. Call will be ignored.");
return;
}
PX_SIMD_GUARD;
const PxU32 prefetchLookAhead = 4;
PxU32 rigidCount = mRigidActorArray.size();
PxU32 batchIterCount = rigidCount / prefetchLookAhead;
PxU32 idx = 0;
for(PxU32 i=0; i < batchIterCount; i++)
{
// prefetch elements for next batch
if (i < (batchIterCount-1))
{
Ps::prefetchLine(mRigidActorArray[idx + prefetchLookAhead]);
Ps::prefetchLine(((PxU8*)mRigidActorArray[idx + prefetchLookAhead]) + 128); // for the buffered pose
Ps::prefetchLine(mRigidActorArray[idx + prefetchLookAhead + 1]);
Ps::prefetchLine(((PxU8*)mRigidActorArray[idx + prefetchLookAhead + 1]) + 128);
Ps::prefetchLine(mRigidActorArray[idx + prefetchLookAhead + 2]);
Ps::prefetchLine(((PxU8*)mRigidActorArray[idx + prefetchLookAhead + 2]) + 128);
Ps::prefetchLine(mRigidActorArray[idx + prefetchLookAhead + 3]);
Ps::prefetchLine(((PxU8*)mRigidActorArray[idx + prefetchLookAhead + 3]) + 128);
}
else
{
for(PxU32 k=(idx + prefetchLookAhead); k < rigidCount; k++)
{
Ps::prefetchLine(mRigidActorArray[k]);
Ps::prefetchLine(((PxU8*)mRigidActorArray[k]) + 128);
}
}
for(PxU32 j=idx; j < (idx + prefetchLookAhead); j++)
{
shiftRigidActor(mRigidActorArray[j], shift);
}
idx += prefetchLookAhead;
}
// process remaining objects
for(PxU32 i=idx; i < rigidCount; i++)
{
shiftRigidActor(mRigidActorArray[i], shift);
}
for(PxU32 i=0; i < mArticulations.size(); i++)
{
NpArticulation* np = static_cast<NpArticulation*>(mArticulations[i]);
NpArticulationLink*const* links = np->getLinks();
for(PxU32 j=0; j < np->getNbLinks(); j++)
{
shiftRigidActor(links[j], shift);
}
}
mScene.shiftOrigin(shift);
//
// shift scene query related data structures
//
mSceneQueryManager.shiftOrigin(shift);
Ps::HashSet<NpVolumeCache*>::Iterator it = mVolumeCaches.getIterator();
while (!it.done())
{
NpVolumeCache* cache = (*it);
cache->onOriginShift(shift);
++it;
}
#if PX_ENABLE_DEBUG_VISUALIZATION
//
// debug visualization
//
mRenderBuffer.shift(-shift);
#endif
}
///////////////////////////////////////////////////////////////////////////////
#if (USE_GRB_INTEROP == 1)
#include "NpScene.h"
#include "GrbEventStream.h"
GrbInteropEventStream3 * NpScene::createSceneEventStream()
{
Array<GrbInteropEvent3> * eventStream = &mGrbEventStreams.insert();
new (eventStream) Array<GrbInteropEvent3>;
mGrbEventStreamAllocs.pushBack(new StackAllocator(mGrbEventStreamStackAllocatorPageSize));
GrbInteropEventStream3 * retval = new GrbInteropEventStream3(this, eventStream);
return retval;
}
void NpScene::releaseSceneEventStream(GrbInteropEventStream3 * sceneEventStream)
{
PxU32 index = PxU32(sceneEventStream->getEventStream() - &mGrbEventStreams[0]);
mGrbEventStreams.replaceWithLast(index);
delete mGrbEventStreamAllocs[index];
mGrbEventStreamAllocs.replaceWithLast(index);
}
PxU32 NpScene::getNumEventStreams()
{
return mGrbEventStreams.size();
}
void NpScene::eventStreamSend(const GrbInteropEvent3 & sceneEvent, PxU32 stream)
{
mGrbEventStreams[stream].pushBack(sceneEvent);
}
StackAllocator & NpScene::getEventStreamStackAlloc(PxU32 eventStream)
{
return *(mGrbEventStreamAllocs[eventStream]);
}
void NpScene::clearEventStream(Array<GrbInteropEvent3> * eventStream)
{
int index = (int)(eventStream - &mGrbEventStreams[0]);
for(PxU32 i=0;i!=eventStream->size();i++)
{
//Free any memory allocated by the event
(*eventStream)[i].release();
}
eventStream->clear();
mGrbEventStreamAllocs[(PxU32)index]->reset(); //reset the stack
}
#endif
///////////////////////////////////////////////////////////////////////////////
PxBatchQuery* NpScene::createBatchQuery(const PxBatchQueryDesc& desc)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,createBatchQuery);
PX_CHECK_AND_RETURN_NULL(desc.isValid(),"Supplied PxBatchQueryDesc is not valid. createBatchQuery returns NULL.");
NpBatchQuery* bq = PX_NEW(NpBatchQuery)(*this, desc);
mBatchQueries.pushBack(bq);
return bq;
}
void NpScene::releaseBatchQuery(PxBatchQuery* sq)
{
CM_PROFILE_ZONE_WITH_SUBSYSTEM(mScene,API,releaseBatchQuery);
NpBatchQuery* npsq = static_cast<NpBatchQuery*>(sq);
bool found = mBatchQueries.findAndReplaceWithLast(npsq);
PX_UNUSED(found); PX_ASSERT(found);
PX_DELETE_AND_RESET(npsq);
}
| 30.452102 | 230 | 0.73615 | [
"object",
"shape"
] |
524f6b1937b11fc3c8a03bf4578957c93aca6afb | 8,830 | cpp | C++ | core/sql/optimizer/PartKeyDist.cpp | anoopsharma00/incubator-trafodion | b109e2cf5883f8e763af853ab6fad7ce7110d9e8 | [
"Apache-2.0"
] | null | null | null | core/sql/optimizer/PartKeyDist.cpp | anoopsharma00/incubator-trafodion | b109e2cf5883f8e763af853ab6fad7ce7110d9e8 | [
"Apache-2.0"
] | null | null | null | core/sql/optimizer/PartKeyDist.cpp | anoopsharma00/incubator-trafodion | b109e2cf5883f8e763af853ab6fad7ce7110d9e8 | [
"Apache-2.0"
] | null | null | null | /**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
****************************************************************************
*
* File: PartKeyDist.h
* Description:
*
* Created: 8/5/1998
* Language: C++
*
*
**************************************************************************** */
#include "PartKeyDist.h"
#include "hs_const.h" /* HS_MAX_BOUNDARY_LEN */
#include "parser.h" /* for the parser of EncodedValues */
// -----------------------------------------------------------------------
// methods on PartitionKeyDistribution class -- just ctors for now
// -----------------------------------------------------------------------
PartitionKeyDistribution::PartitionKeyDistribution ()
: partitionBoundaries_ (HistogramSharedPtr(0), HISTHEAP), /* init to invalid value */
partitionFactors_ (HISTHEAP, 0), /* init to invalid value */
partitionKeyId_ (NULL_VALUE_ID), /* init to invalid value */
objectInfoIsValid_ (FALSE) /* init to invalid value */
{}
PartitionKeyDistribution::PartitionKeyDistribution (
const RangePartitioningFunction & partFunc,
const ColStatDescList & inputHistograms)
: partitionBoundaries_ (HistogramSharedPtr(0), HISTHEAP), /* init to invalid value */
partitionFactors_ (HISTHEAP, 0), /* init to invalid value */
partitionKeyId_ (NULL_VALUE_ID), /* init to invalid value */
objectInfoIsValid_ (FALSE) /* init to invalid value */
{
// -----------------------------------------------------------------------
// Get the partition boundaries:
// -----------------------------------------------------------------------
NAList<EncodedValueList *> boundaries(CmpCommon::statementHeap());
const RangePartitionBoundaries *rpBoundariesPtr = partFunc.getRangePartitionBoundaries();
// There are n+1 partition boundaries for n partitions:
const CollIndex numPartBounds = CollIndex(partFunc.getCountOfPartitions()+1);
for (CollIndex i=0; i < numPartBounds; i++)
{
EncodedValueList *evl = new (CmpCommon::statementHeap())
EncodedValueList(CmpCommon::statementHeap(), 0);
boundaries.insertAt(i, evl);
#pragma nowarn(1506) // warning elimination
const ItemExprList *boundary = rpBoundariesPtr->getBoundaryValues(i);
#pragma warn(1506) // warning elimination
// transform to encoded value list
for (CollIndex j=0; j < boundary->entries(); j++)
{
EncodedValue ev((*boundary)[j], FALSE /* "negate" */);
(boundaries[i])->insertAt(j,ev);
}
}
const ValueIdList listOfPartitionKeys = partFunc.getKeyColumnList();
const ValueIdList listOfPartitionKeyOrders = partFunc.getOrderOfKeyValues() ;
// CSDL::divideHistogramAtPartitionBoundaries() returns FALSE if, for
// some reason, the histogram-to-partition-boundary-list mapping fails
//
// if it returns TRUE, then we know that the PartitionKeyDistribution
// data members partitionBoundaries_ and partitionKeyId_ have been
// set to valid values.
if ( inputHistograms.divideHistogramAtPartitionBoundaries (
listOfPartitionKeys, /* in */
listOfPartitionKeyOrders, /* in */
boundaries, /* in */
partitionKeyId_, /* out */
isPartitionKeyAscending_, /* out */
partitionBoundaries_, /* out */
partitionFactors_ /* out */ ) == TRUE )
{
objectInfoIsValid_ = TRUE ;
}
} // PartitionKeyDistribution::PartitionKeyDistribution
CollIndex
PartitionKeyDistribution::getHistIdxFromPartIdx (CollIndex extIdx) const
{
// Since our "internal" representation of the partition boundaries
// doesn't (necessarily) share the same numbering scheme as the
// "external" world's view of the partition boundaries, we need to
// be able to convert from the "external" to "internal" view.
//
// Note that there is a n-to-1 mapping between the "external" partitions
// and the "internal" histogram intervals. Thus, we can convert exactly
// from "external" to "internal", but not the other way (a *range* of
// partitions could be returned, if this functionality is required
// ... but I don't think it is).
//
// Note also that if the partitioning key is in DESCENDING order (a
// value of FALSE stored in isPartitionKeyAscending_), then we need
// to provide the "inverse" hist idx. See PartKeyDist.h for a careful
// description of what's going on.
#pragma nowarn(270) // warning elimination
DCMPASSERT(extIdx >= 0 AND extIdx < getNumPartitions());
#pragma warn(270) // warning elimination
CollIndex countParts, interval ;
if ( isPartitionKeyAscending_ == FALSE )
{
CollIndex numParts = getNumPartitions() ;
// now "flip-flop", since we reversed the boundaries, so we have to
// "reverse" everything we do when talking about them
extIdx = numParts - extIdx - 1;
}
extIdx += 1 ; // we're zero-based when talking about Partition#
countParts = 0 ;
for ( interval = 1 ; interval < partitionFactors_.entries() ; interval++ )
{
countParts += partitionFactors_[interval] ;
if ( countParts >= extIdx )
break ;
}
DCMPASSERT ( countParts >= extIdx ) ; // if not, the index was bad! (or logic wrong!!!)
// "interval" contains the HistInt index corresponding to the partition
// requested; OR, it contains the HistInt corresponding to a number of
// partitions, one of which is the one that was requested.
return interval ;
}
CostScalar
PartitionKeyDistribution::getRowsForPartition(CollIndex extIdx) const
{
// The first entry in the histogram will never contain rows because
// it corresponds to a "partition" for all rows below "MIN".
// No rows satisfy this. Thus, the first partition is described
// by the first interval.
#pragma nowarn(270) // warning elimination
DCMPASSERT(extIdx >= 0 AND extIdx < getNumPartitions());
#pragma warn(270) // warning elimination
// remember : each entry in the histogram represents potentially many
// different partition boundaries, each with the same partition boundary value.
CollIndex interval = getHistIdxFromPartIdx (extIdx) ;
// If there is more than one partition represented by this histogram
// interval, then we assume that all of the rows in this histogram
// interval are uniformly distributed between all of them.
return (*Hist())[interval].getCardinality() / partitionFactors_[interval] ;
}
CostScalar
PartitionKeyDistribution::getUecForPartition (CollIndex extIdx) const
{
// remember : each entry in the histogram represents potentially many
// different partition boundaries, each with the same partition boundary value.
CollIndex interval = getHistIdxFromPartIdx (extIdx) ;
// If there is more than one partition represented by this histogram
// interval, then we assume that all of the uec in this histogram
// interval are uniformly distributed between all of them.
return (*Hist())[interval].getUec() / partitionFactors_[interval];
}
CollIndex
PartitionKeyDistribution::getNumPartitions () const
{
// remember : each entry in the histogram represents potentially many
// different partition boundaries, each with the same partition boundary value.
CollIndex numParts = 0 ;
// don't count that first HistInt's counter
for ( CollIndex i = 1 ; i < partitionFactors_.entries() ; i++ )
numParts += partitionFactors_[i] ;
// CollIndex numParts = Hist()->entries() - 1;
return numParts;
}
CollIndex
PartitionKeyDistribution::getMaxPartitionFactor() const
{
CollIndex max = 0;
for ( CollIndex i = 1 ; i < partitionFactors_.entries() ; i++ )
{
if (partitionFactors_[i] > max)
max = partitionFactors_[i];
}
return max;
}
// eof
| 38.72807 | 91 | 0.647339 | [
"transform"
] |
525122afd39e68f905b81e5418937281a0e3c6ad | 8,014 | hpp | C++ | framework/areg/base/private/posix/WaitableMutexIX.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 70 | 2021-07-20T11:26:16.000Z | 2022-03-27T11:17:43.000Z | framework/areg/base/private/posix/WaitableMutexIX.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 32 | 2021-07-31T05:20:44.000Z | 2022-03-20T10:11:52.000Z | framework/areg/base/private/posix/WaitableMutexIX.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 40 | 2021-11-02T09:45:38.000Z | 2022-03-27T11:17:46.000Z | #pragma once
/************************************************************************
* This file is part of the AREG SDK core engine.
* AREG SDK is dual-licensed under Free open source (Apache version 2.0
* License) and Commercial (with various pricing models) licenses, depending
* on the nature of the project (commercial, research, academic or free).
* You should have received a copy of the AREG SDK license description in LICENSE.txt.
* If not, please contact to info[at]aregtech.com
*
* \copyright (c) 2017-2021 Aregtech UG. All rights reserved.
* \file areg/base/private/posix/WaitableMutexIX.hpp
* \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit
* \author Artak Avetyan
* \brief AREG Platform, POSIX Waitable Event class.
*
************************************************************************/
/************************************************************************
* Includes
************************************************************************/
#include "areg/base/GEGlobal.h"
#if defined(_POSIX) || defined(POSIX)
#include "areg/base/private/posix/IEWaitableBaseIX.hpp"
//////////////////////////////////////////////////////////////////////////
// WaitableMutexIX class declaration.
//////////////////////////////////////////////////////////////////////////
/**
* \brief The synchronization waitable Mutex object is used to synchronize data access
* between multiple threads. If a Mutex is owned by a thread any attempts
* of other threads to take Mutex ownership will be automatically blocked and
* the threads will be stopped until Mutex is not released or the waiting timeout
* is not expired. There can be only one thread at a time owning waitable Mutex
* and only owning thread can release the waitable Mutex to put to signaled
* state. The released state of Mute is considered as signaled and the thread
* owning state is non-signaled if it has mutex owning thread.
**/
class WaitableMutexIX : public IEWaitableBaseIX
{
//////////////////////////////////////////////////////////////////////////
// Constructor / Destructor.
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Initializes the synchronization waitable Mutex object, sets the Mutex owned flag.
* \param initOwned If true, the Mutex is created non-signaled and owned by the
* current thread. The waitable Mutex gets ownership by calling one of
* wait methods defined in SynchLockAndWaitIX. Once the thread gets
* ownership, any further waiting functions calls of the same thread
* will not be blocked and stopped, so that the waiting Mutex can be
* waited recursive. Any other thread that tries to get the ownership
* of the waitable Mutex will be automatically locked and stopped by
* the system. Once Mutex ownership is taken, it is in non-signaled state.
* Only Mutex owning thread can unblock and release waitable Mutex.
* The requests of other threads to release (signal) waitable Mutex
* is ignored by the system.
* \param asciiName The name of synchronization Event.
**/
explicit WaitableMutexIX(bool initOwned = false, const char * asciiName = nullptr);
/**
* \brief Destructor.
**/
virtual ~WaitableMutexIX( void ) = default;
//////////////////////////////////////////////////////////////////////////
// Attributes and operations.
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Call to release waitable Mutex and set to signaled state. Only owning thread
* can release waitable Mutex. The call from any other threads is ignored.
* When Mutex is signaled, the first released thread gets waitable Mutex ownership
* and immediately set to non-signaled state, so that no other thread can be
* released until mutex is not signaled again. Only released thread (owning thread)
* can release Mutex to set to signaled state again. This call is ignored if the
* waitable Mutex is already in signaled state or method is from not owning
* thread context.
* \return Returns true if operation succeeded.
**/
bool releaseMutex( void );
/**
* \brief Returns waitable mutex owner thread ID, if there is any.
**/
inline pthread_t getOwningThreadId( void ) const;
/************************************************************************/
// IEWaitableBaseIX callback overrides.
/************************************************************************/
/**
* \brief Returns true if the object is signaled. Otherwise, returns false.
* \param contextThread The ID of thread where locking happened.
* The mutex is signaled if owner thread is nullptr or the thread context
* and owner threads are same.
**/
virtual bool checkSignaled( pthread_t contextThread ) const override;
/**
* \brief This callback is triggered when a waiting thread is released to continue to run.
* Waitable Event always return true.
* \param ownerThread Indicates the POSIX thread ID that completed to wait.
* \return Returns true if waitable Mutex did not have owner thread and successfully set
* new owner thread. Only signaled waitable Mutex can assign thread ownership.
* Returns false, if waitable Mutex already has ownership and cannot take new.
**/
virtual bool notifyRequestOwnership( pthread_t ownerThread ) override;
/**
* \brief This callback is triggered to when a system needs to know whether waitable
* can signal multiple threads. Returned 'true' value indicates that there can be
* multiple threads can get waitable signaled state. For example, waitable Mutex
* signals only one thread, when waitable Event can signal multiple threads.
* \return Waitable Mutex always returns false.
**/
virtual bool checkCanSignalMultipleThreads( void ) const override;
/**
* \brief This callback is called to notify the object the amount of
* threads that were leased when the object is in signaled state.
* The number of threads for waitable Mutex are 1 or 0.
* \param numThreads The number of threads that where released when the
* object is in signaled state. 0 means that no thread
* was released by the object.
**/
virtual void notifyReleasedThreads( int numThreads ) override;
//////////////////////////////////////////////////////////////////////////
// Member variables.
//////////////////////////////////////////////////////////////////////////
private:
/**
* \brief The owner thread. The waitable Mutex is released thread ID is invalid.
**/
pthread_t mOwnerThread;
/**
* \brief The number of locks recursively called.
**/
int mLockCount;
//////////////////////////////////////////////////////////////////////////
// Forbidden calls.
//////////////////////////////////////////////////////////////////////////
private:
DECLARE_NOCOPY_NOMOVE( WaitableMutexIX );
};
//////////////////////////////////////////////////////////////////////////
// WaitableMutexIX class inline functions
//////////////////////////////////////////////////////////////////////////
inline pthread_t WaitableMutexIX::getOwningThreadId(void) const
{
ObjectLockIX lock(*this);
return mOwnerThread;
}
#endif // defined(_POSIX) || defined(POSIX)
| 48.865854 | 102 | 0.548041 | [
"object"
] |
5264cb771238a0061a5ad16c40f3a125dd0593e2 | 1,763 | cpp | C++ | Src/Entity/Enemy/Clyde.cpp | Pungyy/PacMan-Game | 957f930f7f8cd85fcba96c95cad394e2f30b38e4 | [
"MIT"
] | null | null | null | Src/Entity/Enemy/Clyde.cpp | Pungyy/PacMan-Game | 957f930f7f8cd85fcba96c95cad394e2f30b38e4 | [
"MIT"
] | null | null | null | Src/Entity/Enemy/Clyde.cpp | Pungyy/PacMan-Game | 957f930f7f8cd85fcba96c95cad394e2f30b38e4 | [
"MIT"
] | null | null | null | #include "Clyde.h"
#include "../../Tile.h"
#include "../Pacman/Pacman.h"
#include "../../States/GameState/GameState.h"
Clyde::Clyde(sf::Vector2i gridPos, GameState* gameState)
: Enemy(gridPos, sf::Vector2i(230, 113), gameState, Entities::Clyde)
{
SetupAnimations();
}
Clyde::~Clyde() { }
sf::Vector2i Clyde::GetScatterTargetPosition()
{
return sf::Vector2i(1, 29);
}
sf::Vector2i Clyde::GetChaseTargetPosition()
{
if (sTile::GetDistanceBetweenTiles(gridPos, gameState->pacman->gridPos) > 8)
return gameState->pacman->gridPos;
return sf::Vector2i(1, 29);
}
void Clyde::SetupAnimations()
{
sf::Texture r1, r2, l1, l2;
r1.loadFromFile("Resources/PacManSprites.png", sf::IntRect(230, 113, 14, 14));
r2.loadFromFile("Resources/PacManSprites.png", sf::IntRect(246, 113, 14, 14));
l1.loadFromFile("Resources/PacManSprites.png", sf::IntRect(262, 113, 14, 14));
l2.loadFromFile("Resources/PacManSprites.png", sf::IntRect(278, 113, 14, 14));
std::vector<sf::Texture> leftAnimTextures{ l1,l2 };
std::vector<sf::Texture> rightAnimTextures{ r1,r2 };
sf::Texture u1, u2, d1, d2;
u1.loadFromFile("Resources/PacManSprites.png", sf::IntRect(294, 113, 14, 14));
u2.loadFromFile("Resources/PacManSprites.png", sf::IntRect(310, 113, 14, 14));
d1.loadFromFile("Resources/PacManSprites.png", sf::IntRect(326, 113, 14, 14));
d2.loadFromFile("Resources/PacManSprites.png", sf::IntRect(342, 113, 14, 14));
std::vector<sf::Texture> upAnimTextures{ u1,u2 };
std::vector<sf::Texture> downAnimTextures{ d1,d2 };
animations[0] = new Animation(leftAnimTextures, true, 0.1f);
animations[1] = new Animation(rightAnimTextures, true, 0.1f);
animations[2] = new Animation(upAnimTextures, true, 0.1f);
animations[3] = new Animation(downAnimTextures, true, 0.1f);
} | 34.568627 | 79 | 0.711855 | [
"vector"
] |
52655fbdbfec8ecdb874a4ecfa14ae63465299e8 | 56,074 | hpp | C++ | canabis/include/bisimage_maths.hpp | amwink/bis | 5d12c54b23be202d179fea9558d1aab09c35392e | [
"MIT"
] | null | null | null | canabis/include/bisimage_maths.hpp | amwink/bis | 5d12c54b23be202d179fea9558d1aab09c35392e | [
"MIT"
] | null | null | null | canabis/include/bisimage_maths.hpp | amwink/bis | 5d12c54b23be202d179fea9558d1aab09c35392e | [
"MIT"
] | null | null | null | #ifndef BISIMAGE_MATHS_HPP_INCLUDED
#define BISIMAGE_MATHS_HPP_INCLUDED
/* Much of the basic 2/3/4D matrix/vector maths
* in this header is inspired by Linas Vepstas'
* https://fossies.org/linux/gle/src/vvector.h
*
* These classes are a middle ground between the
* speed of #define directives and the flexibility
* of class definitions.
*
*
*
* To request more functionality, contact
* Alle Meije Wink, mail: a.m.wink@gmail.com
*
*/
#define _USE_MATH_DEFINES
#include<math.h>
#include<vector>
#include<cfloat>
#include<climits>
#include<iostream>
#include<cassert>
namespace bis {
/* templated signum function
*
*
*/
template < typename T >
T signum (T x) {
if (x > 0) return 1;
if (x < 0) return -1;
return x;
}
/* Vectors and matrices in 2 dimensions
*
* For manipulating 2-dimensional (2D) coordinates, matrices and 2D
* vectors, and their operations, are important tools. Examples are
* operations on digital pictures or slices of a 3D scan. To access
* and change such data, it is important to optimise the operations
* that handle 2D images.
*/
// forward declarations
template <class>
class vec2;
template <class>
class mat2;
/* 2-vector
*
* We define this mathematical object because it is often used in 2D scans
*/
template <typename T>
class vec2 {
template <typename U>
friend std::ostream& operator<<(std::ostream& out, const vec2<U>& v);
template <typename U>
friend std::istream& operator>>(std::istream& in, vec2<U>& v);
protected:
std::vector<T> data;
public:
vec2 (): data(2)
{}; // default constructor
vec2 ( T x, T y ): data(2)
{ data[0] = x; data[1] = y; } // constructor from 2 scalars
vec2 ( T* xyz ): data(2)
{ std::copy (xyz, xyz+2, data.begin() ); } // constructor from pointer
vec2 ( const vec2<T>& rhs ): data(2)
{ std::copy ( rhs.data.begin(), rhs.data.end(), data.begin() ); } // copy constructor
vec2<T> operator=( vec2<T> rhs ) {
std::copy( rhs.data.begin(), rhs.data.end(), data.begin() ); // assignment of vector
return (*this);
}
vec2<T> operator=( T rhs ) {
data = rhs; // assignment of scalar
return (*this);
}
// passing on the [] operator for accessing elements
T& operator[] ( size_t offset) { return data[offset]; } // write access
const T& operator[] ( size_t offset) const { return data[offset]; } // read access
// (in) equality
bool operator== (vec2& v) { return ( data[0]==v[0] && data[1]==v[1] ); }
bool operator!= (vec2& v) { return !( (*this) == v ); }
// some vector computations
T norm() { return ( sqrt( (*this) & (*this) ) ); } // norm: square root of inner product
vec2<T> reciprocal ( const vec2& v ) const { return vec2 ( 1 / data[0], 1 / data[1] ); }
// return std::vector with coefficients
std::vector<T> getdata() { return data; }
// left += and + for elements and vectors
const vec2<T>& operator+= ( const T& rhs ) { data[0]+=rhs; data[1]+=rhs; return (*this); }
template <typename U>
const vec2<T>& operator+= ( const vec2<U>& rhs ) { data[0]+=rhs[0]; data[1]+=rhs[1]; return (*this); }
template <typename U>
const vec2<T> operator+ ( const U& rhs ) { vec2<T> out(*this); out += rhs; return out; }
// left -= and - for elements and vectors
const vec2<T>& operator-= ( const T& rhs ) { data[0]-=rhs; data[1]-=rhs; return (*this); }
template <typename U>
const vec2<T>& operator-= ( const vec2<U>& rhs ) { data[0]-=rhs[0]; data[1]-=rhs[1]; return (*this); }
template <typename U>
const vec2<T> operator- ( const U& rhs ) { vec2<T> out(*this); out -= rhs; return out; }
const vec2<T> operator- ( void ) { return vec2 ( -data[0], -data[1] ); }
// left *= and * for elements and vectors
const vec2<T>& operator*= ( const T& rhs ) { data[0]*=rhs; data[1]*=rhs; return (*this); }
template <typename U>
const vec2<T>& operator*= ( const vec2<U>& rhs ) { data[0]*=rhs[0]; data[1]*=rhs[1]; return (*this); }
// multiplication by scalar
const vec2<T> operator* ( const T& rhs ) { vec2<T> out(*this); out *= rhs; return out; }
// multiplication by vector
template <typename U>
const vec2<T> operator* ( const vec2<U>& rhs ) { vec2<T> out(*this); out *= rhs; return out; }
// multiplication by matrix (if v is a row vector)
template <typename U>
vec2<T> operator*( const mat2<U>& m ) const { return vec2( data[0] * m[0][0] + data[1] * m[1][0],
data[0] * m[0][1] + data[1] * m[1][1] ); }
// left /= and / for elements and vectors
const vec2<T>& operator/= ( const T& rhs ) { data[0]/=rhs; data[1]/=rhs; return (*this); }
template <typename U>
const vec2<T>& operator/= ( const vec2<U>& rhs ) { data[0]/=rhs[0]; data[1]/=rhs[1]; return (*this); }
template <typename U>
const vec2<T> operator/ ( const U& rhs ) { vec2<T> out(*this); out /= rhs; return out; }
// dot product (inner product in the more general case)
T operator& ( const vec2& v ) const { return v[0] * data[0] + v[1] * data[1]; }
// cross product (exterior/wedge product in other than 3D but mostly used in 3D as cross product)
vec2<T> operator^( const vec2& v ) const { return vec2( data[0] * v[1] - data[1] * v[0] ); }
};
// non-members of vec2 for vec2
template <typename U>
std::ostream& operator<<(std::ostream& out, const vec2<U>& v)
{ return out << '(' << v.data[0] << ',' << v.data[1] << ')'; }
template <typename U>
std::istream& operator>>(std::istream& in , vec2<U> &v)
{ return in >> v.data[0] >> v.data[1]; }
// right +, -, * and / operators
template <typename T>
inline vec2 <T> operator+ ( T x, vec2 <T> y) {
return y + x;
}
template <typename T>
inline vec2 <T> operator* ( T x, vec2 <T> y) {
return y * x;
}
template <typename T>
inline vec2 <T> operator- ( T x, vec2 <T> y) {
return -y + x;
}
template <typename T>
inline vec2 <T> operator/ ( T x, vec2 <T> y) {
return reciprocal(y) * x;
}
/* 2x2 matrix
*
* We define this mathematical object because it is often used in 2D image applications
*/
template <typename T>
class mat2 {
template <typename U>
friend std::ostream& operator<<(std::ostream& out, const mat2<U>& v);
template <typename U>
friend std::istream& operator>>(std::istream& in, mat2<U>& v);
protected:
std::vector<T> data;
public:
mat2 ( ): data(4)
{}; // default constructor
mat2 ( T x0, T y0,
T x1, T y1 ): data(4)
{ data[0] = x0; data[1] = y0;
data[2] = x1; data[3] = y1; } // constructor from 4 scalars
mat2 ( T* xyz ): data(4)
{ std::copy (xyz, xyz+4, data.begin() ); } // constructor from pointer
mat2 ( const mat2<T>& rhs ): data(4)
{ std::copy ( rhs.data.begin(), rhs.data.end(), data.begin() ); } // copy constructor
mat2<T> operator=( mat2<T> rhs ) {
std::copy( rhs.data.begin(), rhs.data.end(), data.begin() ); // assignment
return (*this);
}
// passing on the [] operator for accessing 2D elements
T* operator[] (const size_t offset) { return &data[2*offset]; } // write access
const T* operator[] (const size_t offset) const { return &data[2*offset]; } // read access
// (in) equality
bool operator== (mat2& v) { return ( data[0]==v[0] && data[1]==v[1] &&
data[2]==v[2] && data[3]==v[3] ); }
bool operator!= (mat2& v) { return !( (*this) == v ); }
// some matrix computations
mat2<T> reciprocal ( const mat2& v ) const { return mat2 ( 1 / data[0], 1 / data[1],
1 / data[2], 1 / data[3] ); }
const mat2<T> eye ( const T v = 1 ) const { return mat2 ( 1, 0, 0,
0, 1, 0,
0, 0, 1 ); }
// return std::vector with coefficients
std::vector<T> getdata() { return data; }
// left += and + for elements and vectors
const mat2<T>& operator+= ( const T& rhs ) { data[0]+=rhs; data[1]+=rhs;
data[2]+=rhs; data[3]+=rhs;
return (*this); }
template <typename U>
const mat2<T>& operator+= ( const mat2<U>& rhs ) { data[0]+=rhs.data[0]; data[1]+=rhs.data[1];
data[2]+=rhs.data[2]; data[3]+=rhs.data[3];
return (*this); }
template <typename U>
const mat2<T> operator+ ( const U& rhs ) { mat2<T> out(*this); out += rhs; return out; }
// left -= and - for elements and vectors
const mat2<T>& operator-= ( const T& rhs ) { data[0]-=rhs; data[1]-=rhs;
data[2]-=rhs; data[3]-=rhs;
return (*this); }
template <typename U>
const mat2<T>& operator-= ( const mat2<U>& rhs ) { data[0]-=rhs[0]; data[1]-=rhs[1];
data[2]-=rhs[2]; data[3]-=rhs[3];
return (*this); }
template <typename U>
const mat2<T> operator- ( const U& rhs ) { mat2<T> out(*this); out -= rhs; return out; }
const mat2<T> operator- ( void ) { return (*this) * -1; }
// matrix-matrix product (only for 2 mat2-sized inputs)
template <typename U>
mat2<T> operator*=( mat2<U>& m ) { mat2<T> m2( m.data[0] * data[0] + m.data[2] * data[1],
m.data[1] * data[0] + m.data[3] * data[1],
m.data[0] * data[2] + m.data[2] * data[3],
m.data[1] * data[2] + m.data[3] * data[3] );
(*this) = m2;
return (*this); }
// left *= for elements
const mat2<T>& operator*= ( const T& rhs ) { data[0]*=rhs; data[1]*=rhs;
data[2]*=rhs; data[3]*=rhs;
return (*this); }
// operator *
template <typename U>
const mat2<T> operator* ( mat2<U>& rhs ) { mat2<T> out(*this); out *= rhs; return out; }
const mat2<T> operator* ( const T& rhs ) { mat2<T> out(*this); out *= rhs; return out; }
// hadamard product (element-wise multiplication)
template <typename U>
const mat2<T>& hadamard ( const mat2<U>& rhs ) { data[0]/=rhs.data[0]; data[1]/=rhs.data[1];
data[2]/=rhs.data[2]; data[3]/=rhs.data[3];
return (*this); }
// left /= and / for elements and vectors
const mat2<T>& operator/= ( const T& rhs ) { data[0]/=rhs; data[1]/=rhs;
data[2]/=rhs; data[3]/=rhs;
return (*this); }
template <typename U>
const mat2<T>& operator/= ( const mat2<U>& rhs ) { data[0]/=rhs.data[0]; data[1]/=rhs.data[1];
data[2]/=rhs.data[2]; data[3]/=rhs.data[3];
return (*this); }
template <typename U>
const mat2<T> operator/ ( const U& rhs ) { mat2<T> out(*this); out /= rhs; return out; }
// adjoint (adjugate) matrix -- required for inverse
mat2<T> adjoint( const T scale = 1 ) const { return mat2( scale * data[3],
-scale * data[1],
-scale * data[2],
scale * data[0] ); }
// determinant
T determinant() const { return ( data[0] * data[3] - data[1] * data[2] ); }
// inverse
const mat2<T> inverse() {
T det = this->determinant();
if ( det > FLT_EPSILON || det < -FLT_EPSILON )
return ( this->adjoint ( 1 / det ) );
else
return (*this) * std::numeric_limits<T>::quiet_NaN();
}
};
// non-members of mat2 for mat2
template <typename U>
std::ostream& operator<<(std::ostream& out, const mat2<U>& m)
{ return out << '(' << m.data[0] << ',' << m.data[1] << ',' << std::endl
<< ' ' << m.data[2] << ',' << m.data[3] << ')'; }
template <typename U>
std::istream& operator>>(std::istream& in , mat2<U> &m)
{ return in >> m.data[0] >> m.data[1]
>> m.data[3] >> m.data[4]; }
// right +, -, * and / operators
template <typename T>
inline mat2 <T> operator+ ( T x, mat2 <T> y) {
return y + x;
}
template <typename T>
inline mat2 <T> operator* ( T x, mat2 <T> y) {
return y * x;
}
template <typename T>
inline mat2 <T> operator- ( T x, mat2 <T> y) {
return -y + x;
}
template <typename T>
inline mat2 <T> operator/ ( T x, mat2 <T> y) {
return reciprocal(y) * x;
}
// matrix-vector product (vector is assumed to be a column vector)
template <typename T, typename U>
const vec2<T> operator* ( const mat2<U>& m, const vec2<T>& v ) { return vec2( v[0] * m[0][0] + v[1] * m[0][1],
v[0] * m[1][0] + v[1] * m[1][1] ); }
// hadamard product (element-wise multiplication)
template <typename T, typename U>
const mat2<T> hadamard ( const mat2<U>& m, const mat2<T>& n ) { return m.hadamard(n); }
/* Vectors and matrices in 3 dimensions
*
* For manipulating 3-dimensional (3D) coordinates, 3D matrices and
* vectors, and their operations, are important tools. Examples are
* voxel (3D pixel) coordinates in an MRI scan. To access and change
* data at locations in these scans, it is important to optimise the
* operations that handle 3D image space.
*/
// forward declarations
template <class>
class vec3;
template <class>
class mat3;
/* 3-vector
*
* We define this mathematical object because it is often used in 3D scans
*/
template <typename T>
class vec3 {
template <typename U>
friend std::ostream& operator<<(std::ostream& out, const vec3<U>& v);
template <typename U>
friend std::istream& operator>>(std::istream& in, vec3<U>& v);
protected:
std::vector<T> data;
public:
vec3 ( ): data(3)
{}; // default constructor
vec3 ( T x, T y, T z ): data(3)
{ data[0] = x; data[1] = y; data[2] = z; } // constructor from 3 scalars
vec3 ( T* xyz ): data(3)
{ std::copy (xyz, xyz+3, data.begin() ); } // constructor from pointer
vec3 ( const vec3<T>& rhs ): data(3)
{ std::copy ( rhs.data.begin(), rhs.data.end(), data.begin() ); } // copy constructor
vec3 ( const vec2<T>& rhs ): data(3)
{ data[0] = rhs[0]; data[1]=rhs[1]; } // copy from vec2 (add a 0)
vec3<T> operator=( vec3<T> rhs ) {
std::copy( rhs.data.begin(), rhs.data.end(), data.begin() ); // assignment of vector
return (*this);
}
vec3<T> operator=( T rhs ) {
data = rhs; // assignment of scalar
return (*this);
}
// passing on the [] operator for accessing elements
T& operator[] ( size_t offset) { return data[offset]; } // write access
const T& operator[] ( size_t offset) const { return data[offset]; } // read access
// (in) equality
bool operator== (vec3& v) { return ( data[0]==v[0] && data[1]==v[1] && data[2]==v[2] ); }
bool operator!= (vec3& v) { return !( (*this) == v ); }
// some vector computations
T norm() { return ( sqrt( (*this) & (*this) ) ); } // norm: square root of inner product
vec3<T> reciprocal ( const vec3& v ) const { return vec3 ( 1 / data[0], 1 / data[1], 1 / data[2] ); }
// return std::vector with coefficients
std::vector<T> getdata() { return data; }
// left += and + for elements and vectors
const vec3<T>& operator+= ( const T& rhs ) { data[0]+=rhs; data[1]+=rhs; data[2]+=rhs; return (*this); }
template <typename U>
const vec3<T>& operator+= ( const vec3<U>& rhs ) { data[0]+=rhs[0]; data[1]+=rhs[1]; data[2]+=rhs[2]; return (*this); }
template <typename U>
const vec3<T> operator+ ( const U& rhs ) { vec3<T> out(*this); out += rhs; return out; }
// left -= and - for elements and vectors
const vec3<T>& operator-= ( const T& rhs ) { data[0]-=rhs; data[1]-=rhs; data[2]-=rhs; return (*this); }
template <typename U>
const vec3<T>& operator-= ( const vec3<U>& rhs ) { data[0]-=rhs[0]; data[1]-=rhs[1]; data[2]-=rhs[2]; return (*this); }
template <typename U>
const vec3<T> operator- ( const U& rhs ) { vec3<T> out(*this); out -= rhs; return out; }
const vec3<T> operator- ( void ) { return vec3 ( -data[0], -data[1], -data[2] ); }
// left *= and * for elements and vectors
const vec3<T>& operator*= ( const T& rhs ) { data[0]*=rhs; data[1]*=rhs; data[2]*=rhs; return (*this); }
template <typename U>
const vec3<T>& operator*= ( const vec3<U>& rhs ) { data[0]*=rhs[0]; data[1]*=rhs[1]; data[2]*=rhs[2]; return (*this); }
// multiplication by scalar
const vec3<T> operator* ( const T& rhs ) { vec3<T> out(*this); out *= rhs; return out; }
// multiplication by vector
template <typename U>
const vec3<T> operator* ( const vec3<U>& rhs ) { vec3<T> out(*this); out *= rhs; return out; }
// multiplication by matrix (if v is a row vector)
template <typename U>
vec3<T> operator*( const mat3<U>& m ) const { return vec3( data[0] * m[0][0] + data[1] * m[1][0] + data[2] * m[2][0],
data[0] * m[0][1] + data[1] * m[1][1] + data[2] * m[2][1],
data[0] * m[0][2] + data[1] * m[1][2] + data[2] * m[2][2] ); }
// left /= and / for elements and vectors
const vec3<T>& operator/= ( const T& rhs ) { data[0]/=rhs; data[1]/=rhs; data[2]/=rhs; return (*this); }
template <typename U>
const vec3<T>& operator/= ( const vec3<U>& rhs ) { data[0]/=rhs[0]; data[1]/=rhs[1]; data[2]/=rhs[2]; return (*this); }
template <typename U>
const vec3<T> operator/ ( const U& rhs ) { vec3<T> out(*this); out /= rhs; return out; }
// dot product (inner product in the more general case)
T operator& ( const vec3& v ) const { return v[0] * data[0] + v[1] * data[1] + v[2] * data[2]; }
// cross product (wedge product in other than 3D but mostly used in 3D as cross product)
vec3<T> operator^( const vec3& v ) const { return vec3( data[1] * v[2] - data[2] * v[1],
data[0] * v[2] - data[2] * v[0],
data[0] * v[1] - data[1] * v[0] ); }
};
// non-members of vec3 for vec3
template <typename U>
std::ostream& operator<<(std::ostream& out, const vec3<U>& v)
{ return out << '(' << v.data[0] << ',' << v.data[1] << ',' << v.data[2] <<')'; }
template <typename U>
std::istream& operator>>(std::istream& in , vec3<U> &v)
{ return in >> v.data[0] >> v.data[1] >> v.data[2]; }
// right +, -, * and / operators
template <typename T>
inline vec3 <T> operator+ ( T x, vec3 <T> y) {
return y + x;
}
template <typename T>
inline vec3 <T> operator* ( T x, vec3 <T> y) {
return y * x;
}
template <typename T>
inline vec3 <T> operator- ( T x, vec3 <T> y) {
return -y + x;
}
template <typename T>
inline vec3 <T> operator/ ( T x, vec3 <T> y) {
return reciprocal(y) * x;
}
/* 3x3 matrix
*
* We define this mathematical object because it is often used in 3D scans
*/
template <typename T>
class mat3 {
template <typename U>
friend std::ostream& operator<<(std::ostream& out, const mat3<U>& v);
template <typename U>
friend std::istream& operator>>(std::istream& in, mat3<U>& v);
protected:
std::vector<T> data;
public:
mat3 ( ): data(9)
{}; // default constructor
mat3 ( T x0, T y0, T z0,
T x1, T y1, T z1,
T x2, T y2, T z2 ): data(9)
{ data[0] = x0; data[1] = y0; data[2] = z0;
data[3] = x1; data[4] = y1; data[5] = z1;
data[6] = x2; data[7] = y2; data[8] = z2; } // constructor from 9 scalars
mat3 ( T* xyz ): data(9)
{ std::copy (xyz, xyz+9, data.begin() ); } // constructor from pointer
mat3 ( const mat3<T>& rhs ): data(9)
{ std::copy ( rhs.data.begin(), rhs.data.end(), data.begin() ); } // copy constructor
mat3 ( const mat2<T>& rhs ): data(9)
{ data[0] = rhs[0][0]; data[1]=rhs[0][1];
data[3] = rhs[1][0]; data[4]=rhs[1][1]; } // copy from mat2 (add col + row of 0)
mat3<T> operator=( mat3<T> rhs ) {
std::copy( rhs.data.begin(), rhs.data.end(), data.begin() ); // assignment
return (*this);
}
// passing on the [] operator for accessing 2D elements
T* operator[] (const size_t offset) { return &data[3*offset]; } // write access
const T* operator[] (const size_t offset) const { return &data[3*offset]; } // read access
// (in) equality
bool operator== (mat3& v) { return ( data[0]==v[0] && data[1]==v[1] && data[2]==v[2] &&
data[3]==v[3] && data[4]==v[4] && data[4]==v[4] &&
data[6]==v[6] && data[7]==v[7] && data[8]==v[8] ); }
bool operator!= (mat3& v) { return !( (*this) == v ); }
// some matrix computations
mat3<T> reciprocal ( const mat3& v ) const { return mat3 ( 1 / data[0], 1 / data[1], 1 / data[2],
1 / data[3], 1 / data[4], 1 / data[5],
1 / data[6], 1 / data[7], 1 / data[8] ); }
const mat3<T> eye ( const T v = 1 ) const { return mat3 ( 1, 0, 0,
0, 1, 0,
0, 0, 1 ); }
// return std::vector with coefficients
std::vector<T> getdata() { return data; }
// left += and + for elements and vectors
const mat3<T>& operator+= ( const T& rhs ) { data[0]+=rhs; data[1]+=rhs; data[2]+=rhs;
data[3]+=rhs; data[4]+=rhs; data[5]+=rhs;
data[6]+=rhs; data[7]+=rhs; data[8]+=rhs;
return (*this); }
template <typename U>
const mat3<T>& operator+= ( const mat3<U>& rhs ) { data[0]+=rhs.data[0]; data[1]+=rhs.data[1]; data[2]+=rhs.data[2];
data[3]+=rhs.data[3]; data[4]+=rhs.data[4]; data[5]+=rhs.data[5];
data[6]+=rhs.data[6]; data[7]+=rhs.data[7]; data[8]+=rhs.data[8];
return (*this); }
template <typename U>
const mat3<T> operator+ ( const U& rhs ) { mat3<T> out(*this); out += rhs; return out; }
// left -= and - for elements and vectors
const mat3<T>& operator-= ( const T& rhs ) { data[0]-=rhs; data[1]-=rhs; data[2]-=rhs;
data[3]-=rhs; data[4]-=rhs; data[5]-=rhs;
data[6]-=rhs; data[7]-=rhs; data[8]-=rhs;
return (*this); }
template <typename U>
const mat3<T>& operator-= ( const mat3<U>& rhs ) { data[0]-=rhs[0]; data[1]-=rhs[1]; data[2]-=rhs[2];
data[3]-=rhs[3]; data[4]-=rhs[4]; data[5]-=rhs[5];
data[6]-=rhs[6]; data[7]-=rhs[7]; data[8]-=rhs[8];
return (*this); }
template <typename U>
const mat3<T> operator- ( const U& rhs ) { mat3<T> out(*this); out -= rhs; return out; }
const mat3<T> operator- ( void ) { return (*this) * -1; }
// matrix-matrix product (only for 2 mat3-sized inputs)
template <typename U>
mat3<T> operator*=( mat3<U>& m ) { mat3<T> m2( m.data[0] * data[0] + m.data[3] * data[1] + m.data[6] * data[2],
m.data[1] * data[0] + m.data[4] * data[1] + m.data[7] * data[2],
m.data[2] * data[0] + m.data[5] * data[1] + m.data[8] * data[2],
m.data[0] * data[3] + m.data[3] * data[4] + m.data[6] * data[5],
m.data[1] * data[3] + m.data[4] * data[4] + m.data[7] * data[5],
m.data[2] * data[3] + m.data[5] * data[4] + m.data[8] * data[5],
m.data[0] * data[6] + m.data[3] * data[7] + m.data[6] * data[8],
m.data[1] * data[6] + m.data[4] * data[7] + m.data[7] * data[8],
m.data[2] * data[6] + m.data[5] * data[7] + m.data[8] * data[8] );
(*this) = m2;
return (*this); }
// left *= for elements
const mat3<T>& operator*= ( const T& rhs ) { data[0]*=rhs; data[1]*=rhs; data[2]*=rhs;
data[3]*=rhs; data[4]*=rhs; data[5]*=rhs;
data[6]*=rhs; data[7]*=rhs; data[8]*=rhs;
return (*this); }
// operator *
template <typename U>
const mat3<T> operator* ( mat3<U>& rhs ) { mat3<T> out(*this); out *= rhs; return out; }
const mat3<T> operator* ( const T& rhs ) { mat3<T> out(*this); out *= rhs; return out; }
// hadamard product (element-wise multiplication)
template <typename U>
const mat3<T>& hadamard ( const mat3<U>& rhs ) { data[0]/=rhs.data[0]; data[1]/=rhs.data[1]; data[2]/=rhs.data[2];
data[3]/=rhs.data[3]; data[4]/=rhs.data[4]; data[5]/=rhs.data[5];
data[6]/=rhs.data[6]; data[7]/=rhs.data[7]; data[8]/=rhs.data[8];
return (*this); }
// left /= and / for elements and vectors
const mat3<T>& operator/= ( const T& rhs ) { data[0]/=rhs; data[1]/=rhs; data[2]/=rhs;
data[3]/=rhs; data[4]/=rhs; data[5]/=rhs;
data[6]/=rhs; data[7]/=rhs; data[8]/=rhs;
return (*this); }
template <typename U>
const mat3<T>& operator/= ( const mat3<U>& rhs ) { data[0]/=rhs.data[0]; data[1]/=rhs.data[1]; data[2]/=rhs.data[2];
data[3]/=rhs.data[3]; data[4]/=rhs.data[4]; data[5]/=rhs.data[5];
data[6]/=rhs.data[6]; data[7]/=rhs.data[7]; data[8]/=rhs.data[8];
return (*this); }
template <typename U>
const mat3<T> operator/ ( const U& rhs ) { mat3<T> out(*this); out /= rhs; return out; }
// adjoint (adjugate) matrix -- required for inverse
mat3<T> adjoint( const T scale = 1 ) const { return mat3( scale * (data[4] * data[8] - data[5] * data[7]),
-scale * (data[1] * data[8] - data[2] * data[7]),
scale * (data[1] * data[5] - data[2] * data[4]),
-scale * (data[3] * data[8] - data[6] * data[5]),
scale * (data[0] * data[8] - data[2] * data[6]),
-scale * (data[0] * data[5] - data[2] * data[3]),
scale * (data[3] * data[7] - data[4] * data[6]),
-scale * (data[0] * data[7] - data[1] * data[6]),
scale * (data[0] * data[4] - data[1] * data[3]) ); }
// determinant
T determinant() const { return data[0] * ( data[4] * data[8] - data[5] * data[7] )
- data[1] * ( data[3] * data[8] - data[5] * data[6] )
+ data[2] * ( data[3] * data[7] - data[4] * data[6] ); }
// inverse
const mat3<T> inverse() {
T det = this->determinant();
if ( det > FLT_EPSILON || det < -FLT_EPSILON )
return ( this->adjoint ( 1 / det ) );
else
return (*this) * std::numeric_limits<T>::quiet_NaN();
}
};
// non-members of mat3 for mat3
template <typename U>
std::ostream& operator<<(std::ostream& out, const mat3<U>& m)
{ return out << '(' << m.data[0] << ',' << m.data[1] << ',' << m.data[2] << std::endl
<< ' ' << m.data[3] << ',' << m.data[4] << ',' << m.data[5] << std::endl
<< ' ' << m.data[6] << ',' << m.data[7] << ',' << m.data[8] << ')'; }
template <typename U>
std::istream& operator>>(std::istream& in , mat3<U> &v)
{ return in >> v.data[0] >> v.data[1] >> v.data[2]
>> v.data[3] >> v.data[4] >> v.data[5]
>> v.data[6] >> v.data[7] >> v.data[8]; }
// right +, -, * and / operators
template <typename T>
inline mat3 <T> operator+ ( T x, mat3 <T> y) {
return y + x;
}
template <typename T>
inline mat3 <T> operator* ( T x, mat3 <T> y) {
return y * x;
}
template <typename T>
inline mat3 <T> operator- ( T x, mat3 <T> y) {
return -y + x;
}
template <typename T>
inline mat3 <T> operator/ ( T x, mat3 <T> y) {
return reciprocal(y) * x;
}
// matrix-vector product (vector is assumed to be a column vector)
template <typename T, typename U>
const vec3<T> operator* ( const mat3<U>& m, const vec3<T>& v ) { return vec3( v[0] * m[0][0] + v[1] * m[0][1] + v[2] * m[0][2],
v[0] * m[1][0] + v[1] * m[1][1] + v[2] * m[1][2],
v[0] * m[2][0] + v[1] * m[2][1] + v[2] * m[2][2] ); }
// hadamard product (element-wise multiplication)
template <typename T, typename U>
const mat3<T> hadamard ( const mat3<U>& m, const mat3<T>& n ) { return m.hadamard(n); }
/* Vectors and matrices in 4 dimensions
*
* An important application of 4-dimensional (4D) matrices and vectors
* is the manipulation of homogeneous co-ordinates of 3D coordinates.
* An affine transformation of a 3D vector cannot be represented in a
* single 3D matrix. By extending the vector [x y z] to 4D [x y z 1].
* Translations and perspective can then be expressed as matrix
* multiplications.
*/
// forward declarations
template <class>
class vec4;
template <class>
class mat4;
/* 4-vector
*
* We define this mathematical object because it is often used in 4D scans
*/
template <typename T>
class vec4 {
template <typename U>
friend std::ostream& operator<<(std::ostream& out, const vec4<U>& v);
template <typename U>
friend std::istream& operator>>(std::istream& in, vec4<U>& v);
protected:
std::vector<T> data;
public:
vec4 ( ): data(4)
{}; // default constructor
vec4 ( T x, T y, T z, T t ): data(4)
{ data[0] = x; data[1] = y; data[2] = z; data[3] = t; } // constructor from 4 scalars
vec4 ( T* xyz ): data(4)
{ std::copy (xyz, xyz+4, data.begin() ); } // constructor from pointer
vec4 ( const vec4<T>& rhs ): data(4)
{ std::copy ( rhs.data.begin(), rhs.data.end(), data.begin() ); } // copy constructor
vec4 ( const vec2<T>& rhs ): data(4)
{ data[0] = rhs[0]; data[1] = rhs[1]; } // copy from vec2 (add 2 0s)
vec4 ( const vec3<T>& rhs ): data(4)
{ data[0] = rhs[0]; data[1] = rhs[1]; data[2] = rhs[2]; } // copy from vec3 (add a 0)
vec4<T> operator=( vec4<T> rhs ) {
std::copy( rhs.data.begin(), rhs.data.end(), data.begin() ); // assignment of vector
return (*this);
}
vec4<T> operator=( T rhs ) {
data = rhs; // assignment of scalar
return (*this);
}
// passing on the [] operator for accessing elements
T& operator[] ( size_t offset) { return data[offset]; } // write access
const T& operator[] ( size_t offset) const { return data[offset]; } // read access
// (in) equality
bool operator== (vec4& v) { return ( data[0]==v[0] && data[1]==v[1] && data[2]==v[2] && data[3]==v[3] ); }
bool operator!= (vec4& v) { return !( (*this) == v ); }
// some vector computations
T norm() { return ( sqrt( (*this) & (*this) ) ); } // norm: square root of inner product
vec4<T> reciprocal ( const vec4& v ) const { return vec4 ( 1 / data[0], 1 / data[1], 1 / data[2] ); }
// return std::vector with coefficients
std::vector<T> getdata() { return data; }
// left += and + for elements and vectors
const vec4<T>& operator+= ( const T& rhs ) { for ( auto i : {0,1,2,3} ) data[i] += rhs; return (*this); }
template <typename U>
const vec4<T>& operator+= ( const vec4<U>& rhs ) { for ( auto i : {0,1,2,3} ) data[i] += rhs[i]; return (*this); }
template <typename U>
const vec4<T> operator+ ( const U& rhs ) { vec4<T> out(*this); out += rhs; return out; }
// left -= and - for elements and vectors
const vec4<T>& operator-= ( const T& rhs ) { for ( auto i : {0,1,2,3} ) data[i] -= rhs; return (*this); }
template <typename U>
const vec4<T>& operator-= ( const vec4<U>& rhs ) { for ( auto i : {0,1,2,3} ) data[i] -= rhs[i]; return (*this); }
template <typename U>
const vec4<T> operator- ( const U& rhs ) { vec4<T> out(*this); out -= rhs; return out; }
const vec4<T> operator- ( void ) { return vec4 ( -data[0], -data[1], -data[2], data[3] ); }
// left *= and * for elements and vectors
const vec4<T>& operator*= ( const T& rhs ) { for ( auto i : {0,1,2,3} ) data[i] *= rhs; return (*this); }
template <typename U>
const vec4<T>& operator*= ( const vec4<U>& rhs ) { for ( auto i : {0,1,2,3} ) data[i] *= rhs[i]; return (*this); }
// multiplication by scalar
const vec4<T> operator* ( const T& rhs ) { vec4<T> out(*this); out *= rhs; return out; }
// multiplication by vector
template <typename U>
const vec4<T> operator* ( const vec4<U>& rhs ) { vec4<T> out(*this); out *= rhs; return out; }
// multiplication by matrix (if v is a row vector)
template <typename U>
vec4<T> operator*( const mat4<U>& m ) const { return vec4( data[0] * m[0][0] + data[1] * m[1][0]
+ data[2] * m[2][0] + data[2] * m[3][0],
data[0] * m[0][1] + data[1] * m[1][1]
+ data[2] * m[2][1] + data[3] * m[3][1],
data[0] * m[0][2] + data[1] * m[1][2]
+ data[2] * m[2][2] + data[3] * m[3][2],
data[0] * m[0][3] + data[1] * m[1][3]
+ data[2] * m[2][3] + data[3] * m[3][3] ); }
// left /= and / for elements and vectors
const vec4<T>& operator/= ( const T& rhs ) { for ( auto i : {0,1,2,3} ) data[i] /= rhs; return (*this); }
template <typename U>
const vec4<T>& operator/= ( const vec4<U>& rhs ) { for ( auto i : {0,1,2,3} ) data[i] /= rhs[i]; return (*this); }
template <typename U>
const vec4<T> operator/ ( const U& rhs ) { vec4<T> out(*this); out /= rhs; return out; }
// inner product (generalisation of dot product)
T operator& ( const vec4& v ) const { return v[0] * data[0] + v[1] * data[1] + v[2] * data[2] + v[3] * data[3]; }
};
// non-members of vec4 for vec4
template <typename U>
std::ostream& operator<<(std::ostream& out, const vec4<U>& v)
{ return out << '(' << v.data[0] << ',' << v.data[1] << ',' << v.data[2] << ',' << v.data[3] <<')'; }
template <typename U>
std::istream& operator>>(std::istream& in , vec4<U> &v)
{ return in >> v.data[0] >> v.data[1] >> v.data[2] >> v.data[3]; }
// right +, -, * and / operators
template <typename T>
inline vec4 <T> operator+ ( T x, vec4 <T> y) {
return y + x;
}
template <typename T>
inline vec4 <T> operator* ( T x, vec4 <T> y) {
return y * x;
}
template <typename T>
inline vec4 <T> operator- ( T x, vec4 <T> y) {
return -y + x;
}
template <typename T>
inline vec4 <T> operator/ ( T x, vec4 <T> y) {
return reciprocal(y) * x;
}
/* 4x4 matrix
*
* We define this mathematical object because it is often used in 4D scans
*/
template <typename T>
class mat4 {
template <typename U>
friend std::ostream& operator<<(std::ostream& out, const mat4<U>& v);
template <typename U>
friend std::istream& operator>>(std::istream& in, mat4<U>& v);
protected:
std::vector<T> data;
public:
mat4 ( ): data(16)
{}; // default constructor
mat4 ( T x0, T y0, T z0, T t0,
T x1, T y1, T z1, T t1,
T x2, T y2, T z2, T t2,
T x3, T y3, T z3, T t3 ): data(16)
{ data[ 0] = x0; data[ 1] = y0; data[ 2] = z0; data[ 3] = t0;
data[ 4] = x1; data[ 5] = y1; data[ 6] = z1; data[ 7] = t1;
data[ 8] = x2; data[ 9] = y2; data[10] = z2; data[11] = t2;
data[12] = x3; data[13] = y3; data[14] = z3; data[15] = t3;} // constructor from 16 scalars
mat4 ( T* xyz ): data(16)
{ std::copy (xyz, xyz+16, data.begin() ); } // constructor from pointer
mat4 ( const mat4<T>& rhs ): data(16)
{ std::copy ( rhs.data.begin(), rhs.data.end(), data.begin() ); } // copy constructor
mat4 ( const mat2<T>& rhs ): data(16)
{ data[0] = rhs[0][0]; data[1]=rhs[0][1];
data[4] = rhs[1][0]; data[5]=rhs[1][1]; } // copy from mat2 (add cols + rows of 0)
mat4 ( const mat3<T>& rhs ): data(16)
{ data[0] = rhs[0][0]; data[1]=rhs[0][1]; data[ 2]=rhs[0][2];
data[4] = rhs[1][0]; data[5]=rhs[1][1]; data[ 6]=rhs[1][2];
data[8] = rhs[2][0]; data[9]=rhs[2][1]; data[10]=rhs[1][2]; } // copy from mat3 (add cols + rows of 0)
mat4<T> operator=( mat4<T> rhs ) {
std::copy( rhs.data.begin(), rhs.data.end(), data.begin() ); // assignment
return (*this);
}
// passing on the [] operator for accessing 2D elements
T* operator[] (const size_t offset) { return &data[4*offset]; } // write access
const T* operator[] (const size_t offset) const { return &data[4*offset]; } // read access
// (in) equality
bool operator== (mat4& v) { return ( data[ 0]==v[ 0] && data[ 1]==v[ 1] && data[ 2]==v[ 2] && data[ 3]==v[ 3] &&
data[ 4]==v[ 4] && data[ 5]==v[ 5] && data[ 6]==v[ 6] && data[ 7]==v[ 7] &&
data[ 8]==v[ 8] && data[ 9]==v[ 9] && data[10]==v[10] && data[11]==v[11] &&
data[12]==v[12] && data[13]==v[13] && data[14]==v[14] && data[15]==v[15] ); }
bool operator!= (mat4& v) { return !( (*this) == v ); }
// some matrix computations
mat4<T> reciprocal ( const mat4& v ) const { return mat4 ( 1 / data[ 0], 1 / data[ 1], 1 / data[ 2], 1 / data[ 3],
1 / data[ 4], 1 / data[ 5], 1 / data[ 6], 1 / data[ 7],
1 / data[ 8], 1 / data[ 9], 1 / data[10], 1 / data[11],
1 / data[12], 1 / data[13], 1 / data[14], 1 / data[15] ); }
const mat4<T> eye ( const T v = 1 ) const { return mat4 ( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 ); }
// return std::vector with coefficients
std::vector<T> getdata() { return data; }
// left += and + for elements and vectors
const mat4<T>& operator+= ( const T& rhs ) { for ( int i=0; i<16; i++ ) data[i] += rhs; return (*this); }
template <typename U>
const mat4<T>& operator+= ( const mat4<U>& rhs ) { for ( int i=0; i<16; i++ ) data[i] += rhs.data[i]; return (*this); }
template <typename U>
const mat4<T> operator+ ( const U& rhs ) { mat4<T> out(*this); out += rhs; return out; }
// left -= and - for elements and vectors
const mat4<T>& operator-= ( const T& rhs ) { for ( int i=0; i<16; i++ ) data[i] -= rhs; return (*this); }
template <typename U>
const mat4<T>& operator-= ( const mat4<U>& rhs ) { for ( int i=0; i<16; i++ ) data[i] -= rhs.data[i]; return (*this); }
template <typename U>
const mat4<T> operator- ( const U& rhs ) { mat4<T> out(*this); out -= rhs; return out; }
const mat4<T> operator- ( void ) { return mat4 ( -data[ 0], -data[ 1], -data[ 2], -data[ 3]
-data[ 4], -data[ 5], -data[ 6], -data[ 7]
-data[ 8], -data[ 9], -data[10], -data[11]
-data[12], -data[13], -data[14], -data[15] ); }
// matrix-matrix product (only for 2 mat4-sized inputs)
template <typename U>
mat4<T> operator*=( mat4<U>& m ) { mat4<T> m2( m.data[ 0] * data[ 0] + m.data[ 4] * data[ 1] + m.data[ 8] * data[ 2] + m.data[12] * data[ 3],
m.data[ 1] * data[ 0] + m.data[ 5] * data[ 1] + m.data[ 9] * data[ 2] + m.data[13] * data[ 3],
m.data[ 2] * data[ 0] + m.data[ 6] * data[ 1] + m.data[10] * data[ 2] + m.data[14] * data[ 3],
m.data[ 3] * data[ 0] + m.data[ 7] * data[ 1] + m.data[11] * data[ 2] + m.data[15] * data[ 3],
m.data[ 0] * data[ 4] + m.data[ 4] * data[ 5] + m.data[ 8] * data[ 6] + m.data[12] * data[ 7],
m.data[ 1] * data[ 4] + m.data[ 5] * data[ 5] + m.data[ 9] * data[ 6] + m.data[13] * data[ 7],
m.data[ 2] * data[ 4] + m.data[ 6] * data[ 5] + m.data[10] * data[ 6] + m.data[14] * data[ 7],
m.data[ 3] * data[ 4] + m.data[ 7] * data[ 5] + m.data[11] * data[ 6] + m.data[15] * data[ 7],
m.data[ 0] * data[ 8] + m.data[ 4] * data[ 9] + m.data[ 8] * data[10] + m.data[12] * data[11],
m.data[ 1] * data[ 8] + m.data[ 5] * data[ 9] + m.data[ 9] * data[10] + m.data[13] * data[11],
m.data[ 2] * data[ 8] + m.data[ 6] * data[ 9] + m.data[10] * data[10] + m.data[14] * data[11],
m.data[ 3] * data[ 8] + m.data[ 7] * data[ 9] + m.data[11] * data[10] + m.data[15] * data[11],
m.data[ 0] * data[12] + m.data[ 4] * data[13] + m.data[ 8] * data[14] + m.data[12] * data[15],
m.data[ 1] * data[12] + m.data[ 5] * data[13] + m.data[ 9] * data[14] + m.data[13] * data[15],
m.data[ 2] * data[12] + m.data[ 6] * data[13] + m.data[10] * data[14] + m.data[14] * data[15],
m.data[ 3] * data[12] + m.data[ 7] * data[13] + m.data[11] * data[14] + m.data[15] * data[15] );
(*this) = m2;
return (*this); }
// left *= for elements
const mat4<T>& operator*= ( const T& rhs ) { for ( int i=0; i<16; i++ ) data[i] *= rhs; return (*this); }
// operator *
template <typename U>
const mat4<T> operator* ( mat4<U>& rhs ) { mat4<T> out(*this); out *= rhs; return out; }
const mat4<T> operator* ( const T& rhs ) { mat4<T> out(*this); out *= rhs; return out; }
// hadamard product (element-wise multiplication)
template <typename U>
const mat4<T>& hadamard ( const mat4<U>& rhs ) { for ( int i=0; i<16; i++ ) data[i] *= rhs.data[i]; return (*this); }
// left /= and / for elements and vectors
const mat4<T>& operator/= ( const T& rhs ) { for ( int i=0; i<16; i++ ) data[i] /= rhs; return (*this); }
template <typename U>
const mat4<T>& operator/= ( const mat4<U>& rhs ) { for ( int i=0; i<16; i++ ) data[i] /= rhs.data[i]; return (*this); }
template <typename U>
const mat4<T> operator/ ( const U& rhs ) { mat4<T> out(*this); out /= rhs; return out; }
// cofactors -- required for adjoint (adjugate) matrix
const T cofactor_ij ( size_t i, size_t j ) {
vec4<size_t> ii;
vec4<size_t> jj;
double fac;
// fill with elements except i
for (size_t k=0; k<i; k++) ii[k] = k;
for (size_t k=i; k<3; k++) ii[k] = k+1;
// fill with elements except j
for (size_t k=0; k<j; k++) jj[k] = k;
for (size_t k=j; k<3; k++) jj[k] = k+1;
(fac) = (*this)[ii[0]][jj[0]] * ( (*this)[ii[1]][jj[1]] * (*this)[ii[2]][jj[2]]
- (*this)[ii[1]][jj[2]] * (*this)[ii[2]][jj[1]] );
(fac) -= (*this)[ii[0]][jj[1]] * ( (*this)[ii[1]][jj[0]] * (*this)[ii[2]][jj[2]]
- (*this)[ii[1]][jj[2]] * (*this)[ii[2]][jj[0]] );
(fac) += (*this)[ii[0]][jj[2]] * ( (*this)[ii[1]][jj[0]] * (*this)[ii[2]][jj[1]]
- (*this)[ii[1]][jj[1]] * (*this)[ii[2]][jj[0]] );
/* compute sign */
size_t k = i+j;
if ( k != (k/2)*2) {
(fac) = -(fac);
}
return T(fac);
} // cofactor_ij
// determinant -- 0 for singular matrices
const T determinant () {
T det =
cofactor_ij ( 0, 0 ) * (*this)[0][0] +
cofactor_ij ( 0, 1 ) * (*this)[0][1] +
cofactor_ij ( 0, 2 ) * (*this)[0][2] +
cofactor_ij ( 0, 3 ) * (*this)[0][3];
return det;
} // determinant
// adjoint (adjugate) matrix -- required for inverse
mat4<T> adjoint( const T scale = 1 ) {
mat4<T> out;
for ( int i=0; i<4; i++ )
for ( int j=0; j<4; j++ )
out[j][i] = scale * cofactor_ij ( i, j );
return out;
}
// inverse
const mat4<T> inverse() {
T det = this->determinant();
if ( det > FLT_EPSILON || det < -FLT_EPSILON )
return ( this->adjoint ( 1 / det ) );
else
return (*this) * std::numeric_limits<T>::quiet_NaN();
}
};
// non-members of mat4 for mat4
template <typename U>
std::ostream& operator<<(std::ostream& out, const mat4<U>& m)
{ return out << '(' << m.data[ 0] << ',' << m.data[ 1] << ',' << m.data[ 2] << ',' << m.data[ 3] << std::endl
<< ' ' << m.data[ 4] << ',' << m.data[ 5] << ',' << m.data[ 6] << ',' << m.data[ 7] << std::endl
<< ' ' << m.data[ 8] << ',' << m.data[ 9] << ',' << m.data[10] << ',' << m.data[11] << std::endl
<< ' ' << m.data[12] << ',' << m.data[13] << ',' << m.data[14] << ',' << m.data[15] << ')'; }
template <typename U>
std::istream& operator>>(std::istream& in , mat4<U> &v)
{ return in >> v.data[ 0] >> v.data[ 1] >> v.data[ 2] >> v.data[ 3]
>> v.data[ 4] >> v.data[ 5] >> v.data[ 6] >> v.data[ 7]
>> v.data[ 8] >> v.data[ 9] >> v.data[10] >> v.data[11]
>> v.data[12] >> v.data[13] >> v.data[14] >> v.data[15]; }
// right +, -, * and / operators
template <typename T>
inline mat4 <T> operator+ ( T x, mat4 <T> y) {
return y + x;
}
template <typename T>
inline mat4 <T> operator* ( T x, mat4 <T> y) {
return y * x;
}
template <typename T>
inline mat4 <T> operator- ( T x, mat4 <T> y) {
return -y + x;
}
template <typename T>
inline mat4 <T> operator/ ( T x, mat4 <T> y) {
return reciprocal(y) * x;
}
// matrix-vector product (vector is assumed to be a column vector)
template <typename T, typename U>
const vec4<T> operator* ( const mat4<U>& m, const vec4<T>& v ) { return vec4( v[0] * m[0][0] + v[1] * m[0][1] + v[2] * m[0][2] + v[3] * m[0][3],
v[0] * m[1][0] + v[1] * m[1][1] + v[2] * m[1][2] + v[3] * m[1][3],
v[0] * m[2][0] + v[1] * m[2][1] + v[2] * m[2][2] + v[3] * m[2][3],
v[0] * m[3][0] + v[1] * m[3][1] + v[2] * m[3][2] + v[3] * m[3][3] ); }
// hadamard product (element-wise multiplication)
template <typename T, typename U>
const mat4<T> hadamard ( const mat4<U>& m, const mat4<T>& n ) { return m.hadamard(n); }
template<class T>
inline T fMaxOf2(T min, T max)
{
return max > min ? max : min;
}
template<class T>
inline T fMinOf2(T min, T max)
{
return max > min ? min : max;
}
/** \brief gauss samples the gauss curve
*
* given a position x and a width sigma
*/
template <typename T>
inline T gauss(T sigma, T x) {
T expVal = - .5* pow( x/sigma, 2);
T divider = sqrt(2 * M_PI * pow(sigma, 2));
return (1 / divider) * exp(expVal);
}
/** \brief gausskernel in a vector
*
* length of the vector is 3.5 * sigma on either side
* (gauss is .001 at 3.460871782016046838 times sigma)
* also possible: 5.1 * sigma
* (gauss is 10^-6 at 5.07869511287291208 times sigma)
*/
template <typename T>
const std::vector<T> gausskernel(T sigma) {
double
limit = 3.5;
std::vector<T>
out ( 1 + 2 * (unsigned) ceil( sigma * limit ) );
// update limit as the 1st value on the x axis
limit = -ceil (sigma * limit);
// fill the Gaussian vector, whilst updating the x axis
for (size_t i=0; i<out.size(); i++)
out[i] = gauss<T> (sigma, limit++);
return out;
}
/** \brief owfilter() returns an orthogonal wavelet filter given its name
*
* Filter is returned as a std::vector of doubles.
* Only the scaling filter h is given. The wavelet
* filter g is the QMF of h.
*/
const std::vector <double> owfilter ( const std::string name ) {
// currently the orthogonal wavelet filters available are:
// "Haar" and Daubechies2"
std::vector <double> out;
const double sq2=sqrt(2);
if ( name == "Daubechies2" ) { // Daubechies 4-tap filter (2 vanishing moments)
const double sq3 = sqrt(3);
const double f2 = 4 * sq2;
out = { (1 + sq3) / f2, (3 + sq3) / f2, (3 - sq3) / f2, (1 - sq3) / f2 };
} else {
out = { sq2, sq2 }; // Haar filter
}
return out;
}
} // namespace bis
#endif // BISIMAGE_MATHS_HPP_INCLUDED
| 45.551584 | 148 | 0.443878 | [
"object",
"vector",
"3d"
] |
5272f4c99982abf70cde0b55635f733a6f880fed | 2,624 | cpp | C++ | LeetCode/01/LeetCode145-BinaryTreePostorderTraversal.cpp | Ad147/LeetCode-Solutions | 2ddbaef7387887f030825616cafde87db7d2022e | [
"MIT"
] | null | null | null | LeetCode/01/LeetCode145-BinaryTreePostorderTraversal.cpp | Ad147/LeetCode-Solutions | 2ddbaef7387887f030825616cafde87db7d2022e | [
"MIT"
] | null | null | null | LeetCode/01/LeetCode145-BinaryTreePostorderTraversal.cpp | Ad147/LeetCode-Solutions | 2ddbaef7387887f030825616cafde87db7d2022e | [
"MIT"
] | null | null | null | // LeetCode145-BinaryTreePostorderTraversal.cpp
// Ad147
// Init: 19Mar01
/* -----------------------------------------------------------------------------
145. Binary Tree Postorder Traversal
Hard
Stack, Tree
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
----------------------------------------
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
----------------------------------------
Follow up: Recursive solution is trivial, could you do it iteratively?
----------------------------------------------------------------------------- */
#include <vector>
#include <algorithm> // std::reverse
using std::vector;
/**
* Definition for a binary tree node.
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// Solution-1 ==================================================================
// Runtime: 4 ms, faster than 100.00% of C++ online submissions for Binary Tree Postorder Traversal.
// Memory Usage: 9.2 MB, less than 67.70% of C++ online submissions for Binary Tree Postorder Traversal.
// Algorithm: Iteration.
// Time Complexity: O(n).
// Space Complexity: O(n).
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> ret;
if (!root)
return ret;
vector<TreeNode *> stack{root};
while (!stack.empty())
{
TreeNode *p = stack.back();
stack.pop_back();
ret.push_back(p->val);
if (p->left)
stack.push_back(p->left);
if (p->right)
stack.push_back(p->right);
}
std::reverse(ret.begin(), ret.end());
return ret;
}
};
// Solution-0 ==================================================================
// Runtime: 4 ms, faster than 100.00% of C++ online submissions for Binary Tree Postorder Traversal.
// Memory Usage: 9.4 MB, less than 18.41% of C++ online submissions for Binary Tree Postorder Traversal.
// Algorithm: Recursion.
// Time Complexity: O(n).
// Space Complexity: O(n).
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> ret;
if (!root)
return ret;
postorderTraversal(root, &ret);
return ret;
}
private:
void postorderTraversal(TreeNode *root, vector<int> *ret)
{
if (!root)
return;
postorderTraversal(root->left, ret);
postorderTraversal(root->right, ret);
ret->push_back(root->val);
}
};
| 23.63964 | 104 | 0.516387 | [
"vector"
] |
5280da86a920d118089f376b9236d3d814ee1a17 | 20,887 | hpp | C++ | third_party/CppAD/include/cppad/core/compare.hpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/include/cppad/core/compare.hpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/include/cppad/core/compare.hpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | # ifndef CPPAD_CORE_COMPARE_HPP
# define CPPAD_CORE_COMPARE_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-19 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
/*
-------------------------------------------------------------------------------
$begin Compare$$
$spell
cos
Op
bool
const
$$
$section AD Binary Comparison Operators$$
$head Syntax$$
$icode%b% = %x% %Op% %y%$$
$head Purpose$$
Compares two operands where one of the operands is an
$codei%AD<%Base%>%$$ object.
The comparison has the same interpretation as for
the $icode Base$$ type.
$head Op$$
The operator $icode Op$$ is one of the following:
$table
$bold Op$$ $pre $$ $cnext $bold Meaning$$ $rnext
$code <$$ $cnext is $icode x$$ less than $icode y$$ $rnext
$code <=$$ $cnext is $icode x$$ less than or equal $icode y$$ $rnext
$code >$$ $cnext is $icode x$$ greater than $icode y$$ $rnext
$code >=$$ $cnext is $icode x$$ greater than or equal $icode y$$ $rnext
$code ==$$ $cnext is $icode x$$ equal to $icode y$$ $rnext
$code !=$$ $cnext is $icode x$$ not equal to $icode y$$
$tend
$head x$$
The operand $icode x$$ has prototype
$codei%
const %Type% &%x%
%$$
where $icode Type$$ is $codei%AD<%Base%>%$$, $icode Base$$, or $code int$$.
$head y$$
The operand $icode y$$ has prototype
$codei%
const %Type% &%y%
%$$
where $icode Type$$ is $codei%AD<%Base%>%$$, $icode Base$$, or $code int$$.
$head b$$
The result $icode b$$ has type
$codei%
bool %b%
%$$
$head Operation Sequence$$
The result of this operation is a $code bool$$ value
(not an $cref/AD of Base/glossary/AD of Base/$$ object).
Thus it will not be recorded as part of an
AD of $icode Base$$
$cref/operation sequence/glossary/Operation/Sequence/$$.
$pre
$$
For example, suppose
$icode x$$ and $icode y$$ are $codei%AD<%Base%>%$$ objects,
the tape corresponding to $codei%AD<%Base%>%$$ is recording,
$icode b$$ is true,
and the subsequent code is
$codei%
if( %b% )
%y% = cos(%x%);
else
%y% = sin(%x%);
%$$
only the assignment $icode%y% = cos(%x%)%$$ is recorded on the tape
(if $icode x$$ is a $cref/parameter/glossary/Parameter/$$,
nothing is recorded).
The $cref CompareChange$$ function can yield
some information about changes in comparison operation results.
You can use $cref CondExp$$ to obtain comparison operations
that depends on the
$cref/independent variable/glossary/Tape/Independent Variable/$$
values with out re-taping the AD sequence of operations.
$head Assumptions$$
If one of the $icode Op$$ operators listed above
is used with an $codei%AD<%Base%>%$$ object,
it is assumed that the same operator is supported by the base type
$icode Base$$.
$head Example$$
$children%
example/general/compare.cpp
%$$
The file
$cref compare.cpp$$
contains an example and test of these operations.
$end
-------------------------------------------------------------------------------
*/
// BEGIN CppAD namespace
namespace CppAD {
// -------------------------------- < --------------------------
template <class Base>
CPPAD_INLINE_FRIEND_TEMPLATE_FUNCTION
bool operator < (const AD<Base> &left , const AD<Base> &right)
{ bool result = (left.value_ < right.value_);
//
// check if we are recording compare operators
local::ADTape<Base> *tape = AD<Base>::tape_ptr();
if( tape == CPPAD_NULL )
return result;
if( ! tape->Rec_.get_record_compare() )
return result;
tape_id_t tape_id = tape->id_;
// tape_id cannot match the default value for tape_id_; i.e., 0
CPPAD_ASSERT_UNKNOWN( tape_id > 0 );
// check if left and right tapes match
bool match_left = left.tape_id_ == tape_id;
bool match_right = right.tape_id_ == tape_id;
// check if left and right are dynamic parameters
bool dyn_left = match_left & (left.ad_type_ == dynamic_enum);
bool dyn_right = match_right & (right.ad_type_ == dynamic_enum);
// check if left and right are variables
bool var_left = match_left & (left.ad_type_ != dynamic_enum);
bool var_right = match_right & (right.ad_type_ != dynamic_enum);
CPPAD_ASSERT_KNOWN(
left.tape_id_ == right.tape_id_ || ! match_left || ! match_right ,
"< : AD variables or dynamic parameters on different threads."
);
if( var_left )
{ if( var_right )
{ // variable < variable
if( result )
{ tape->Rec_.PutOp(local::LtvvOp);
tape->Rec_.PutArg(left.taddr_, right.taddr_);
}
else
{ tape->Rec_.PutOp(local::LevvOp);
tape->Rec_.PutArg(right.taddr_, left.taddr_);
}
}
else
{ // variable < parameter
addr_t p = right.taddr_;
if( ! dyn_right )
p = tape->Rec_.put_con_par(right.value_);
if( result )
{ tape->Rec_.PutOp(local::LtvpOp);
tape->Rec_.PutArg(left.taddr_, p);
}
else
{ tape->Rec_.PutOp(local::LepvOp);
tape->Rec_.PutArg(p, left.taddr_);
}
}
}
else if ( var_right )
{ // parameter < variable
addr_t p = left.taddr_;
if( ! dyn_left )
p = tape->Rec_.put_con_par(left.value_);
if( result )
{ tape->Rec_.PutOp(local::LtpvOp);
tape->Rec_.PutArg(p, right.taddr_);
}
else
{ tape->Rec_.PutOp(local::LevpOp);
tape->Rec_.PutArg(right.taddr_, p);
}
}
else if( dyn_left | dyn_right )
{ // parameter < parameter
addr_t arg0 = left.taddr_;
addr_t arg1 = right.taddr_;
if( ! dyn_left )
arg0 = tape->Rec_.put_con_par(left.value_);
if( ! dyn_right )
arg1 = tape->Rec_.put_con_par(right.value_);
//
if( result )
{ tape->Rec_.PutOp(local::LtppOp);
tape->Rec_.PutArg(arg0, arg1);
}
else
{ tape->Rec_.PutOp(local::LeppOp);
tape->Rec_.PutArg(arg1, arg0);
}
}
return result;
}
// convert other cases into the case above
CPPAD_FOLD_BOOL_VALUED_BINARY_OPERATOR(<)
// -------------------------------- <= --------------------------
template <class Base>
CPPAD_INLINE_FRIEND_TEMPLATE_FUNCTION
bool operator <= (const AD<Base> &left , const AD<Base> &right)
{ bool result = (left.value_ <= right.value_);
//
// check if we are recording compare operators
local::ADTape<Base> *tape = AD<Base>::tape_ptr();
if( tape == CPPAD_NULL )
return result;
if( ! tape->Rec_.get_record_compare() )
return result;
tape_id_t tape_id = tape->id_;
// tape_id cannot match the default value for tape_id_; i.e., 0
CPPAD_ASSERT_UNKNOWN( tape_id > 0 );
// check if left and right tapes match
bool match_left = left.tape_id_ == tape_id;
bool match_right = right.tape_id_ == tape_id;
// check if left and right are dynamic parameters
bool dyn_left = match_left & (left.ad_type_ == dynamic_enum);
bool dyn_right = match_right & (right.ad_type_ == dynamic_enum);
// check if left and right are variables
bool var_left = match_left & (left.ad_type_ != dynamic_enum);
bool var_right = match_right & (right.ad_type_ != dynamic_enum);
CPPAD_ASSERT_KNOWN(
left.tape_id_ == right.tape_id_ || ! match_left || ! match_right ,
"<= : AD variables or dynamic parameters on different threads."
);
if( var_left )
{ if( var_right )
{ // variable <= variable
if( result )
{ tape->Rec_.PutOp(local::LevvOp);
tape->Rec_.PutArg(left.taddr_, right.taddr_);
}
else
{ tape->Rec_.PutOp(local::LtvvOp);
tape->Rec_.PutArg(right.taddr_, left.taddr_);
}
}
else
{ // variable <= parameter
addr_t p = right.taddr_;
if( ! dyn_right )
p = tape->Rec_.put_con_par(right.value_);
if( result )
{ tape->Rec_.PutOp(local::LevpOp);
tape->Rec_.PutArg(left.taddr_, p);
}
else
{ tape->Rec_.PutOp(local::LtpvOp);
tape->Rec_.PutArg(p, left.taddr_);
}
}
}
else if ( var_right )
{ // parameter <= variable
addr_t p = left.taddr_;
if( ! dyn_left )
p = tape->Rec_.put_con_par(left.value_);
if( result )
{ tape->Rec_.PutOp(local::LepvOp);
tape->Rec_.PutArg(p, right.taddr_);
}
else
{ tape->Rec_.PutOp(local::LtvpOp);
tape->Rec_.PutArg(right.taddr_, p);
}
}
else if( dyn_left | dyn_right )
{ // parameter <= parameter
addr_t arg0 = left.taddr_;
addr_t arg1 = right.taddr_;
if( ! dyn_left )
arg0 = tape->Rec_.put_con_par(left.value_);
if( ! dyn_right )
arg1 = tape->Rec_.put_con_par(right.value_);
//
if( result )
{ tape->Rec_.PutOp(local::LeppOp);
tape->Rec_.PutArg(arg0, arg1);
}
else
{ tape->Rec_.PutOp(local::LtppOp);
tape->Rec_.PutArg(arg1, arg0);
}
}
return result;
}
// convert other cases into the case above
CPPAD_FOLD_BOOL_VALUED_BINARY_OPERATOR(<=)
// -------------------------------- > --------------------------
template <class Base>
CPPAD_INLINE_FRIEND_TEMPLATE_FUNCTION
bool operator > (const AD<Base> &left , const AD<Base> &right)
{ bool result = (left.value_ > right.value_);
//
// check if we are recording compare operators
local::ADTape<Base> *tape = AD<Base>::tape_ptr();
if( tape == CPPAD_NULL )
return result;
if( ! tape->Rec_.get_record_compare() )
return result;
tape_id_t tape_id = tape->id_;
// tape_id cannot match the default value for tape_id_; i.e., 0
CPPAD_ASSERT_UNKNOWN( tape_id > 0 );
// check if left and right tapes match
bool match_left = left.tape_id_ == tape_id;
bool match_right = right.tape_id_ == tape_id;
// check if left and right are dynamic parameters
bool dyn_left = match_left & (left.ad_type_ == dynamic_enum);
bool dyn_right = match_right & (right.ad_type_ == dynamic_enum);
// check if left and right are variables
bool var_left = match_left & (left.ad_type_ != dynamic_enum);
bool var_right = match_right & (right.ad_type_ != dynamic_enum);
CPPAD_ASSERT_KNOWN(
left.tape_id_ == right.tape_id_ || ! match_left || ! match_right ,
"> : AD variables or dynamic parameters on different threads."
);
if( var_left )
{ if( var_right )
{ // variable > variable
if( result )
{ tape->Rec_.PutOp(local::LtvvOp);
tape->Rec_.PutArg(right.taddr_, left.taddr_);
}
else
{ tape->Rec_.PutOp(local::LevvOp);
tape->Rec_.PutArg(left.taddr_, right.taddr_);
}
}
else
{ // variable > parameter
addr_t p = right.taddr_;
if( ! dyn_right )
p = tape->Rec_.put_con_par(right.value_);
if( result )
{ tape->Rec_.PutOp(local::LtpvOp);
tape->Rec_.PutArg(p, left.taddr_);
}
else
{ tape->Rec_.PutOp(local::LevpOp);
tape->Rec_.PutArg(left.taddr_, p);
}
}
}
else if ( var_right )
{ // parameter > variable
addr_t p = left.taddr_;
if( ! dyn_left )
p = tape->Rec_.put_con_par(left.value_);
if( result )
{ tape->Rec_.PutOp(local::LtvpOp);
tape->Rec_.PutArg(right.taddr_, p);
}
else
{ tape->Rec_.PutOp(local::LepvOp);
tape->Rec_.PutArg(p, right.taddr_);
}
}
else if( dyn_left | dyn_right )
{ // parameter > parameter
addr_t arg0 = left.taddr_;
addr_t arg1 = right.taddr_;
if( ! dyn_left )
arg0 = tape->Rec_.put_con_par(left.value_);
if( ! dyn_right )
arg1 = tape->Rec_.put_con_par(right.value_);
//
if( result )
{ tape->Rec_.PutOp(local::LtppOp);
tape->Rec_.PutArg(arg1, arg0);
}
else
{ tape->Rec_.PutOp(local::LeppOp);
tape->Rec_.PutArg(arg0, arg1);
}
}
return result;
}
// convert other cases into the case above
CPPAD_FOLD_BOOL_VALUED_BINARY_OPERATOR(>)
// -------------------------------- >= --------------------------
template <class Base>
CPPAD_INLINE_FRIEND_TEMPLATE_FUNCTION
bool operator >= (const AD<Base> &left , const AD<Base> &right)
{ bool result = (left.value_ >= right.value_);
//
// check if we are recording compare operators
local::ADTape<Base> *tape = AD<Base>::tape_ptr();
if( tape == CPPAD_NULL )
return result;
if( ! tape->Rec_.get_record_compare() )
return result;
tape_id_t tape_id = tape->id_;
// tape_id cannot match the default value for tape_id_; i.e., 0
CPPAD_ASSERT_UNKNOWN( tape_id > 0 );
// check if left and right tapes match
bool match_left = left.tape_id_ == tape_id;
bool match_right = right.tape_id_ == tape_id;
// check if left and right are dynamic parameters
bool dyn_left = match_left & (left.ad_type_ == dynamic_enum);
bool dyn_right = match_right & (right.ad_type_ == dynamic_enum);
// check if left and right are variables
bool var_left = match_left & (left.ad_type_ != dynamic_enum);
bool var_right = match_right & (right.ad_type_ != dynamic_enum);
CPPAD_ASSERT_KNOWN(
left.tape_id_ == right.tape_id_ || ! match_left || ! match_right ,
">= : AD variables or dynamic parameters on different threads."
);
if( var_left )
{ if( var_right )
{ // variable >= variable
if( result )
{ tape->Rec_.PutOp(local::LevvOp);
tape->Rec_.PutArg(right.taddr_, left.taddr_);
}
else
{ tape->Rec_.PutOp(local::LtvvOp);
tape->Rec_.PutArg(left.taddr_, right.taddr_);
}
}
else
{ // variable >= parameter
addr_t p = right.taddr_;
if( ! dyn_right )
p = tape->Rec_.put_con_par(right.value_);
if( result )
{ tape->Rec_.PutOp(local::LepvOp);
tape->Rec_.PutArg(p, left.taddr_);
}
else
{ tape->Rec_.PutOp(local::LtvpOp);
tape->Rec_.PutArg(left.taddr_, p);
}
}
}
else if ( var_right )
{ // parameter >= variable
addr_t p = left.taddr_;
if( ! dyn_left )
p = tape->Rec_.put_con_par(left.value_);
if( result )
{ tape->Rec_.PutOp(local::LevpOp);
tape->Rec_.PutArg(right.taddr_, p);
}
else
{ tape->Rec_.PutOp(local::LtpvOp);
tape->Rec_.PutArg(p, right.taddr_);
}
}
else if( dyn_left | dyn_right )
{ // parameter >= parameter
addr_t arg0 = left.taddr_;
addr_t arg1 = right.taddr_;
if( ! dyn_left )
arg0 = tape->Rec_.put_con_par(left.value_);
if( ! dyn_right )
arg1 = tape->Rec_.put_con_par(right.value_);
//
if( result )
{ tape->Rec_.PutOp(local::LeppOp);
tape->Rec_.PutArg(arg1, arg0);
}
else
{ tape->Rec_.PutOp(local::LtppOp);
tape->Rec_.PutArg(arg0, arg1);
}
}
return result;
}
// convert other cases into the case above
CPPAD_FOLD_BOOL_VALUED_BINARY_OPERATOR(>=)
// -------------------------------- == -------------------------
template <class Base>
CPPAD_INLINE_FRIEND_TEMPLATE_FUNCTION
bool operator == (const AD<Base> &left , const AD<Base> &right)
{ bool result = (left.value_ == right.value_);
//
// check if we are recording compare operators
local::ADTape<Base> *tape = AD<Base>::tape_ptr();
if( tape == CPPAD_NULL )
return result;
if( ! tape->Rec_.get_record_compare() )
return result;
tape_id_t tape_id = tape->id_;
// tape_id cannot match the default value for tape_id_; i.e., 0
CPPAD_ASSERT_UNKNOWN( tape_id > 0 );
// check if left and right tapes match
bool match_left = left.tape_id_ == tape_id;
bool match_right = right.tape_id_ == tape_id;
// check if left and right are dynamic parameters
bool dyn_left = match_left & (left.ad_type_ == dynamic_enum);
bool dyn_right = match_right & (right.ad_type_ == dynamic_enum);
// check if left and right are variables
bool var_left = match_left & (left.ad_type_ != dynamic_enum);
bool var_right = match_right & (right.ad_type_ != dynamic_enum);
CPPAD_ASSERT_KNOWN(
left.tape_id_ == right.tape_id_ || ! match_left || ! match_right ,
"==: AD variables or dynamic parameters on different threads."
);
//
tape->Rec_.comp_eq(
var_left, var_right, dyn_left, dyn_right, left, right, result
);
//
return result;
}
// convert other cases into the case above
CPPAD_FOLD_BOOL_VALUED_BINARY_OPERATOR(==)
// -------------------------------- != -------------------------
template <class Base>
CPPAD_INLINE_FRIEND_TEMPLATE_FUNCTION
bool operator != (const AD<Base> &left , const AD<Base> &right)
{ bool result = (left.value_ != right.value_);
//
// check if we are recording compare operators
local::ADTape<Base> *tape = AD<Base>::tape_ptr();
if( tape == CPPAD_NULL )
return result;
if( ! tape->Rec_.get_record_compare() )
return result;
tape_id_t tape_id = tape->id_;
// tape_id cannot match the default value for tape_id_; i.e., 0
CPPAD_ASSERT_UNKNOWN( tape_id > 0 );
// check if left and right tapes match
bool match_left = left.tape_id_ == tape_id;
bool match_right = right.tape_id_ == tape_id;
// check if left and right are dynamic parameters
bool dyn_left = match_left & (left.ad_type_ == dynamic_enum);
bool dyn_right = match_right & (right.ad_type_ == dynamic_enum);
// check if left and right are variables
bool var_left = match_left & (left.ad_type_ != dynamic_enum);
bool var_right = match_right & (right.ad_type_ != dynamic_enum);
CPPAD_ASSERT_KNOWN(
left.tape_id_ == right.tape_id_ || ! match_left || ! match_right ,
"!=: AD variables or dynamic parameters on different threads."
);
if( var_left )
{ if( var_right )
{ // variable == variable
tape->Rec_.PutArg(left.taddr_, right.taddr_);
if( result )
tape->Rec_.PutOp(local::NevvOp);
else
tape->Rec_.PutOp(local::EqvvOp);
}
else
{ // variable == parameter
addr_t p = right.taddr_;
if( ! dyn_right )
p = tape->Rec_.put_con_par(right.value_);
tape->Rec_.PutArg(p, left.taddr_);
if( result )
tape->Rec_.PutOp(local::NepvOp);
else
tape->Rec_.PutOp(local::EqpvOp);
}
}
else if ( var_right )
{ // parameter == variable
addr_t p = left.taddr_;
if( ! dyn_left )
p = tape->Rec_.put_con_par(left.value_);
tape->Rec_.PutArg(p, right.taddr_);
if( result )
tape->Rec_.PutOp(local::NepvOp);
else
tape->Rec_.PutOp(local::EqpvOp);
}
else if( dyn_left | dyn_right )
{ // parameter == parameter
addr_t arg0 = left.taddr_;
addr_t arg1 = right.taddr_;
if( ! dyn_left )
arg0 = tape->Rec_.put_con_par(left.value_);
if( ! dyn_right )
arg1 = tape->Rec_.put_con_par(right.value_);
//
tape->Rec_.PutArg(arg0, arg1);
if( result )
tape->Rec_.PutOp(local::NeppOp);
else
tape->Rec_.PutOp(local::EqppOp);
}
return result;
}
// convert other cases into the case above
CPPAD_FOLD_BOOL_VALUED_BINARY_OPERATOR(!=)
} // END CppAD namespace
# endif
| 32.841195 | 79 | 0.563125 | [
"object"
] |
52821f84d13b7b00ce64002b6b6e36a8cb30fc51 | 4,024 | hh | C++ | libs/vdt4/vdt_rwis_file_reader.hh | OSADP/Pikalert-Vehicle-Data-Translator- | 295da604408f6f13af0301b55476a81311459386 | [
"Apache-2.0"
] | 2 | 2020-06-03T15:59:50.000Z | 2020-12-21T11:11:57.000Z | libs/vdt4/vdt_rwis_file_reader.hh | OSADP/Pikalert-Vehicle-Data-Translator- | 295da604408f6f13af0301b55476a81311459386 | [
"Apache-2.0"
] | null | null | null | libs/vdt4/vdt_rwis_file_reader.hh | OSADP/Pikalert-Vehicle-Data-Translator- | 295da604408f6f13af0301b55476a81311459386 | [
"Apache-2.0"
] | 2 | 2019-10-02T06:47:23.000Z | 2020-02-02T18:32:23.000Z | //==============================================================================
//
// (c) Copyright, 2012 University Corporation for Atmospheric Research (UCAR).
// All rights reserved.
//
// File: $RCSfile: vdt_rwis_file_reader.hh,v $
// Version: $Revision: 1.1 $ Dated: $Date: 2013-04-10 17:43:27 $
//
//==============================================================================
/**
*
* @file vdt_rwis_file_reader.hh
*
* @class vdt_rwis_file_reader
*
* VDT RWIS (Road Weather Information System) class
*
*/
#ifndef VDT_RWIS_FILE_READER_HH
#define VDT_RWIS_FILE_READER_HH
#include "vdt_nc_file_reader.hh"
//ED why is vdt_probe_message.hh needed here?
#include "vdt_probe_message.hh"
#include "vdt_surface_observation.hh"
#include <vector>
using namespace std;
class vdt_rwis_file_reader : public vdt_nc_file_reader
{
public:
/** @brief number of records netcdf dimension name */
const static char* REC_NUM;
/** @brief station name length netcdf dimension name */
const static char* STN_NAME_LEN;
/** @brief station netcdf variable name */
const static char* STATION_NAME;
/** @brief latitude netcdf variable name */
const static char* LATITUDE;
/** @brief longitude netcdf variable name */
const static char* LONGITUDE;
/** @brief elevation netcdf variable name */
const static char* ELEVATION;
/** @brief observation time netcdf variable name */
const static char* OBS_TIME;
/** @brief air temperature netcdf variable name */
const static char* AIR_TEMP;
/** @brief air temperature QC netcdf variable name */
const static char* AIR_TEMP_DD;
/** @brief surface temperature netcdf variable name */
const static char* SURFACE_TEMP;
/** @brief pressure netcdf variable name */
const static char* PRESS;
/** @brief pressure QC netcdf variable name */
const static char* PRESS_DD;
/** @brief dew point temperature netcdf variable name */
const static char* DEW_TEMP;
/** @brief dew point temperature QC netcdf variable name */
const static char* DEW_TEMP_DD;
/** @brief hourly precipitation amount netcdf variable name */
const static char* HOURLY_PRECIP;
/** @brief hourly precipitation amount QC netcdf variable name */
const static char* HOURLY_PRECIP_DD;
/** @brief prevailing visibility netcdf variable name */
const static char* PREVAIL_VIS;
/** @brief prevailing visibility netcdf QC variable name */
const static char* PREVAIL_VIS_DD;
/** @brief wind direction netcdf variable name */
const static char* WIND_DIR;
/** @brief wind direction netcdf QC variable name */
const static char* WIND_DIR_DD;
/** @brief wind speed netcdf variable name */
const static char* WIND_SPEED;
/** @brief wind speed netcdf QC variable name */
const static char* WIND_SPEED_DD;
/** @brief wind gust netcdf variable name */
const static char* WIND_GUST;
/** @brief wind gust netcdf QC variable name */
const static char* WIND_GUST_DD;
/** @brief fill attribute netcdf variable name */
const static char* FILL_ATTR;
/** @brief pressWx length dimension */
const static char* MAX_WEATHER_LEN;
/** @brief present weather dscription variable */
const static char* PRES_WX;
/** @brief Road State - sensor 1 variable */
const static char* ROAD_STATE_1;
/**
* @brief constructor
* @param[in] fpath file path to netcdf file
* @param[in] logg log file
*/
vdt_rwis_file_reader(const char* fpath) : vdt_nc_file_reader(fpath) {};
~vdt_rwis_file_reader();
/**
* @brief gets surface observations
* @param[out] obs vector of vdt surface observations
* @return 0 on success, -1 on failure
*/
int get_rwis(vector<vdt_surface_observation>& obs);
/**
* @brief gets surface observations
* @param[out] obs vector of vdt surface observations
* @return 0 on success, -1 on failure
*/
int get_num_rwis_obs()
{
return num_rwis_obs;
}
private:
int num_rwis_obs;
};
#endif /* VDT_RWIS_FILE_READER_HH */
| 26.649007 | 80 | 0.672714 | [
"vector"
] |
528235ea574d5f52b43ee1efdff665409cfe0f6d | 879 | hpp | C++ | source/lightspace/public/model_parser.hpp | gitbetter/Lightspace | b00a29e2aac64cfac87ca30d2d053559d84289df | [
"MIT"
] | null | null | null | source/lightspace/public/model_parser.hpp | gitbetter/Lightspace | b00a29e2aac64cfac87ca30d2d053559d84289df | [
"MIT"
] | null | null | null | source/lightspace/public/model_parser.hpp | gitbetter/Lightspace | b00a29e2aac64cfac87ca30d2d053559d84289df | [
"MIT"
] | null | null | null | #pragma once
#include "common.hpp"
#include "tensor.hpp"
#include <fstream>
#include <vector>
#include <map>
namespace ls {
enum class model_parse_status
{
SUCCESS, FAIL
};
struct model_parse_data
{
unsigned int lines_ignored;
std::vector<f_point> vertices;
std::map<std::string, group_ptr> groups;
group_ptr root_group;
model_parse_data();
};
struct model_parse_error
{
unsigned int line_number{ 0 };
std::string message;
};
struct model_parse_result
{
model_parse_status status{ model_parse_status::FAIL };
std::unique_ptr<model_parse_data> data;
std::unique_ptr<model_parse_error> error;
group_ptr to_shape_group() const;
};
struct model_parser
{
static model_parse_result obj( std::ifstream& f );
};
}
| 19.108696 | 62 | 0.623436 | [
"vector"
] |
528436389189bb5307c30c4de7915c806ed9d61f | 682 | cpp | C++ | Sasuke_CodeWar#1/BaiG.cpp | trannguyenhan01092000/WorkspaceAlgorithm | 6ad3f12d55c7675184a8c15c5388ee8422e15a16 | [
"MIT"
] | 8 | 2020-11-26T03:36:49.000Z | 2020-11-28T14:33:07.000Z | Sasuke_CodeWar#1/BaiG.cpp | trannguyenhan/WorkspaceAlgorithm | 6ad3f12d55c7675184a8c15c5388ee8422e15a16 | [
"MIT"
] | null | null | null | Sasuke_CodeWar#1/BaiG.cpp | trannguyenhan/WorkspaceAlgorithm | 6ad3f12d55c7675184a8c15c5388ee8422e15a16 | [
"MIT"
] | null | null | null | #include <iostream>
#include<vector>
#include<algorithm>
#include<fstream>
#include<math.h>
#include<sstream>
using namespace std;
bool possibleName(string name, string typed){
int lensName = name.length();
int lensTyped = typed.length();
vector<int> a;
int i=0, j=0;
while(j<lensTyped){
if(name[i] == typed[j]){
a.push_back(name[i]);
i++;
j++;
} else {
if(a.empty()){ return false; }
else {
if(typed[j] == a.back()){
j++;
} else { return false; }
}
}
}
return true;
}
int main()
{
return 0;
}
| 16.634146 | 45 | 0.475073 | [
"vector"
] |
528c6122cb28265cc73a0575be347bde9ce7a292 | 377 | cpp | C++ | BaekJoon/KOI/KOI2019-1/Stick/Stick.cpp | radii-dev/ps_study | a638156430b8c2717a3d6694324a6bb3306d9016 | [
"MIT"
] | null | null | null | BaekJoon/KOI/KOI2019-1/Stick/Stick.cpp | radii-dev/ps_study | a638156430b8c2717a3d6694324a6bb3306d9016 | [
"MIT"
] | null | null | null | BaekJoon/KOI/KOI2019-1/Stick/Stick.cpp | radii-dev/ps_study | a638156430b8c2717a3d6694324a6bb3306d9016 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int stick(int len) {
vector<int> see;
int tmp;
for (int i = 0; i < len; i++) {
cin >> tmp;
if (!see.empty()) {
int j = see.size() - 1;
while (j >= 0 && see.at(j--) <= tmp)
see.pop_back();
}
see.push_back(tmp);
}
return see.size();
}
int main() {
int len;
cin >> len;
cout << stick(len);
} | 14.5 | 39 | 0.541114 | [
"vector"
] |
528c8c88d2f23373bec2e942e8316ce75979dd5a | 6,364 | cpp | C++ | ShaderParser/DescriptorSetInstantiation.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | 3 | 2018-05-17T08:39:39.000Z | 2020-12-09T13:20:26.000Z | ShaderParser/DescriptorSetInstantiation.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | null | null | null | ShaderParser/DescriptorSetInstantiation.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | 1 | 2021-11-14T08:50:15.000Z | 2021-11-14T08:50:15.000Z | // Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "DescriptorSetInstantiation.h"
#include "NodeGraphSignature.h"
#include "../RenderCore/Assets/PredefinedCBLayout.h"
#include "../RenderCore/ShaderLangUtil.h"
#include "../Utility/StringUtils.h"
#include "../Utility/IteratorUtils.h"
#include <set>
#include <unordered_map>
namespace ShaderSourceParser
{
TypeDescriptor CalculateTypeDescriptor(StringSection<> type)
{
// HLSL keywords are not case sensitive. We could assume that
// a type name that does not begin with one of the scalar type
// prefixes is a global resource (like a texture, etc). This
// should provide some flexibility with new DX12 types, and perhaps
// allow for manipulating custom "interface" types...?
//
// However, that isn't going to work well with struct types (which
// can be contained with cbuffers and be passed to functions like
// scalars)
//
// const char* scalarTypePrefixes[] =
// {
// "bool", "int", "uint", "half", "float", "double"
// };
//
// Note that we only check the prefix -- to catch variations on
// texture and RWTexture (and <> arguments like Texture2D<float4>)
const char* resourceTypePrefixes[] =
{
"cbuffer", "tbuffer",
"StructuredBuffer", "Buffer", "ByteAddressBuffer", "AppendStructuredBuffer",
"RWBuffer", "RWByteAddressBuffer", "RWStructuredBuffer",
"RWTexture", // RWTexture1D, RWTexture1DArray, RWTexture2D, RWTexture2DArray, RWTexture3D
"texture", // Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture2DMS, Texture2DMSArray, Texture3D, TextureCube, TextureCubeArray
// special .fx file types:
// "BlendState", "DepthStencilState", "DepthStencilView", "RasterizerState", "RenderTargetView",
};
// note -- some really special function signature-only: InputPatch, OutputPatch, LineStream, TriangleStream, PointStream
for (unsigned c=0; c<dimof(resourceTypePrefixes); ++c)
if (XlBeginsWithI(type, MakeStringSection(resourceTypePrefixes[c])))
return TypeDescriptor::Resource;
const char* samplerTypePrefixes[] =
{
"sampler", // SamplerState, SamplerComparisonState
};
for (unsigned c=0; c<dimof(samplerTypePrefixes); ++c)
if (XlBeginsWithI(type, MakeStringSection(samplerTypePrefixes[c])))
return TypeDescriptor::Sampler;
return TypeDescriptor::Constant;
}
static std::string MakeGlobalName(const std::string& str)
{
auto i = str.find('.');
if (i != std::string::npos)
return str.substr(i+1);
return str;
}
std::shared_ptr<RenderCore::Assets::PredefinedDescriptorSetLayout> MakeMaterialDescriptorSet(
IteratorRange<const GraphLanguage::NodeGraphSignature::Parameter*> captures,
RenderCore::ShaderLanguage shaderLanguage,
std::ostream& warningStream)
{
std::vector<RenderCore::Assets::PredefinedDescriptorSetLayout::Resource> srvs;
std::vector<RenderCore::Assets::PredefinedDescriptorSetLayout::Sampler> samplers;
using NameAndType = RenderCore::Assets::PredefinedCBLayout::NameAndType;
struct WorkingCB
{
std::vector<NameAndType> _cbElements;
ParameterBox _defaults;
};
std::unordered_map<std::string, WorkingCB> workingCBs;
std::set<std::string> texturesAlreadyStored;
// hack -- skip DiffuseTexture and NormalsTexture, because these are provided by the system headers
// texturesAlreadyStored.insert("DiffuseTexture");
// texturesAlreadyStored.insert("NormalsTexture");
for (const auto&c : captures) {
auto type = CalculateTypeDescriptor(c._type);
if (type != TypeDescriptor::Constant) {
auto globalName = MakeGlobalName(c._name);
if (texturesAlreadyStored.find(globalName) == texturesAlreadyStored.end()) {
texturesAlreadyStored.insert(globalName);
// This capture must be either an srv or a sampler
if (c._direction == GraphLanguage::ParameterDirection::In) {
if (type == TypeDescriptor::Resource) {
srvs.push_back({globalName, {}});
} else
samplers.push_back({globalName, {}});
}
}
continue;
}
auto fmt = RenderCore::ShaderLangTypeNameAsTypeDesc(c._type);
if (fmt._type == ImpliedTyping::TypeCat::Void) {
warningStream << "\t// Could not convert type (" << c._type << ") to shader language type for capture (" << c._name << "). Skipping cbuffer entry." << std::endl;
continue;
}
std::string cbName, memberName;
auto i = c._name.find('.');
if (i != std::string::npos) {
cbName = c._name.substr(0, i);
memberName = c._name.substr(i+1);
} else {
cbName = "BasicMaterialConstants";
memberName = c._name;
}
auto cbi = workingCBs.find(cbName);
if (cbi == workingCBs.end())
cbi = workingCBs.insert(std::make_pair(cbName, WorkingCB{})).first;
cbi->second._cbElements.push_back(NameAndType{ memberName, fmt });
if (!c._default.empty())
cbi->second._defaults.SetParameter(
MakeStringSection(memberName).Cast<utf8>(),
MakeStringSection(c._default));
}
auto result = std::make_shared<RenderCore::Assets::PredefinedDescriptorSetLayout>();
result->_resources = std::move(srvs);
result->_samplers = std::move(samplers);
for (auto&cb:workingCBs) {
// Sort first in alphabetical order, and then optimize for
// type packing. This ensures that we get the same output layout for a given
// input, regardless of the input's original ordering.
std::sort(
cb.second._cbElements.begin(), cb.second._cbElements.end(),
[](const NameAndType& lhs, const NameAndType& rhs) {
return lhs._name < rhs._name;
});
RenderCore::Assets::PredefinedCBLayout::OptimizeElementOrder(MakeIteratorRange(cb.second._cbElements), shaderLanguage);
auto layout = std::make_shared<RenderCore::Assets::PredefinedCBLayout>(
MakeIteratorRange(cb.second._cbElements), cb.second._defaults);
if (!layout->_elements.empty())
result->_constantBuffers.emplace_back(
RenderCore::Assets::PredefinedDescriptorSetLayout::ConstantBuffer {
cb.first,
std::move(layout)
});
}
return result;
}
}
| 38.107784 | 165 | 0.682747 | [
"vector"
] |
528ffed0d37fe090697ea65c7ea7a1e9ff9207b7 | 4,142 | cc | C++ | performance/board_get_set/BoardGetSet.cc | starpentagon/realcore | 64dd67d5b05f146f4cde3540d9be76303262e89c | [
"MIT"
] | null | null | null | performance/board_get_set/BoardGetSet.cc | starpentagon/realcore | 64dd67d5b05f146f4cde3540d9be76303262e89c | [
"MIT"
] | 10 | 2017-02-22T12:17:49.000Z | 2017-03-10T00:15:31.000Z | performance/board_get_set/BoardGetSet.cc | starpentagon/realcore | 64dd67d5b05f146f4cde3540d9be76303262e89c | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <array>
#include <boost/program_options.hpp>
#include "Move.h"
#include "BitBoard.h"
using namespace std;
using namespace boost;
using namespace boost::program_options;
using namespace realcore;
int main(int argc, char* argv[])
{
// オプション設定
options_description option;
option.add_options()
("count,c", value<uint64_t>()->default_value(100 * 10000), "反復回数(default: 100万回)")
("help,h", "ヘルプを表示");
variables_map arg_map;
store(parse_command_line(argc, argv, option), arg_map);
if(arg_map.count("help")){
cout << "Usage: " << argv[0] << " [options]" << endl;
cout << option;
cout << endl;
cout << "Repeat the following procedure on specified times:" << endl;
cout << " 1. Construct Board object" << endl;
cout << " 2. SetState BlackStone along with the shuffled list" << endl;
cout << " 3. SetState WhiteStone along with the shuffled list" << endl;
cout << " 4. SetState BlackStone/WhiteStone alternately along with the shuffled list" << endl;
cout << " 5. SetState OpenPosition along with the shuffled list" << endl;
cout << " 6. GetState along with the shuffled list" << endl;
cout << endl;
return 0;
}
const uint64_t iteration_count = arg_map["count"].as<uint64_t>();
auto in_board_move = GetAllInBoardMove();
// SetState: kBlackStone
shuffle(in_board_move.begin(), in_board_move.end(), mt19937_64());
{
auto start_time = chrono::system_clock::now();
for(size_t i=0; i<iteration_count; i++)
{
BitBoard bit_board;
for(const auto move : in_board_move){
bit_board.SetState<kBlackStone>(move);
}
}
auto elapsed_time = chrono::system_clock::now() - start_time;
cout << "SetState<kBlackStone>:\t";
cout << chrono::duration_cast<chrono::milliseconds>(elapsed_time).count();
cout << " ms" << endl;
}
{
auto start_time = chrono::system_clock::now();
for(size_t i=0; i<iteration_count; i++)
{
BitBoard bit_board;
for(const auto move : in_board_move){
bit_board.SetState<kWhiteStone>(move);
}
}
auto elapsed_time = chrono::system_clock::now() - start_time;
cout << "SetState<kWhiteStone>:\t";
cout << chrono::duration_cast<chrono::milliseconds>(elapsed_time).count();
cout << " ms" << endl;
}
{
auto start_time = chrono::system_clock::now();
PositionState state = kBlackStone;
for(size_t i=0; i<iteration_count; i++)
{
BitBoard bit_board;
for(const auto move : in_board_move){
bit_board.SetState(move, state);
state = static_cast<PositionState>(3 - state);
}
}
auto elapsed_time = chrono::system_clock::now() - start_time;
cout << "SetState(Alternately):\t";
cout << chrono::duration_cast<chrono::milliseconds>(elapsed_time).count();
cout << " ms" << endl;
}
{
auto start_time = chrono::system_clock::now();
for(size_t i=0; i<iteration_count; i++)
{
BitBoard bit_board;
for(const auto move : in_board_move){
bit_board.SetState<kOpenPosition>(move);
}
}
auto elapsed_time = chrono::system_clock::now() - start_time;
cout << "SetState<kOpenPosition>:\t";
cout << chrono::duration_cast<chrono::milliseconds>(elapsed_time).count();
cout << " ms" << endl;
}
{
// 状態取得のみだと最適化された際に不要な参照として削除されることがあるため簡単な集計&結果表示を行う
auto start_time = chrono::system_clock::now();
std::array<uint64_t, 4> state_count{{0}};
for(size_t i=0; i<iteration_count; i++)
{
BitBoard bit_board;
for(const auto move : in_board_move){
const auto state = bit_board.GetState(move);
++state_count[state];
}
}
auto elapsed_time = chrono::system_clock::now() - start_time;
cout << "GetState:\t";
cout << chrono::duration_cast<chrono::milliseconds>(elapsed_time).count();
cout << " ms" << endl;
cout << "Summary result: " << state_count[0] << "," << state_count[1] << "," << state_count[2] << "," << state_count[3] << endl;
}
return 0;
} | 27.613333 | 132 | 0.632545 | [
"object"
] |
529358d956ad5cc5ccd472af07a7898fa801444f | 22,324 | cpp | C++ | Asap-3.8.4/Basics/LennardJones.cpp | auag92/n2dm | 03403ef8da303b79478580ae76466e374ec9da60 | [
"MIT"
] | 1 | 2021-10-19T11:35:34.000Z | 2021-10-19T11:35:34.000Z | Asap-3.8.4/Basics/LennardJones.cpp | auag92/n2dm | 03403ef8da303b79478580ae76466e374ec9da60 | [
"MIT"
] | null | null | null | Asap-3.8.4/Basics/LennardJones.cpp | auag92/n2dm | 03403ef8da303b79478580ae76466e374ec9da60 | [
"MIT"
] | 3 | 2016-07-18T19:22:48.000Z | 2021-07-06T03:06:42.000Z | // Copyright (C) 2008-2011 Jakob Schiotz and Center for Individual
// Nanoparticle Functionality, Department of Physics, Technical
// University of Denmark. Email: schiotz@fysik.dtu.dk
//
// This file is part of Asap version 3.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// version 3 as published by the Free Software Foundation. Permission
// to use other versions of the GNU Lesser General Public License may
// granted by Jakob Schiotz or the head of department of the
// Department of Physics, Technical University of Denmark, as
// described in section 14 of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// and the GNU Lesser Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
/*
* Calculates the Lennard Jones potential
*/
// This implementation supports parallel simulations. Due to the
// simplicity of Lennard-Jones, everything is handled by the
// ParallelAtoms and ParallelPotential classes, this potential only
// has to be prepared for parallel simulations in two ways:
//
// 1. After a neighborlist update, the number of atoms may have
// changed, and arrays may have to be reallocated.
//
// 2. The neighborlist may return atoms with number higher than
// nAtoms, these are ghosts of atoms residing on other processor,
// and only have positions and atomic numbers. It must be avoided
// to update energies, forces and stresses for these, as that would
// overwrite the end of the arrays.
#include "AsapPython.h"
#include "Asap.h"
#include "LennardJones.h"
#include "NeighborList.h"
#include "Atoms.h"
#include "Vec.h"
#include "Timing.h"
//#define ASAPDEBUG
#include "Debug.h"
#include <math.h>
#include <stdio.h>
#include <algorithm>
#ifndef _WIN32
#include <sys/wait.h>
#endif
using std::cerr;
using std::endl;
using std::flush;
using std::less;
extern int verbose;
#define SPARSE_MATRIX_SIZE 92 // No Pu, please!
// Use same volume for all atoms in stress calculation.
#define SHAREVOLUME
#if 0
#define VERB(x) if (verbose == 1) cerr << x
#else
#define VERB(x)
#endif
#ifdef SUN_SQRT_LITERAL_HACK
// SunOS compiler: sqrt does not work with a literal number (cannot decide if
// it is a double or a long double).
#define sqrt(x) sqrt((double) x)
#endif
// Standard mapping of the six independent parts of the stress tensor to
// vector notation
const static int stresscomp[3][3] = {{0, 5, 4}, {5, 1, 3}, {4, 3, 2}};
//******************************************************************************
// LennardJones
//******************************************************************************
LennardJones::LennardJones(PyObject *self,
int numElements, const std::vector<int> &elements,
const std::vector<double> &epsilon,
const std::vector<double> &sigma,
const std::vector<double> &masses, double rCut,
bool modified) : Potential(self)
{
DEBUGPRINT;
atoms = NULL;
this->nAtoms = 0;
neighborList= 0;
neighborList_obj= 0;
driftfactor = 0.05;
this->modified = modified;
this->numElements = numElements;
this->latticeConstant = 0.0;
memset(&counters, 0x0, sizeof(counters));
if(rCut<0)
this->rCut = CalculateRCut(numElements*numElements, sigma);
else
this->rCut = rCut;
Internalize(numElements, elements, epsilon, sigma, masses);
//Print();
DEBUGPRINT;
}
LennardJones::~LennardJones()
{
DEBUGPRINT;
Py_XDECREF(neighborList_obj);
if (atoms != NULL)
AsapAtoms_DECREF(atoms);
}
//******************************************************************************
// Print
//******************************************************************************
void LennardJones::Print() {
std::cout<<" ***************************************"<<endl;
std::cout<<" atoms is "<<atoms<<endl;
std::cout<<" neighborList is "<<neighborList<<endl;
std::cout<<" nAtoms is "<<nAtoms<<endl;
if(atoms&&neighborList) {
std::cout<<" atoms->GetNumberOfAtoms() is "<<atoms->GetNumberOfAtoms()<<endl;
std::cout<<" neighborList->MaxNeighborListLength() "<<neighborList->MaxNeighborListLength()<<endl;
}
std::cout<<" modified is "<<modified<<endl;
std::cout<<" numElements is "<<numElements<<endl;
std::cout<<" latticeConstant is "<<latticeConstant<<endl;
std::cout<<" SPARSE_MATRIX_SIZE is "<<SPARSE_MATRIX_SIZE<<endl;
std::cout<<endl;
std::cout<<" ***************************************"<<endl<<endl;
//std::cout<<"Epsilon table:"<<endl;
//for(int i=0;i<SPARSE_MATRIX_SIZE;i++)
// for(int j=0;j<SPARSE_MATRIX_SIZE;j++)
// std::cout<<"epsilon["<<i<<","<<j<<"]:"<<epsilon[i*SPARSE_MATRIX_SIZE+j]<<endl;
}
//******************************************************************************
// Internalize
//******************************************************************************
void LennardJones::Internalize(int p_numElements,
const std::vector<int> &p_elements,
const std::vector<double> &p_epsilon,
const std::vector<double> &p_sigma,
const std::vector<double> &p_masses)
{
DEBUGPRINT;
//Print();
double rCut6 = pow(rCut, 6.0); //cCut^6
double rCut12 = pow(rCut, 12.0); //cCut^12
//0. complete upper triangular matrices
std::vector<double> full_epsilon; full_epsilon.resize(p_numElements*p_numElements);
std::vector<double> full_sigma; full_sigma.resize(p_numElements*p_numElements);
for(int i=0;i<p_numElements;i++) {
for(int j=0;j<=i;j++) {
full_epsilon[j*p_numElements+i]=p_epsilon[i*p_numElements+j];
full_sigma[j*p_numElements+i]=p_sigma[i*p_numElements+j];
full_epsilon[i*p_numElements+j]=p_epsilon[i*p_numElements+j];
full_sigma[i*p_numElements+j]=p_sigma[i*p_numElements+j];
}
}
//copy the masses
masses.resize(SPARSE_MATRIX_SIZE);
memset(&masses[0], -1, sizeof(double)*SPARSE_MATRIX_SIZE);
for(int i=0; i<p_numElements; i++)
masses[p_elements[i]] = p_masses[i];
atomicvolume.resize(SPARSE_MATRIX_SIZE);
memset(&atomicvolume[0], -1, sizeof(double)*SPARSE_MATRIX_SIZE);
double volumefactor = 0.94; // 1.1^3 / sqrt(2)
for(int i=0; i<p_numElements; i++)
{
double sig = p_sigma[i*p_numElements+i];
atomicvolume[p_elements[i]] = (volumefactor * sig * sig * sig);
}
//1. allocate the matrices
epsilon.resize(SPARSE_MATRIX_SIZE*SPARSE_MATRIX_SIZE);
sigma6.resize(SPARSE_MATRIX_SIZE*SPARSE_MATRIX_SIZE);
sigma12.resize(SPARSE_MATRIX_SIZE*SPARSE_MATRIX_SIZE);
v0.resize(SPARSE_MATRIX_SIZE*SPARSE_MATRIX_SIZE);
//2. Fill the matrix with the values we know.
// a) We know that sigma[i][j] = sigma[j][i]
// b) The position in the array is calculated as follows:
// (element number of atom i)*SPARSE_MATRIX_SIZE + (element number of atom j)
for(int i=0; i<p_numElements; i++) {
for(int j=0; j<=i; j++) {
double newEpsilon = full_epsilon[i*p_numElements+j];
double newSigma1 = full_sigma[i*p_numElements+j];
double newSigma3 = newSigma1 * newSigma1 * newSigma1;
double newSigma6 = newSigma3 * newSigma3 ;
int position1 = p_elements[i]+p_elements[j]*SPARSE_MATRIX_SIZE;
int position2 = p_elements[j]+p_elements[i]*SPARSE_MATRIX_SIZE;
epsilon[position1] = newEpsilon;
epsilon[position2] = newEpsilon;
//sigma^6
sigma6 [position1] = newSigma6;
sigma6 [position2] = newSigma6;
//sigma^12
sigma12 [position1] = newSigma6*newSigma6;
sigma12 [position2] = newSigma6*newSigma6;
//v0
if (modified)
{
v0[position1] = 2*epsilon[position1]*(sigma12[position1]/rCut12-sigma6[position1]/rCut6);
v0[position2] = 2*epsilon[position2]*(sigma12[position2]/rCut12-sigma6[position2]/rCut6);
}
else
{
v0[position1] = 0.0;
v0[position2] = 0.0;
}
}
}
DEBUGPRINT;
}
void LennardJones::SetAtoms(PyObject *pyatoms, Atoms* accessobj /* = NULL */)
{
if (atoms != NULL)
{
// SetAtoms should only do anything the first time it is called.
// Subsequent calls should just check for accessobj being NULL.
if (accessobj != NULL)
throw AsapError("LennardJones::SetAtoms called multiple times with accessobj != NULL");
// SetAtoms should not do anything if called more than once!
return;
}
// The first time SetAtoms is being called some initialization is done.
if (accessobj != NULL)
{
atoms = accessobj;
AsapAtoms_INCREF(atoms);
}
else
atoms = new NormalAtoms();
assert(atoms != NULL);
}
//******************************************************************************
// CalculateIDs
//******************************************************************************
/*
calculates or defines the default rCut
*/
double LennardJones::CalculateRCut(int numElements,
const vector<double> &sigma)
{
//we return 3*min(sigma)
double result = sigma[0];
int i = 0;
while(++i<numElements)
if(sigma[i]>result)
result = sigma[i];
return 3*result;
}
//******************************************************************************
// Allocate
//******************************************************************************
void LennardJones::Allocate()
{
DEBUGPRINT;
if (verbose)
cerr << "Allocate(" << nAtoms << ") " << endl;
assert(nAtoms != 0);
atomicEnergies.resize(nAtoms);
forces.resize(nSize);
virials.resize(nSize);
DEBUGPRINT;
}
//******************************************************************************
// CheckNeighborLists
//******************************************************************************
void LennardJones::CheckNeighborLists()
{
DEBUGPRINT;
if (counters.nblist == atoms->GetPositionsCounter() && neighborList != NULL
&& !neighborList->IsInvalid())
return;
if (neighborList)
{
DEBUGPRINT;
bool update = neighborList->CheckNeighborList();
update = atoms->UpdateBeforeCalculation(update,
rCut * (1 + driftfactor));
if (update)
neighborList->UpdateNeighborList();
if ((nAtoms != atoms->GetNumberOfAtoms()) ||
(nSize != nAtoms + atoms->GetNumberOfGhostAtoms()))
{
DEBUGPRINT;
assert(update);
nAtoms = atoms->GetNumberOfAtoms();
nSize = nAtoms + atoms->GetNumberOfGhostAtoms();
Allocate();
}
}
else
{
DEBUGPRINT;
atoms->UpdateBeforeCalculation(true, rCut * (1 + driftfactor));
PyAsap_NeighborLocatorObject *nbl = PyAsap_NewNeighborList(atoms, rCut,
driftfactor);
neighborList_obj = (PyObject *)nbl;
neighborList = dynamic_cast<NeighborList*>(nbl->cobj);
assert(neighborList != NULL);
neighborList->CheckAndUpdateNeighborList();
nAtoms = atoms->GetNumberOfAtoms();
nSize = nAtoms + atoms->GetNumberOfGhostAtoms();
Allocate();
}
counters.nblist = atoms->GetPositionsCounter();
DEBUGPRINT;
}
//******************************************************************************
// GetPotentialEnergy
//******************************************************************************
double LennardJones::GetPotentialEnergy(PyObject *pyatoms)
{
DEBUGPRINT;
assert(atoms != NULL);
atoms->Begin(pyatoms);
CheckNeighborLists();
DEBUGPRINT;
double e = CalculateEnergyAndEnergies();
atoms->End();
return e;
}
const vector<double> &LennardJones::GetPotentialEnergies(PyObject *pyatoms)
{
DEBUGPRINT;
assert(atoms != NULL);
atoms->Begin(pyatoms);
CheckNeighborLists();
CalculateEnergyAndEnergies();
atoms->End();
DEBUGPRINT;
return atomicEnergies;
}
//******************************************************************************
// GetStresses
//******************************************************************************
const vector<SymTensor> &LennardJones::GetVirials(PyObject *pyatoms)
{
assert(atoms != NULL);
atoms->Begin(pyatoms);
CheckNeighborLists();
if (nAtoms != virials.size())
virials.resize(nSize);
memset(&virials[0], 0, nSize * sizeof(SymTensor));
GetVirials(atoms->GetMomenta(), &virials[0]);
atoms->End();
return virials;
}
//******************************************************************************
// Stress
//******************************************************************************
/*
p_{i,alpha} * p_{i, beta} dV(r_{ij} r_{ij,alpha)*r_{ij,beta)
Calculates ------------------------- - Sum( 0.5 * --------- * ------------------------ )
m_{i} dr_{ij} r_{ij)
where
dV(r_ij) sigma^{12} sigma^{6}
-------- = 4*epsilon*[(-12)*(----------) +6*(---------) ]
dr_{ij} r_ij^{13} r_ij^{7}
resulting in
p_{i,alpha} * p_{i, beta} sigma^{12} sigma^{6}
------------------------- - 12*Sum(epsilon*[(-2)*(----------) + (---------) ] * r_{ij,alpha)*r_{ij,beta)
m_{i} r_ij^{14} r_ij^{8}
*/
//******************************************************************************
// GetStresses
//******************************************************************************
void LennardJones::GetVirials(const Vec *momenta, SymTensor *stresses)
{
DEBUGPRINT;
int maxNeighbors=neighborList->MaxNeighborListLength();//the max number of neighbors in neighborlist
int numNeighbors; //the current number of neighbors in the iteration
vector<Vec> diffs(maxNeighbors);
vector<int> neighbors(maxNeighbors);
vector<double> diffs2(maxNeighbors);
const asap_z_int *atomicNumberPtr;
int matrixLength;
atomicNumberPtr = atoms->GetAtomicNumbers();
matrixLength = SPARSE_MATRIX_SIZE;
for(int i=0; i<nAtoms; i++) {
for(int alpha = 0; alpha < 3; alpha++)
for(int beta = alpha; beta < 3; beta++)
{
int j = stresscomp[alpha][beta];
double result;
int MaxNB = maxNeighbors;
numNeighbors = neighborList->GetNeighbors(i, &neighbors[0],
&diffs[0], &diffs2[0],
MaxNB);
for(int a=0; a<numNeighbors; a++) {//iterate over the neighbors
int neighbor = neighbors[a];
double dist4 =diffs2[a]*diffs2[a]; //=dist^4
double dist8 =dist4*dist4; //=dist^8
double dist14=dist8*dist4*diffs2[a];//=dist^14
int arrayPos; //position in the sigma/epsilon array
arrayPos = atomicNumberPtr[i]*matrixLength+atomicNumberPtr[neighbor];
result = epsilon[arrayPos]*(sigma6[arrayPos]/dist8 -
2*sigma12[arrayPos]/dist14) *
(diffs[a][alpha]) * (diffs[a][beta]);
if (neighbor < nAtoms)
result *= 12.0;
else
result *= 6.0;
stresses[i][j] += result;
stresses[neighbor][j] += result;
}
}
}
DEBUGPRINT;
}
void LennardJones::GetAtomicVolumes(vector<double> &volumes)
{
#ifdef SHAREVOLUME
volumes.clear();
#else
volumes.resize(nAtoms);
for (int i = 0; i < nAtoms; i++)
volumes[i] = atomicvolume[z[i]];
#endif
}
//******************************************************************************
// GetCartesianForces
//******************************************************************************
const vector<Vec> &LennardJones::GetForces(PyObject *pyatoms)
{
assert(atoms != NULL);
atoms->Begin(pyatoms);
CheckNeighborLists();
assert(nSize >= nAtoms);
assert(forces.size() == nSize);
memset(&(forces[0]), 0, nSize * sizeof(Vec)); //zero the forces
GetCartesianForces(forces);
atoms->End();
return forces;
}
//******************************************************************************
// GetCartesianForces
//******************************************************************************
//
// dV(r_{in}) dr_{in}
// Calculates F_{alpha}(n) = Sum_{i<>n} (---------- * ( -------------- ))
// dr_{in) dr_{n,alpha}
//
//
// where
//
//
// dV(r_in) sigma^{12} sigma^6
// -------- = 4*epsilon*[(-12)*(----------) +6*(-------) ]
// dr_{in} r_in^{13} r_in^7
//
// and
//
// dr_{in} - (r_{i0} - r_{n,alpha})
// ( -------------- )) = ---------------------------------------------------------------------------
// dr_{n,alpha} ((r_{n0} - r_{i0})^2 + (r_{n0} - r_{i0})^2 + (r_{n0} - r_{i0})^2 ) ^ (1/2)
//
// = - (r_{i0} - r_{n,alpha})
// ------------------------
// | r_{n,i} |
//
// alpha = {0,1,2} (the dimension)
//
//
// Simplified:
// ===========
//
// sigma^{12} sigma^6
// F_{alpha}(n) = -24*Sum_{i<>n} epsilon*[ -2*(----------) + *(-------) ]*(r_{i0} - r_{n,alpha}) ]
// r_in^{14} r_in^8
//
void LennardJones::GetCartesianForces(vector<Vec>& forces)
{
DEBUGPRINT
const asap_z_int *z = atoms->GetAtomicNumbers();
int maxNeighbors=neighborList->MaxNeighborListLength();
vector<int> neighbors(maxNeighbors);
vector<Vec> diffs(maxNeighbors);
vector<double> diffs2(maxNeighbors);
int size;
DEBUGPRINT;
const asap_z_int *zz;
int msize;
zz = z;
msize = SPARSE_MATRIX_SIZE;
for(int n=0; n<nAtoms; n++) { //iterate over all atoms
size = maxNeighbors;
int numNeighbors = neighborList->GetNeighbors(n, &neighbors[0], &diffs[0],
&diffs2[0], size);
for(int a=0; a<numNeighbors; a++) {//iterate over all neighbors
int i = neighbors[a];
double dist4 =diffs2[a]*diffs2[a]; //=dist^4
double dist8 =dist4*dist4; //=dist^12
double dist14=dist8*dist4*diffs2[a];
int arrayPos; //position in the sigma/epsilon array
double dV;
arrayPos = zz[n]*msize + zz[i];
dV = epsilon[arrayPos]*(sigma6[arrayPos]/dist8 - 2*sigma12[arrayPos]/dist14);///sqrt(diffs2[a]);
if (i < nAtoms)
dV *= -24.0;
else
dV *= -12.0;
forces[n] -= dV * diffs[a];
forces[i] += dV * diffs[a];
}
}
DEBUGPRINT
}
//******************************************************************************
// Add
//******************************************************************************
//
// adds up the items in the vector, sorting them first by their absolute values
// (the result is pretty exact, since small numbers (1e-20 etc.) do not just
// drop out)
//
double LennardJones::Add(vector<double> &items) {
int numItems = items.size();
double result = 0.0;
sort(items.begin(), items.end(), LennardJones::LessFabs);
for(int a=0;a<numItems;a++) {
result += items[a];
}
return result;
}
//******************************************************************************
// LessFabs
//******************************************************************************
//compares the absolute values of a number
bool LennardJones::LessFabs(const double d1, const double d2) {
return fabs(d1)<fabs(d2);
}
//******************************************************************************
// CalculateEnergyAndEnergies
//******************************************************************************
double LennardJones::CalculateEnergyAndEnergies() {
if (counters.energies != atoms->GetPositionsCounter()) {
memset(&atomicEnergies[0], 0, nAtoms * sizeof(double));
CalculateEnergyAndEnergies(atomicEnergies);
counters.energies = atoms->GetPositionsCounter();
}
double energy = 0.0;
assert(atomicEnergies.size() == nAtoms);
for (int a = 0; a < nAtoms; a++) {
energy += atomicEnergies[a];
}
return energy;
}
//******************************************************************************
// CalculateEnergyAndEnergies
//******************************************************************************
///
/// sigma sigma
/// V(r_ij) = 4*epsilon*[(-------)^12 - (------)^6 ]
/// r_{ij} r_{ij}
///
void LennardJones::CalculateEnergyAndEnergies(vector<double>& atomicEnergies)
{
DEBUGPRINT;
const asap_z_int *z; //lookup for atomic numbers
int size;
int cols; //the number of columns in sigma6, epsilon matrices
int maxNeighbors=neighborList->MaxNeighborListLength();
vector<int> neighbors(maxNeighbors);
vector<double> diffs2(maxNeighbors);
vector<Vec> diffs(maxNeighbors);
z = atoms->GetAtomicNumbers();
cols = SPARSE_MATRIX_SIZE;
for(int i = 0;i<nAtoms;i++) {//iterate over the real number of atoms
size = maxNeighbors;
int n = neighborList->GetNeighbors(i, &neighbors[0], &diffs[0],
&diffs2[0], size);
for(int j = 0;j<n;j++) {
int nn = neighbors[j];
int position = z[i]*cols+z[nn];
double s6_div_r6 = sigma6[position]/diffs2[j]/diffs2[j]/diffs2[j];
double s12_div_r12 = s6_div_r6 * s6_div_r6 ;
double result = 2.0*epsilon[position]*(s12_div_r12-s6_div_r6)-v0[position];
atomicEnergies[i] += result;
if (nn < nAtoms)
atomicEnergies[nn] += result;
}
}
DEBUGPRINT;
}
long LennardJones::PrintMemory() const
{
cerr << "*MEM* LennardJones: Memory estimate not supported." << endl;
return 0;
}
| 33.722054 | 121 | 0.528669 | [
"vector"
] |
52939b0f9c7c42fbf0de6ea3eef989f5d4fcfb65 | 46,853 | cpp | C++ | frameworks/compile/mclinker/lib/Target/ARM/ARMRelocator.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | frameworks/compile/mclinker/lib/Target/ARM/ARMRelocator.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | frameworks/compile/mclinker/lib/Target/ARM/ARMRelocator.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | //===- ARMRelocator.cpp ----------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===--------------------------------------------------------------------===//
#include <mcld/LinkerConfig.h>
#include <mcld/IRBuilder.h>
#include <llvm/ADT/Twine.h>
#include <llvm/Support/DataTypes.h>
#include <llvm/Support/ELF.h>
#include <llvm/Support/Host.h>
#include <mcld/Support/MsgHandling.h>
#include <mcld/LD/LDSymbol.h>
#include <mcld/LD/ELFFileFormat.h>
#include <mcld/Object/ObjectBuilder.h>
#include "ARMRelocator.h"
#include "ARMRelocationFunctions.h"
using namespace mcld;
//===--------------------------------------------------------------------===//
// Relocation Functions and Tables
//===--------------------------------------------------------------------===//
DECL_ARM_APPLY_RELOC_FUNCS
/// the prototype of applying function
typedef Relocator::Result (*ApplyFunctionType)(Relocation& pReloc,
ARMRelocator& pParent);
// the table entry of applying functions
struct ApplyFunctionTriple
{
ApplyFunctionType func;
unsigned int type;
const char* name;
};
// declare the table of applying functions
static const ApplyFunctionTriple ApplyFunctions[] = {
DECL_ARM_APPLY_RELOC_FUNC_PTRS
};
//===--------------------------------------------------------------------===//
// ARMRelocator
//===--------------------------------------------------------------------===//
ARMRelocator::ARMRelocator(ARMGNULDBackend& pParent,
const LinkerConfig& pConfig)
: Relocator(pConfig),
m_Target(pParent) {
}
ARMRelocator::~ARMRelocator()
{
}
Relocator::Result
ARMRelocator::applyRelocation(Relocation& pRelocation)
{
Relocation::Type type = pRelocation.type();
if (type > 130) { // 131-255 doesn't noted in ARM spec
return Relocator::Unknown;
}
return ApplyFunctions[type].func(pRelocation, *this);
}
const char* ARMRelocator::getName(Relocator::Type pType) const
{
return ApplyFunctions[pType].name;
}
Relocator::Size ARMRelocator::getSize(Relocation::Type pType) const
{
return 32;
}
void ARMRelocator::addCopyReloc(ResolveInfo& pSym)
{
Relocation& rel_entry = *getTarget().getRelDyn().consumeEntry();
rel_entry.setType(llvm::ELF::R_ARM_COPY);
assert(pSym.outSymbol()->hasFragRef());
rel_entry.targetRef().assign(*pSym.outSymbol()->fragRef());
rel_entry.setSymInfo(&pSym);
}
/// defineSymbolForCopyReloc
/// For a symbol needing copy relocation, define a copy symbol in the BSS
/// section and all other reference to this symbol should refer to this
/// copy.
/// This is executed at scan relocation stage.
LDSymbol&
ARMRelocator::defineSymbolforCopyReloc(IRBuilder& pBuilder,
const ResolveInfo& pSym)
{
// get or create corresponding BSS LDSection
LDSection* bss_sect_hdr = NULL;
ELFFileFormat* file_format = getTarget().getOutputFormat();
if (ResolveInfo::ThreadLocal == pSym.type())
bss_sect_hdr = &file_format->getTBSS();
else
bss_sect_hdr = &file_format->getBSS();
// get or create corresponding BSS SectionData
SectionData* bss_data = NULL;
if (bss_sect_hdr->hasSectionData())
bss_data = bss_sect_hdr->getSectionData();
else
bss_data = IRBuilder::CreateSectionData(*bss_sect_hdr);
// Determine the alignment by the symbol value
// FIXME: here we use the largest alignment
uint32_t addralign = config().targets().bitclass() / 8;
// allocate space in BSS for the copy symbol
Fragment* frag = new FillFragment(0x0, 1, pSym.size());
uint64_t size = ObjectBuilder::AppendFragment(*frag,
*bss_data,
addralign);
bss_sect_hdr->setSize(bss_sect_hdr->size() + size);
// change symbol binding to Global if it's a weak symbol
ResolveInfo::Binding binding = (ResolveInfo::Binding)pSym.binding();
if (binding == ResolveInfo::Weak)
binding = ResolveInfo::Global;
// Define the copy symbol in the bss section and resolve it
LDSymbol* cpy_sym = pBuilder.AddSymbol<IRBuilder::Force, IRBuilder::Resolve>(
pSym.name(),
(ResolveInfo::Type)pSym.type(),
ResolveInfo::Define,
binding,
pSym.size(), // size
0x0, // value
FragmentRef::Create(*frag, 0x0),
(ResolveInfo::Visibility)pSym.other());
return *cpy_sym;
}
/// checkValidReloc - When we attempt to generate a dynamic relocation for
/// ouput file, check if the relocation is supported by dynamic linker.
void ARMRelocator::checkValidReloc(Relocation& pReloc) const
{
// If not PIC object, no relocation type is invalid
if (!config().isCodeIndep())
return;
switch(pReloc.type()) {
case llvm::ELF::R_ARM_RELATIVE:
case llvm::ELF::R_ARM_COPY:
case llvm::ELF::R_ARM_GLOB_DAT:
case llvm::ELF::R_ARM_JUMP_SLOT:
case llvm::ELF::R_ARM_ABS32:
case llvm::ELF::R_ARM_ABS32_NOI:
case llvm::ELF::R_ARM_PC24:
case llvm::ELF::R_ARM_TLS_DTPMOD32:
case llvm::ELF::R_ARM_TLS_DTPOFF32:
case llvm::ELF::R_ARM_TLS_TPOFF32:
break;
default:
error(diag::non_pic_relocation) << (int)pReloc.type()
<< pReloc.symInfo()->name();
break;
}
}
void
ARMRelocator::scanLocalReloc(Relocation& pReloc, const LDSection& pSection)
{
// rsym - The relocation target symbol
ResolveInfo* rsym = pReloc.symInfo();
switch(pReloc.type()){
// Set R_ARM_TARGET1 to R_ARM_ABS32
// Ref: GNU gold 1.11 arm.cc, line 9892
// FIXME: R_ARM_TARGET1 should be set by option --target1-rel
// or --target1-rel
case llvm::ELF::R_ARM_TARGET1:
pReloc.setType(llvm::ELF::R_ARM_ABS32);
case llvm::ELF::R_ARM_ABS32:
case llvm::ELF::R_ARM_ABS32_NOI: {
// If buiding PIC object (shared library or PIC executable),
// a dynamic relocations with RELATIVE type to this location is needed.
// Reserve an entry in .rel.dyn
if (config().isCodeIndep()) {
getTarget().getRelDyn().reserveEntry();
// set Rel bit
rsym->setReserved(rsym->reserved() | ReserveRel);
getTarget().checkAndSetHasTextRel(*pSection.getLink());
}
return;
}
case llvm::ELF::R_ARM_ABS16:
case llvm::ELF::R_ARM_ABS12:
case llvm::ELF::R_ARM_THM_ABS5:
case llvm::ELF::R_ARM_ABS8:
case llvm::ELF::R_ARM_BASE_ABS:
case llvm::ELF::R_ARM_MOVW_ABS_NC:
case llvm::ELF::R_ARM_MOVT_ABS:
case llvm::ELF::R_ARM_THM_MOVW_ABS_NC:
case llvm::ELF::R_ARM_THM_MOVT_ABS: {
// PIC code should not contain these kinds of relocation
if (config().isCodeIndep()) {
error(diag::non_pic_relocation) << (int)pReloc.type()
<< pReloc.symInfo()->name();
}
return;
}
case llvm::ELF::R_ARM_GOTOFF32:
case llvm::ELF::R_ARM_GOTOFF12: {
// FIXME: A GOT section is needed
return;
}
// Set R_ARM_TARGET2 to R_ARM_GOT_PREL
// Ref: GNU gold 1.11 arm.cc, line 9892
// FIXME: R_ARM_TARGET2 should be set by option --target2
case llvm::ELF::R_ARM_TARGET2:
pReloc.setType(llvm::ELF::R_ARM_GOT_PREL);
case llvm::ELF::R_ARM_GOT_BREL:
case llvm::ELF::R_ARM_GOT_PREL: {
// A GOT entry is needed for these relocation type.
// return if we already create GOT for this symbol
if (rsym->reserved() & (ReserveGOT | GOTRel))
return;
getTarget().getGOT().reserveGOT();
// If building PIC object, a dynamic relocation with
// type RELATIVE is needed to relocate this GOT entry.
// Reserve an entry in .rel.dyn
if (config().isCodeIndep()) {
// create .rel.dyn section if not exist
getTarget().getRelDyn().reserveEntry();
// set GOTRel bit
rsym->setReserved(rsym->reserved() | 0x4u);
return;
}
// set GOT bit
rsym->setReserved(rsym->reserved() | 0x2u);
return;
}
case llvm::ELF::R_ARM_BASE_PREL: {
// FIXME: Currently we only support R_ARM_BASE_PREL against
// symbol _GLOBAL_OFFSET_TABLE_
if (rsym != getTarget().getGOTSymbol()->resolveInfo())
fatal(diag::base_relocation) << (int)pReloc.type() << rsym->name()
<< "mclinker@googlegroups.com";
return;
}
case llvm::ELF::R_ARM_COPY:
case llvm::ELF::R_ARM_GLOB_DAT:
case llvm::ELF::R_ARM_JUMP_SLOT:
case llvm::ELF::R_ARM_RELATIVE: {
// These are relocation type for dynamic linker, shold not
// appear in object file.
fatal(diag::dynamic_relocation) << (int)pReloc.type();
break;
}
default: {
break;
}
} // end switch
}
void ARMRelocator::scanGlobalReloc(Relocation& pReloc,
IRBuilder& pBuilder,
const LDSection& pSection)
{
// rsym - The relocation target symbol
ResolveInfo* rsym = pReloc.symInfo();
switch(pReloc.type()) {
// Set R_ARM_TARGET1 to R_ARM_ABS32
// Ref: GNU gold 1.11 arm.cc, line 9892
// FIXME: R_ARM_TARGET1 should be set by option --target1-rel
// or --target1-rel
case llvm::ELF::R_ARM_TARGET1:
pReloc.setType(llvm::ELF::R_ARM_ABS32);
case llvm::ELF::R_ARM_ABS32:
case llvm::ELF::R_ARM_ABS16:
case llvm::ELF::R_ARM_ABS12:
case llvm::ELF::R_ARM_THM_ABS5:
case llvm::ELF::R_ARM_ABS8:
case llvm::ELF::R_ARM_BASE_ABS:
case llvm::ELF::R_ARM_MOVW_ABS_NC:
case llvm::ELF::R_ARM_MOVT_ABS:
case llvm::ELF::R_ARM_THM_MOVW_ABS_NC:
case llvm::ELF::R_ARM_THM_MOVT_ABS:
case llvm::ELF::R_ARM_ABS32_NOI: {
// Absolute relocation type, symbol may needs PLT entry or
// dynamic relocation entry
if (getTarget().symbolNeedsPLT(*rsym)) {
// create plt for this symbol if it does not have one
if (!(rsym->reserved() & ReservePLT)){
// Symbol needs PLT entry, we need to reserve a PLT entry
// and the corresponding GOT and dynamic relocation entry
// in .got and .rel.plt. (GOT entry will be reserved simultaneously
// when calling ARMPLT->reserveEntry())
getTarget().getPLT().reserveEntry();
getTarget().getRelPLT().reserveEntry();
// set PLT bit
rsym->setReserved(rsym->reserved() | ReservePLT);
}
}
if (getTarget().symbolNeedsDynRel(*rsym, (rsym->reserved() & ReservePLT), true)) {
// symbol needs dynamic relocation entry, reserve an entry in .rel.dyn
getTarget().getRelDyn().reserveEntry();
if (getTarget().symbolNeedsCopyReloc(pReloc, *rsym)) {
LDSymbol& cpy_sym = defineSymbolforCopyReloc(pBuilder, *rsym);
addCopyReloc(*cpy_sym.resolveInfo());
}
else {
checkValidReloc(pReloc);
// set Rel bit
rsym->setReserved(rsym->reserved() | ReserveRel);
getTarget().checkAndSetHasTextRel(*pSection.getLink());
}
}
return;
}
case llvm::ELF::R_ARM_GOTOFF32:
case llvm::ELF::R_ARM_GOTOFF12: {
// FIXME: A GOT section is needed
return;
}
case llvm::ELF::R_ARM_BASE_PREL:
case llvm::ELF::R_ARM_THM_MOVW_BREL_NC:
case llvm::ELF::R_ARM_THM_MOVW_BREL:
case llvm::ELF::R_ARM_THM_MOVT_BREL:
// FIXME: Currently we only support these relocations against
// symbol _GLOBAL_OFFSET_TABLE_
if (rsym != getTarget().getGOTSymbol()->resolveInfo()) {
fatal(diag::base_relocation) << (int)pReloc.type() << rsym->name()
<< "mclinker@googlegroups.com";
}
case llvm::ELF::R_ARM_REL32:
case llvm::ELF::R_ARM_LDR_PC_G0:
case llvm::ELF::R_ARM_SBREL32:
case llvm::ELF::R_ARM_THM_PC8:
case llvm::ELF::R_ARM_MOVW_PREL_NC:
case llvm::ELF::R_ARM_MOVT_PREL:
case llvm::ELF::R_ARM_THM_MOVW_PREL_NC:
case llvm::ELF::R_ARM_THM_MOVT_PREL:
case llvm::ELF::R_ARM_THM_ALU_PREL_11_0:
case llvm::ELF::R_ARM_THM_PC12:
case llvm::ELF::R_ARM_REL32_NOI:
case llvm::ELF::R_ARM_ALU_PC_G0_NC:
case llvm::ELF::R_ARM_ALU_PC_G0:
case llvm::ELF::R_ARM_ALU_PC_G1_NC:
case llvm::ELF::R_ARM_ALU_PC_G1:
case llvm::ELF::R_ARM_ALU_PC_G2:
case llvm::ELF::R_ARM_LDR_PC_G1:
case llvm::ELF::R_ARM_LDR_PC_G2:
case llvm::ELF::R_ARM_LDRS_PC_G0:
case llvm::ELF::R_ARM_LDRS_PC_G1:
case llvm::ELF::R_ARM_LDRS_PC_G2:
case llvm::ELF::R_ARM_LDC_PC_G0:
case llvm::ELF::R_ARM_LDC_PC_G1:
case llvm::ELF::R_ARM_LDC_PC_G2:
case llvm::ELF::R_ARM_ALU_SB_G0_NC:
case llvm::ELF::R_ARM_ALU_SB_G0:
case llvm::ELF::R_ARM_ALU_SB_G1_NC:
case llvm::ELF::R_ARM_ALU_SB_G1:
case llvm::ELF::R_ARM_ALU_SB_G2:
case llvm::ELF::R_ARM_LDR_SB_G0:
case llvm::ELF::R_ARM_LDR_SB_G1:
case llvm::ELF::R_ARM_LDR_SB_G2:
case llvm::ELF::R_ARM_LDRS_SB_G0:
case llvm::ELF::R_ARM_LDRS_SB_G1:
case llvm::ELF::R_ARM_LDRS_SB_G2:
case llvm::ELF::R_ARM_LDC_SB_G0:
case llvm::ELF::R_ARM_LDC_SB_G1:
case llvm::ELF::R_ARM_LDC_SB_G2:
case llvm::ELF::R_ARM_MOVW_BREL_NC:
case llvm::ELF::R_ARM_MOVT_BREL:
case llvm::ELF::R_ARM_MOVW_BREL: {
// Relative addressing relocation, may needs dynamic relocation
if (getTarget().symbolNeedsDynRel(*rsym, (rsym->reserved() & ReservePLT), false)) {
// symbol needs dynamic relocation entry, reserve an entry in .rel.dyn
getTarget().getRelDyn().reserveEntry();
if (getTarget().symbolNeedsCopyReloc(pReloc, *rsym)) {
LDSymbol& cpy_sym = defineSymbolforCopyReloc(pBuilder, *rsym);
addCopyReloc(*cpy_sym.resolveInfo());
}
else {
checkValidReloc(pReloc);
// set Rel bit
rsym->setReserved(rsym->reserved() | ReserveRel);
getTarget().checkAndSetHasTextRel(*pSection.getLink());
}
}
return;
}
case llvm::ELF::R_ARM_PC24:
case llvm::ELF::R_ARM_THM_CALL:
case llvm::ELF::R_ARM_PLT32:
case llvm::ELF::R_ARM_CALL:
case llvm::ELF::R_ARM_JUMP24:
case llvm::ELF::R_ARM_THM_JUMP24:
case llvm::ELF::R_ARM_SBREL31:
case llvm::ELF::R_ARM_PREL31:
case llvm::ELF::R_ARM_THM_JUMP19:
case llvm::ELF::R_ARM_THM_JUMP6:
case llvm::ELF::R_ARM_THM_JUMP11:
case llvm::ELF::R_ARM_THM_JUMP8: {
// These are branch relocation (except PREL31)
// A PLT entry is needed when building shared library
// return if we already create plt for this symbol
if (rsym->reserved() & ReservePLT)
return;
// if the symbol's value can be decided at link time, then no need plt
if (getTarget().symbolFinalValueIsKnown(*rsym))
return;
// if symbol is defined in the ouput file and it's not
// preemptible, no need plt
if (rsym->isDefine() && !rsym->isDyn() &&
!getTarget().isSymbolPreemptible(*rsym)) {
return;
}
// Symbol needs PLT entry, we need to reserve a PLT entry
// and the corresponding GOT and dynamic relocation entry
// in .got and .rel.plt. (GOT entry will be reserved simultaneously
// when calling ARMPLT->reserveEntry())
getTarget().getPLT().reserveEntry();
getTarget().getRelPLT().reserveEntry();
// set PLT bit
rsym->setReserved(rsym->reserved() | ReservePLT);
return;
}
// Set R_ARM_TARGET2 to R_ARM_GOT_PREL
// Ref: GNU gold 1.11 arm.cc, line 9892
// FIXME: R_ARM_TARGET2 should be set by option --target2
case llvm::ELF::R_ARM_TARGET2:
pReloc.setType(llvm::ELF::R_ARM_GOT_PREL);
case llvm::ELF::R_ARM_GOT_BREL:
case llvm::ELF::R_ARM_GOT_ABS:
case llvm::ELF::R_ARM_GOT_PREL: {
// Symbol needs GOT entry, reserve entry in .got
// return if we already create GOT for this symbol
if (rsym->reserved() & (ReserveGOT | GOTRel))
return;
getTarget().getGOT().reserveGOT();
// if the symbol cannot be fully resolved at link time, then we need a
// dynamic relocation
if (!getTarget().symbolFinalValueIsKnown(*rsym)) {
getTarget().getRelDyn().reserveEntry();
// set GOTRel bit
rsym->setReserved(rsym->reserved() | GOTRel);
return;
}
// set GOT bit
rsym->setReserved(rsym->reserved() | ReserveGOT);
return;
}
case llvm::ELF::R_ARM_COPY:
case llvm::ELF::R_ARM_GLOB_DAT:
case llvm::ELF::R_ARM_JUMP_SLOT:
case llvm::ELF::R_ARM_RELATIVE: {
// These are relocation type for dynamic linker, shold not
// appear in object file.
fatal(diag::dynamic_relocation) << (int)pReloc.type();
break;
}
default: {
break;
}
} // end switch
}
void ARMRelocator::scanRelocation(Relocation& pReloc,
IRBuilder& pBuilder,
Module& pModule,
LDSection& pSection)
{
// rsym - The relocation target symbol
ResolveInfo* rsym = pReloc.symInfo();
assert(NULL != rsym &&
"ResolveInfo of relocation not set while scanRelocation");
assert(NULL != pSection.getLink());
if (0 == (pSection.getLink()->flag() & llvm::ELF::SHF_ALLOC))
return;
// Scan relocation type to determine if an GOT/PLT/Dynamic Relocation
// entries should be created.
// FIXME: Below judgements concern nothing about TLS related relocation
// rsym is local
if (rsym->isLocal())
scanLocalReloc(pReloc, pSection);
// rsym is external
else
scanGlobalReloc(pReloc, pBuilder, pSection);
// check if we shoule issue undefined reference for the relocation target
// symbol
if (rsym->isUndef() && !rsym->isDyn() && !rsym->isWeak() && !rsym->isNull())
fatal(diag::undefined_reference) << rsym->name();
}
//===--------------------------------------------------------------------===//
// non-member functions
//===--------------------------------------------------------------------===//
static Relocator::DWord getThumbBit(const Relocation& pReloc)
{
// Set thumb bit if
// - symbol has type of STT_FUNC, is defined and with bit 0 of its value set
Relocator::DWord thumbBit =
((!pReloc.symInfo()->isUndef() || pReloc.symInfo()->isDyn()) &&
(pReloc.symInfo()->type() == ResolveInfo::Function) &&
((pReloc.symValue() & 0x1) != 0))?
1:0;
return thumbBit;
}
//=========================================//
// Relocation helper function //
//=========================================//
// Using uint64_t to make sure those complicate operations won't cause
// undefined behavior.
static
uint64_t helper_sign_extend(uint64_t pVal, uint64_t pOri_width)
{
assert(pOri_width <= 64);
if (pOri_width == 64)
return pVal;
uint64_t mask = (~((uint64_t)0)) >> (64 - pOri_width);
pVal &= mask;
// Reverse sign bit, then subtract sign bit.
uint64_t sign_bit = 1 << (pOri_width - 1);
return (pVal ^ sign_bit) - sign_bit;
}
static
uint64_t helper_bit_select(uint64_t pA, uint64_t pB, uint64_t pMask)
{
return (pA & ~pMask) | (pB & pMask) ;
}
// Check if symbol can use relocation R_ARM_RELATIVE
static bool
helper_use_relative_reloc(const ResolveInfo& pSym,
const ARMRelocator& pFactory)
{
// if symbol is dynamic or undefine or preemptible
if (pSym.isDyn() ||
pSym.isUndef() ||
pFactory.getTarget().isSymbolPreemptible(pSym))
return false;
return true;
}
// Strip LSB (THUMB bit) if "S" is a THUMB target.
static inline void helper_clear_thumb_bit(ARMRelocator::DWord& pValue)
{
pValue &= (~0x1);
}
static
ARMGOTEntry& helper_get_GOT_and_init(Relocation& pReloc,
ARMRelocator& pParent)
{
// rsym - The relocation target symbol
ResolveInfo* rsym = pReloc.symInfo();
ARMGNULDBackend& ld_backend = pParent.getTarget();
ARMGOTEntry* got_entry = pParent.getSymGOTMap().lookUp(*rsym);
if (NULL == got_entry) {
got_entry = ld_backend.getGOT().consumeGOT();
pParent.getSymGOTMap().record(*rsym, *got_entry);
// If we first get this GOT entry, we should initialize it.
if (rsym->reserved() & ARMRelocator::ReserveGOT) {
// No corresponding dynamic relocation, initialize to the symbol value.
got_entry->setValue(pReloc.symValue());
}
else if (rsym->reserved() & ARMRelocator::GOTRel) {
// Initialize corresponding dynamic relocation.
Relocation& rel_entry = *ld_backend.getRelDyn().consumeEntry();
if ( rsym->isLocal() ||
helper_use_relative_reloc(*rsym, pParent)) {
// Initialize got entry to target symbol address
got_entry->setValue(pReloc.symValue());
rel_entry.setType(llvm::ELF::R_ARM_RELATIVE);
rel_entry.setSymInfo(0);
}
else {
// Initialize got entry to 0 for corresponding dynamic relocation.
got_entry->setValue(0);
rel_entry.setType(llvm::ELF::R_ARM_GLOB_DAT);
rel_entry.setSymInfo(rsym);
}
rel_entry.targetRef().assign(*got_entry);
}
else {
fatal(diag::reserve_entry_number_mismatch_got);
}
}
return *got_entry;
}
static
ARMRelocator::Address helper_GOT_ORG(ARMRelocator& pParent)
{
return pParent.getTarget().getGOT().addr();
}
static
ARMRelocator::Address helper_GOT(Relocation& pReloc, ARMRelocator& pParent)
{
ARMGOTEntry& got_entry = helper_get_GOT_and_init(pReloc, pParent);
return helper_GOT_ORG(pParent) + got_entry.getOffset();
}
static
ARMPLT1& helper_get_PLT_and_init(Relocation& pReloc, ARMRelocator& pParent)
{
// rsym - The relocation target symbol
ResolveInfo* rsym = pReloc.symInfo();
ARMGNULDBackend& ld_backend = pParent.getTarget();
ARMPLT1* plt_entry = pParent.getSymPLTMap().lookUp(*rsym);
if (NULL != plt_entry)
return *plt_entry;
plt_entry = ld_backend.getPLT().consume();
pParent.getSymPLTMap().record(*rsym, *plt_entry);
// If we first get this PLT entry, we should initialize it.
if (rsym->reserved() & ARMRelocator::ReservePLT) {
ARMGOTEntry* gotplt_entry = pParent.getSymGOTPLTMap().lookUp(*rsym);
assert(NULL == gotplt_entry && "PLT entry not exist, but DynRel entry exist!");
gotplt_entry = ld_backend.getGOT().consumeGOTPLT();
pParent.getSymGOTPLTMap().record(*rsym, *gotplt_entry);
// Initialize corresponding dynamic relocation.
Relocation& rel_entry = *ld_backend.getRelPLT().consumeEntry();
rel_entry.setType(llvm::ELF::R_ARM_JUMP_SLOT);
rel_entry.targetRef().assign(*gotplt_entry);
rel_entry.setSymInfo(rsym);
}
else {
fatal(diag::reserve_entry_number_mismatch_plt);
}
return *plt_entry;
}
static
ARMRelocator::Address helper_PLT_ORG(ARMRelocator& pParent)
{
return pParent.getTarget().getPLT().addr();
}
static
ARMRelocator::Address helper_PLT(Relocation& pReloc, ARMRelocator& pParent)
{
ARMPLT1& plt_entry = helper_get_PLT_and_init(pReloc, pParent);
return helper_PLT_ORG(pParent) + plt_entry.getOffset();
}
// Get an relocation entry in .rel.dyn and set its type to pType,
// its FragmentRef to pReloc->targetFrag() and its ResolveInfo to
// pReloc->symInfo()
static
void helper_DynRel(Relocation& pReloc,
ARMRelocator::Type pType,
ARMRelocator& pParent)
{
// rsym - The relocation target symbol
ResolveInfo* rsym = pReloc.symInfo();
ARMGNULDBackend& ld_backend = pParent.getTarget();
Relocation& rel_entry = *ld_backend.getRelDyn().consumeEntry();
rel_entry.setType(pType);
rel_entry.targetRef() = pReloc.targetRef();
if (pType == llvm::ELF::R_ARM_RELATIVE)
rel_entry.setSymInfo(0);
else
rel_entry.setSymInfo(rsym);
}
static ARMRelocator::DWord
helper_extract_movw_movt_addend(ARMRelocator::DWord pTarget)
{
// imm16: [19-16][11-0]
return helper_sign_extend((((pTarget >> 4)) & 0xf000U) | (pTarget & 0xfffU),
16);
}
static ARMRelocator::DWord
helper_insert_val_movw_movt_inst(ARMRelocator::DWord pTarget,
ARMRelocator::DWord pImm)
{
// imm16: [19-16][11-0]
pTarget &= 0xfff0f000U;
pTarget |= pImm & 0x0fffU;
pTarget |= (pImm & 0xf000U) << 4;
return pTarget;
}
static ARMRelocator::DWord
helper_extract_thumb_movw_movt_addend(ARMRelocator::DWord pValue)
{
// imm16: [19-16][26][14-12][7-0]
return helper_sign_extend((((pValue >> 4) & 0xf000U) |
((pValue >> 15) & 0x0800U) |
((pValue >> 4) & 0x0700U) |
(pValue& 0x00ffU)),
16);
}
static ARMRelocator::DWord
helper_insert_val_thumb_movw_movt_inst(ARMRelocator::DWord pValue,
ARMRelocator::DWord pImm)
{
// imm16: [19-16][26][14-12][7-0]
pValue &= 0xfbf08f00U;
pValue |= (pImm & 0xf000U) << 4;
pValue |= (pImm & 0x0800U) << 15;
pValue |= (pImm & 0x0700U) << 4;
pValue |= (pImm & 0x00ffU);
return pValue;
}
static ARMRelocator::DWord
helper_thumb32_branch_offset(ARMRelocator::DWord pUpper16,
ARMRelocator::DWord pLower16)
{
ARMRelocator::DWord s = (pUpper16 & (1U << 10)) >> 10, // 26 bit
u = pUpper16 & 0x3ffU, // 25-16
l = pLower16 & 0x7ffU, // 10-0
j1 = (pLower16 & (1U << 13)) >> 13, // 13
j2 = (pLower16 & (1U << 11)) >> 11; // 11
ARMRelocator::DWord i1 = j1 ^ s? 0: 1,
i2 = j2 ^ s? 0: 1;
// [31-25][24][23][22][21-12][11-1][0]
// 0 s i1 i2 u l 0
return helper_sign_extend((s << 24) | (i1 << 23) | (i2 << 22) |
(u << 12) | (l << 1),
25);
}
static ARMRelocator::DWord
helper_thumb32_branch_upper(ARMRelocator::DWord pUpper16,
ARMRelocator::DWord pOffset)
{
uint32_t sign = ((pOffset & 0x80000000U) >> 31);
return (pUpper16 & ~0x7ffU) | ((pOffset >> 12) & 0x3ffU) | (sign << 10);
}
static ARMRelocator::DWord
helper_thumb32_branch_lower(ARMRelocator::DWord pLower16,
ARMRelocator::DWord pOffset)
{
uint32_t sign = ((pOffset & 0x80000000U) >> 31);
return ((pLower16 & ~0x2fffU) |
((((pOffset >> 23) & 1) ^ !sign) << 13) |
((((pOffset >> 22) & 1) ^ !sign) << 11) |
((pOffset >> 1) & 0x7ffU));
}
// Return true if overflow
static bool
helper_check_signed_overflow(ARMRelocator::DWord pValue,
unsigned bits)
{
int32_t signed_val = static_cast<int32_t>(pValue);
int32_t max = (1 << (bits - 1)) - 1;
int32_t min = -(1 << (bits - 1));
if (signed_val > max || signed_val < min) {
return true;
} else {
return false;
}
}
//=========================================//
// Each relocation function implementation //
//=========================================//
// R_ARM_NONE
ARMRelocator::Result none(Relocation& pReloc, ARMRelocator& pParent)
{
return ARMRelocator::OK;
}
// R_ARM_ABS32: (S + A) | T
ARMRelocator::Result abs32(Relocation& pReloc, ARMRelocator& pParent)
{
ResolveInfo* rsym = pReloc.symInfo();
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord A = pReloc.target() + pReloc.addend();
ARMRelocator::DWord S = pReloc.symValue();
if (T != 0x0)
helper_clear_thumb_bit(S);
LDSection& target_sect = pReloc.targetRef().frag()->getParent()->getSection();
// If the flag of target section is not ALLOC, we will not scan this relocation
// but perform static relocation. (e.g., applying .debug section)
if (0x0 == (llvm::ELF::SHF_ALLOC & target_sect.flag())) {
pReloc.target() = (S + A) | T;
return ARMRelocator::OK;
}
// A local symbol may need REL Type dynamic relocation
if (rsym->isLocal() && (rsym->reserved() & ARMRelocator::ReserveRel)) {
helper_DynRel(pReloc, llvm::ELF::R_ARM_RELATIVE, pParent);
pReloc.target() = (S + A) | T ;
return ARMRelocator::OK;
}
// An external symbol may need PLT and dynamic relocation
if (!rsym->isLocal()) {
if (rsym->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
T = 0 ; // PLT is not thumb
}
// If we generate a dynamic relocation (except R_ARM_RELATIVE)
// for a place, we should not perform static relocation on it
// in order to keep the addend store in the place correct.
if (rsym->reserved() & ARMRelocator::ReserveRel) {
if (helper_use_relative_reloc(*rsym, pParent)) {
helper_DynRel(pReloc, llvm::ELF::R_ARM_RELATIVE, pParent);
}
else {
helper_DynRel(pReloc, pReloc.type(), pParent);
return ARMRelocator::OK;
}
}
}
// perform static relocation
pReloc.target() = (S + A) | T;
return ARMRelocator::OK;
}
// R_ARM_REL32: ((S + A) | T) - P
ARMRelocator::Result rel32(Relocation& pReloc, ARMRelocator& pParent)
{
// perform static relocation
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord A = pReloc.target() + pReloc.addend();
if (T != 0x0)
helper_clear_thumb_bit(S);
// An external symbol may need PLT (this reloc is from stub)
if (!pReloc.symInfo()->isLocal()) {
if (pReloc.symInfo()->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
T = 0; // PLT is not thumb.
}
}
// perform relocation
pReloc.target() = ((S + A) | T) - pReloc.place();
return ARMRelocator::OK;
}
// R_ARM_BASE_PREL: B(S) + A - P
ARMRelocator::Result base_prel(Relocation& pReloc, ARMRelocator& pParent)
{
// perform static relocation
ARMRelocator::DWord A = pReloc.target() + pReloc.addend();
pReloc.target() = pReloc.symValue() + A - pReloc.place();
return ARMRelocator::OK;
}
// R_ARM_GOTOFF32: ((S + A) | T) - GOT_ORG
ARMRelocator::Result gotoff32(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord A = pReloc.target() + pReloc.addend();
ARMRelocator::Address GOT_ORG = helper_GOT_ORG(pParent);
ARMRelocator::Address S = pReloc.symValue();
if (T != 0x0)
helper_clear_thumb_bit(S);
pReloc.target() = ((S + A) | T) - GOT_ORG;
return ARMRelocator::OK;
}
// R_ARM_GOT_BREL: GOT(S) + A - GOT_ORG
ARMRelocator::Result got_brel(Relocation& pReloc, ARMRelocator& pParent)
{
if (!(pReloc.symInfo()->reserved() &
(ARMRelocator::ReserveGOT | ARMRelocator::GOTRel))) {
return ARMRelocator::BadReloc;
}
ARMRelocator::Address GOT_S = helper_GOT(pReloc, pParent);
ARMRelocator::DWord A = pReloc.target() + pReloc.addend();
ARMRelocator::Address GOT_ORG = helper_GOT_ORG(pParent);
// Apply relocation.
pReloc.target() = GOT_S + A - GOT_ORG;
return ARMRelocator::OK;
}
// R_ARM_GOT_PREL: GOT(S) + A - P
ARMRelocator::Result got_prel(Relocation& pReloc, ARMRelocator& pParent)
{
if (!(pReloc.symInfo()->reserved() &
(ARMRelocator::ReserveGOT | ARMRelocator::GOTRel))) {
return ARMRelocator::BadReloc;
}
ARMRelocator::Address GOT_S = helper_GOT(pReloc, pParent);
ARMRelocator::DWord A = pReloc.target() + pReloc.addend();
ARMRelocator::Address P = pReloc.place();
// Apply relocation.
pReloc.target() = GOT_S + A - P;
return ARMRelocator::OK;
}
// R_ARM_THM_JUMP11: S + A - P
ARMRelocator::Result thm_jump11(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::DWord P = pReloc.place();
ARMRelocator::DWord A =
helper_sign_extend((pReloc.target() & 0x07ff) << 1, 11) +
pReloc.addend();
// S depends on PLT exists or not
ARMRelocator::Address S = pReloc.symValue();
if (pReloc.symInfo()->reserved() & ARMRelocator::ReservePLT)
S = helper_PLT(pReloc, pParent);
ARMRelocator::DWord X = S + A - P;
if (helper_check_signed_overflow(X, 11))
return ARMRelocator::Overflow;
// Make sure the Imm is 0. Result Mask.
pReloc.target() = (pReloc.target() & 0xFFFFF800u) | ((X & 0x0FFEu) >> 1);
return ARMRelocator::OK;
}
// R_ARM_PC24: ((S + A) | T) - P
// R_ARM_PLT32: ((S + A) | T) - P
// R_ARM_JUMP24: ((S + A) | T) - P
// R_ARM_CALL: ((S + A) | T) - P
ARMRelocator::Result call(Relocation& pReloc, ARMRelocator& pParent)
{
// If target is undefined weak symbol, we only need to jump to the
// next instruction unless it has PLT entry. Rewrite instruction
// to NOP.
if (pReloc.symInfo()->isWeak() &&
pReloc.symInfo()->isUndef() &&
!pReloc.symInfo()->isDyn() &&
!(pReloc.symInfo()->reserved() & ARMRelocator::ReservePLT)) {
// change target to NOP : mov r0, r0
pReloc.target() = (pReloc.target() & 0xf0000000U) | 0x01a00000;
return ARMRelocator::OK;
}
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord A =
helper_sign_extend((pReloc.target() & 0x00FFFFFFu) << 2, 26) +
pReloc.addend();
ARMRelocator::Address P = pReloc.place();
ARMRelocator::Address S = pReloc.symValue();
if (T != 0x0)
helper_clear_thumb_bit(S);
// S depends on PLT exists or not
if (pReloc.symInfo()->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
T = 0; // PLT is not thumb.
}
// At this moment (after relaxation), if the jump target is thumb instruction,
// switch mode is needed, rewrite the instruction to BLX
// FIXME: check if we can use BLX instruction (check from .ARM.attribute
// CPU ARCH TAG, which should be ARMv5 or above)
if (T != 0) {
// cannot rewrite to blx for R_ARM_JUMP24
if (pReloc.type() == llvm::ELF::R_ARM_JUMP24)
return ARMRelocator::BadReloc;
if (pReloc.type() == llvm::ELF::R_ARM_PC24)
return ARMRelocator::BadReloc;
pReloc.target() = (pReloc.target() & 0xffffff) |
0xfa000000 |
(((S + A - P) & 2) << 23);
}
ARMRelocator::DWord X = ((S + A) | T) - P;
// Check X is 24bit sign int. If not, we should use stub or PLT before apply.
if (helper_check_signed_overflow(X, 26))
return ARMRelocator::Overflow;
// Make sure the Imm is 0. Result Mask.
pReloc.target() = (pReloc.target() & 0xFF000000u) | ((X & 0x03FFFFFEu) >> 2);
return ARMRelocator::OK;
}
// R_ARM_THM_CALL: ((S + A) | T) - P
// R_ARM_THM_JUMP24: ((S + A) | T) - P
ARMRelocator::Result thm_call(Relocation& pReloc, ARMRelocator& pParent)
{
// If target is undefined weak symbol, we only need to jump to the
// next instruction unless it has PLT entry. Rewrite instruction
// to NOP.
if (pReloc.symInfo()->isWeak() &&
pReloc.symInfo()->isUndef() &&
!pReloc.symInfo()->isDyn() &&
!(pReloc.symInfo()->reserved() & ARMRelocator::ReservePLT)) {
pReloc.target() = (0xe000U << 16) | 0xbf00U;
return ARMRelocator::OK;
}
// get lower and upper 16 bit instructions from relocation targetData
uint16_t upper_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()));
uint16_t lower_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1);
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord A = helper_thumb32_branch_offset(upper_inst,
lower_inst);
ARMRelocator::Address P = pReloc.place();
ARMRelocator::Address S;
// if symbol has plt
if (pReloc.symInfo()->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
T = 0; // PLT is not thumb.
}
else {
S = pReloc.symValue();
if (T != 0x0)
helper_clear_thumb_bit(S);
}
S = S + A;
// At this moment (after relaxation), if the jump target is arm
// instruction, switch mode is needed, rewrite the instruction to BLX
// FIXME: check if we can use BLX instruction (check from .ARM.attribute
// CPU ARCH TAG, which should be ARMv5 or above)
if (T == 0) {
// cannot rewrite to blx for R_ARM_THM_JUMP24
if (pReloc.type() == llvm::ELF::R_ARM_THM_JUMP24)
return ARMRelocator::BadReloc;
// for BLX, select bit 1 from relocation base address to jump target
// address
S = helper_bit_select(S, P, 0x2);
// rewrite instruction to BLX
lower_inst &= ~0x1000U;
}
else {
// otherwise, the instruction should be BL
lower_inst |= 0x1000U;
}
ARMRelocator::DWord X = (S | T) - P;
// FIXME: Check bit size is 24(thumb2) or 22?
if (helper_check_signed_overflow(X, 25)) {
return ARMRelocator::Overflow;
}
upper_inst = helper_thumb32_branch_upper(upper_inst, X);
lower_inst = helper_thumb32_branch_lower(lower_inst, X);
*(reinterpret_cast<uint16_t*>(&pReloc.target())) = upper_inst;
*(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1) = lower_inst;
return ARMRelocator::OK;
}
// R_ARM_MOVW_ABS_NC: (S + A) | T
ARMRelocator::Result movw_abs_nc(Relocation& pReloc, ARMRelocator& pParent)
{
ResolveInfo* rsym = pReloc.symInfo();
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord A =
helper_extract_movw_movt_addend(pReloc.target()) + pReloc.addend();
if (T != 0x0)
helper_clear_thumb_bit(S);
LDSection& target_sect = pReloc.targetRef().frag()->getParent()->getSection();
// If the flag of target section is not ALLOC, we will not scan this
// relocation but perform static relocation. (e.g., applying .debug section)
if (0x0 != (llvm::ELF::SHF_ALLOC & target_sect.flag())) {
// use plt
if (rsym->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
T = 0 ; // PLT is not thumb
}
}
// perform static relocation
ARMRelocator::DWord X = (S + A) | T;
pReloc.target() = helper_insert_val_movw_movt_inst(
pReloc.target() + pReloc.addend(), X);
return ARMRelocator::OK;
}
// R_ARM_MOVW_PREL_NC: ((S + A) | T) - P
ARMRelocator::Result movw_prel_nc(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord P = pReloc.place();
ARMRelocator::DWord A =
helper_extract_movw_movt_addend(pReloc.target()) + pReloc.addend();
if (T != 0x0)
helper_clear_thumb_bit(S);
ARMRelocator::DWord X = ((S + A) | T) - P;
if (helper_check_signed_overflow(X, 16)) {
return ARMRelocator::Overflow;
} else {
pReloc.target() = helper_insert_val_movw_movt_inst(pReloc.target(), X);
return ARMRelocator::OK;
}
}
// R_ARM_MOVT_ABS: S + A
ARMRelocator::Result movt_abs(Relocation& pReloc, ARMRelocator& pParent)
{
ResolveInfo* rsym = pReloc.symInfo();
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord A =
helper_extract_movw_movt_addend(pReloc.target()) + pReloc.addend();
LDSection& target_sect = pReloc.targetRef().frag()->getParent()->getSection();
// If the flag of target section is not ALLOC, we will not scan this relocation
// but perform static relocation. (e.g., applying .debug section)
if (0x0 != (llvm::ELF::SHF_ALLOC & target_sect.flag())) {
// use plt
if (rsym->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
}
}
ARMRelocator::DWord X = S + A;
X >>= 16;
// perform static relocation
pReloc.target() = helper_insert_val_movw_movt_inst(pReloc.target(), X);
return ARMRelocator::OK;
}
// R_ARM_MOVT_PREL: S + A - P
ARMRelocator::Result movt_prel(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord P = pReloc.place();
ARMRelocator::DWord A =
helper_extract_movw_movt_addend(pReloc.target()) + pReloc.addend();
ARMRelocator::DWord X = S + A - P;
X >>= 16;
pReloc.target() = helper_insert_val_movw_movt_inst(pReloc.target(), X);
return ARMRelocator::OK;
}
// R_ARM_THM_MOVW_ABS_NC: (S + A) | T
ARMRelocator::Result thm_movw_abs_nc(Relocation& pReloc, ARMRelocator& pParent)
{
ResolveInfo* rsym = pReloc.symInfo();
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord T = getThumbBit(pReloc);
if (T != 0x0)
helper_clear_thumb_bit(S);
// get lower and upper 16 bit instructions from relocation targetData
uint16_t upper_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()));
uint16_t lower_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1);
ARMRelocator::DWord val = ((upper_inst) << 16) | (lower_inst);
ARMRelocator::DWord A =
helper_extract_thumb_movw_movt_addend(val) + pReloc.addend();
LDSection& target_sect = pReloc.targetRef().frag()->getParent()->getSection();
// If the flag of target section is not ALLOC, we will not scan this relocation
// but perform static relocation. (e.g., applying .debug section)
if (0x0 != (llvm::ELF::SHF_ALLOC & target_sect.flag())) {
// use plt
if (rsym->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
T = 0; // PLT is not thumb
}
}
ARMRelocator::DWord X = (S + A) | T;
val = helper_insert_val_thumb_movw_movt_inst(val, X);
*(reinterpret_cast<uint16_t*>(&pReloc.target())) = val >> 16;
*(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1) = val & 0xFFFFu;
return ARMRelocator::OK;
}
// R_ARM_THM_MOVW_PREL_NC: ((S + A) | T) - P
ARMRelocator::Result thm_movw_prel_nc(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord P = pReloc.place();
if (T != 0x0)
helper_clear_thumb_bit(S);
// get lower and upper 16 bit instructions from relocation targetData
uint16_t upper_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()));
uint16_t lower_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1);
ARMRelocator::DWord val = ((upper_inst) << 16) | (lower_inst);
ARMRelocator::DWord A =
helper_extract_thumb_movw_movt_addend(val) + pReloc.addend();
ARMRelocator::DWord X = ((S + A) | T) - P;
val = helper_insert_val_thumb_movw_movt_inst(val, X);
*(reinterpret_cast<uint16_t*>(&pReloc.target())) = val >> 16;
*(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1) = val & 0xFFFFu;
return ARMRelocator::OK;
}
// R_ARM_THM_MOVW_BREL_NC: ((S + A) | T) - B(S)
// R_ARM_THM_MOVW_BREL: ((S + A) | T) - B(S)
ARMRelocator::Result thm_movw_brel(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord P = pReloc.place();
if (T != 0x0)
helper_clear_thumb_bit(S);
// get lower and upper 16 bit instructions from relocation targetData
uint16_t upper_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()));
uint16_t lower_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1);
ARMRelocator::DWord val = ((upper_inst) << 16) | (lower_inst);
ARMRelocator::DWord A =
helper_extract_thumb_movw_movt_addend(val) + pReloc.addend();
ARMRelocator::DWord X = ((S + A) | T) - P;
val = helper_insert_val_thumb_movw_movt_inst(val, X);
*(reinterpret_cast<uint16_t*>(&pReloc.target())) = val >> 16;
*(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1) = val & 0xFFFFu;
return ARMRelocator::OK;
}
// R_ARM_THM_MOVT_ABS: S + A
ARMRelocator::Result thm_movt_abs(Relocation& pReloc, ARMRelocator& pParent)
{
ResolveInfo* rsym = pReloc.symInfo();
ARMRelocator::Address S = pReloc.symValue();
// get lower and upper 16 bit instructions from relocation targetData
uint16_t upper_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()));
uint16_t lower_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1);
ARMRelocator::DWord val = ((upper_inst) << 16) | (lower_inst);
ARMRelocator::DWord A =
helper_extract_thumb_movw_movt_addend(val) + pReloc.addend();
LDSection& target_sect = pReloc.targetRef().frag()->getParent()->getSection();
// If the flag of target section is not ALLOC, we will not scan this
// relocation but perform static relocation. (e.g., applying .debug section)
if (0x0 != (llvm::ELF::SHF_ALLOC & target_sect.flag())) {
// use plt
if (rsym->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
}
}
ARMRelocator::DWord X = S + A;
X >>= 16;
// check 16-bit overflow
if (helper_check_signed_overflow(X, 16))
return ARMRelocator::Overflow;
val = helper_insert_val_thumb_movw_movt_inst(val, X);
*(reinterpret_cast<uint16_t*>(&pReloc.target())) = val >> 16;
*(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1) = val & 0xFFFFu;
return ARMRelocator::OK;
}
// R_ARM_THM_MOVT_PREL: S + A - P
// R_ARM_THM_MOVT_BREL: S + A - B(S)
ARMRelocator::Result thm_movt_prel(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::Address S = pReloc.symValue();
ARMRelocator::DWord P = pReloc.place();
// get lower and upper 16 bit instructions from relocation targetData
uint16_t upper_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()));
uint16_t lower_inst = *(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1);
ARMRelocator::DWord val = ((upper_inst) << 16) | (lower_inst);
ARMRelocator::DWord A =
helper_extract_thumb_movw_movt_addend(val) + pReloc.addend();
ARMRelocator::DWord X = S + A - P;
X >>= 16;
val = helper_insert_val_thumb_movw_movt_inst(val, X);
*(reinterpret_cast<uint16_t*>(&pReloc.target())) = val >> 16;
*(reinterpret_cast<uint16_t*>(&pReloc.target()) + 1) = val & 0xFFFFu;
return ARMRelocator::OK;
}
// R_ARM_PREL31: ((S + A) | T) - P
ARMRelocator::Result prel31(Relocation& pReloc, ARMRelocator& pParent)
{
ARMRelocator::DWord target = pReloc.target();
ARMRelocator::DWord T = getThumbBit(pReloc);
ARMRelocator::DWord A = helper_sign_extend(target, 31) + pReloc.addend();
ARMRelocator::DWord P = pReloc.place();
ARMRelocator::Address S = pReloc.symValue();
if (T != 0x0)
helper_clear_thumb_bit(S);
// if symbol has plt
if ( pReloc.symInfo()->reserved() & ARMRelocator::ReservePLT) {
S = helper_PLT(pReloc, pParent);
T = 0; // PLT is not thumb.
}
ARMRelocator::DWord X = ((S + A) | T) - P;
pReloc.target() = helper_bit_select(target, X, 0x7fffffffU);
if (helper_check_signed_overflow(X, 31))
return ARMRelocator::Overflow;
return ARMRelocator::OK;
}
// R_ARM_TLS_GD32: GOT(S) + A - P
// R_ARM_TLS_IE32: GOT(S) + A - P
// R_ARM_TLS_LE32: S + A - tp
ARMRelocator::Result tls(Relocation& pReloc, ARMRelocator& pParent)
{
return ARMRelocator::Unsupport;
}
ARMRelocator::Result unsupport(Relocation& pReloc, ARMRelocator& pParent)
{
return ARMRelocator::Unsupport;
}
| 34.299414 | 89 | 0.639425 | [
"object"
] |
529a60911198114d2a6fc4ac6f85cf84b0999af8 | 6,878 | cc | C++ | tests/libtests/faults/data/CohesiveImpulsesDataHex8.cc | cehanagan/pylith | cf5c1c34040460a82f79b6eb54df894ed1b1ee93 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/faults/data/CohesiveImpulsesDataHex8.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/faults/data/CohesiveImpulsesDataHex8.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University at Buffalo
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2021 University of California, Davis
//
// See LICENSE.md for license information.
//
// ======================================================================
//
/* Original mesh
*
* Cells are 0-1 and vertices are 2-13.
*
* 2,3,4,5 -------- 6,7,8,9 -------- 10,11,12,13
*
* ^^^^^^^ Vertices forming fault
*
* After adding cohesive elements
*
* Cells are 0-1,2 and vertices are 3-18,19-22.
*
* 3,4,5,6 -------- 7,8,9,10 -- 15,16,17,18 -------- 11,12,13,14
* 59,60,61,62
* ^^^^^^^^^^^^^^^^^^^^^^ Cohesive element
*
*/
#include "CohesiveImpulsesDataHex8.hh"
const char* pylith::faults::CohesiveImpulsesDataHex8::_meshFilename =
"data/hex8.mesh";
const int pylith::faults::CohesiveImpulsesDataHex8::_spaceDim = 3;
const int pylith::faults::CohesiveImpulsesDataHex8::_cellDim = 2;
const int pylith::faults::CohesiveImpulsesDataHex8::_numBasis = 4;
const int pylith::faults::CohesiveImpulsesDataHex8::_numQuadPts = 4;
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_quadPts[] = {
-1.0, -1.0,
+1.0, -1.0,
+1.0, +1.0,
-1.0, +1.0
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_quadWts[] = {
1.0, 1.0, 1.0, 1.0
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_basis[] = {
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_basisDeriv[] = {
-0.39433757, -0.39433757,
+0.39433757, -0.10566243,
+0.10566243, +0.10566243,
-0.10566243, +0.39433757,
-0.39433757, -0.10566243,
+0.39433757, -0.39433757,
+0.10566243, +0.39433757,
-0.10566243, +0.10566243,
-0.10566243, -0.10566243,
+0.10566243, -0.39433757,
+0.39433757, +0.39433757,
-0.39433757, +0.10566243,
-0.10566243, -0.39433757,
+0.10566243, -0.10566243,
+0.39433757, +0.10566243,
-0.39433757, +0.39433757,
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_verticesRef[] = {
-1.0, -1.0,
+1.0, -1.0,
+1.0, +1.0,
-1.0, +1.0
};
const int pylith::faults::CohesiveImpulsesDataHex8::_id = 10;
const char* pylith::faults::CohesiveImpulsesDataHex8::_label = "fault";
const char* pylith::faults::CohesiveImpulsesDataHex8::_impulseAmpFilename =
"data/hex8_impulses.spatialdb";
const int pylith::faults::CohesiveImpulsesDataHex8::_impulseDOF[1] = {
1,
};
const int pylith::faults::CohesiveImpulsesDataHex8::_numComponents = 1;
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_fieldT[] = {
4.1, 6.1, 8.1,
4.2, 6.2, 8.2,
4.3, 6.3, 8.3,
4.4, 6.4, 8.4,
4.5, 6.5, 8.5, // 7
4.6, 6.6, 8.6, // 8
4.7, 6.7, 8.7, // 9
4.8, 6.8, 8.8, // 10
4.9, 6.9, 8.9,
4.0, 6.0, 8.0,
5.1, 7.1, 9.1,
5.2, 7.2, 9.2,
5.3, 7.3, 9.3, // 15
5.5, 7.5, 9.5, // 16
5.7, 7.7, 9.7, // 17
5.9, 7.9, 9.9, // 18
5.4, 7.4, 9.4, // 19
5.6, 7.6, 9.6, // 20
5.8, 7.8, 9.8, // 21
5.0, 7.0, 9.0, // 22
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_fieldIncr[] = {
3.1, 4.1, 5.1,
3.2, 4.2, 5.2,
3.3, 4.3, 5.3,
3.4, 4.4, 5.4,
3.5, 4.5, 5.5, // 7
3.6, 4.6, 5.6, // 8
3.7, 4.7, 5.7, // 9
3.8, 4.8, 5.8, // 10
3.9, 4.9, 5.9,
3.0, 4.0, 5.0,
3.1, 4.1, 5.1,
3.2, 4.2, 5.2,
3.3, 4.3, 5.3, // 15
3.5, 4.5, 5.5, // 16
3.7, 4.7, 5.7, // 17
3.9, 4.9, 5.9, // 18
3.4, 4.4, 5.4, // 19
3.6, 4.6, 5.6, // 20
3.8, 4.8, 5.8, // 21
3.0, 4.0, 5.0, // 22
};
// ----------------------------------------------------------------------
// Computed values
// ----------------------------------------------------------------------
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_orientation[] = {
0.0, +1.0, 0.0, 0.0, 0.0, +1.0, +1.0, 0.0, 0.0,
0.0, +1.0, 0.0, 0.0, 0.0, +1.0, +1.0, 0.0, 0.0,
0.0, +1.0, 0.0, 0.0, 0.0, +1.0, +1.0, 0.0, 0.0,
0.0, +1.0, 0.0, 0.0, 0.0, +1.0, +1.0, 0.0, 0.0,
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_area[] = {
1.0, 1.0, 1.0, 1.0
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_amplitude[4] = {
0.8,
1.6,
0.0,
1.2,
};
const int pylith::faults::CohesiveImpulsesDataHex8::_numImpulses = 3;
const int pylith::faults::CohesiveImpulsesDataHex8::_numConstraintEdges = 4;
const int pylith::faults::CohesiveImpulsesDataHex8::_constraintEdges[4] = {
59, 60, 61, 62
};
const int pylith::faults::CohesiveImpulsesDataHex8::_negativeVertices[4] = {
7, 8, 9, 10
};
const PylithScalar pylith::faults::CohesiveImpulsesDataHex8::_residual[] = {
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
+5.4, +7.4, +9.4, // 7
+5.6, +7.6, +9.6, // 8
+5.8, +7.8, +9.8, // 9
+5.0, +7.0, +9.0, // 10
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
-5.4, -7.4, -9.4, // 15
-5.6, -7.6, -9.6, // 16
-5.8, -7.8, -9.8, // 17
-5.0, -7.0, -9.0, // 18
// 19 (constraint)
-(5.3-4.5-0.0), -(7.3-6.5+0.0), -(9.3-8.5-0.0),
// 20 (constraint)
-(5.5-4.6-0.0), -(7.5-6.6+0.0), -(9.5-8.6-1.6),
// 21 (constraint)
-(5.7-4.7-0.0), -(7.7-6.7+0.0), -(9.7-8.7-0.0),
// 22 (constraint)
-(5.9-4.8-0.0), -(7.9-6.8+0.0), -(9.9-8.8-0.0),
};
pylith::faults::CohesiveImpulsesDataHex8::CohesiveImpulsesDataHex8(void)
{ // constructor
meshFilename = const_cast<char*>(_meshFilename);
spaceDim = _spaceDim;
cellDim = _cellDim;
numBasis = _numBasis;
numQuadPts = _numQuadPts;
quadPts = const_cast<PylithScalar*>(_quadPts);
quadWts = const_cast<PylithScalar*>(_quadWts);
basis = const_cast<PylithScalar*>(_basis);
basisDeriv = const_cast<PylithScalar*>(_basisDeriv);
verticesRef = const_cast<PylithScalar*>(_verticesRef);
id = _id;
label = const_cast<char*>(_label);
impulseAmpFilename = const_cast<char*>(_impulseAmpFilename);
impulseDOF = const_cast<int*>(_impulseDOF);
numComponents = _numComponents;
fieldT = const_cast<PylithScalar*>(_fieldT);
fieldIncr = const_cast<PylithScalar*>(_fieldIncr);
orientation = const_cast<PylithScalar*>(_orientation);
area = const_cast<PylithScalar*>(_area);
amplitude = const_cast<PylithScalar*>(_amplitude);
numImpulses = _numImpulses;
residual = const_cast<PylithScalar*>(_residual);
constraintEdges = const_cast<int*>(_constraintEdges);
negativeVertices = const_cast<int*>(_negativeVertices);
numConstraintEdges = _numConstraintEdges;
} // constructor
pylith::faults::CohesiveImpulsesDataHex8::~CohesiveImpulsesDataHex8(void)
{}
// End of file
| 27.293651 | 79 | 0.577348 | [
"mesh"
] |
529ccbd5e664fd71894c982235817e98f0c35b3f | 15,931 | cpp | C++ | src/collada-view/DefaultRenderer.cpp | veter-team/daeview | 6eaff3cd4efe0c5548d8897267356db473b4b907 | [
"MIT"
] | 7 | 2016-01-08T20:38:51.000Z | 2021-03-03T03:54:40.000Z | src/collada-view/DefaultRenderer.cpp | veter-team/daeview | 6eaff3cd4efe0c5548d8897267356db473b4b907 | [
"MIT"
] | null | null | null | src/collada-view/DefaultRenderer.cpp | veter-team/daeview | 6eaff3cd4efe0c5548d8897267356db473b4b907 | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <sstream>
#include <boost/graph/depth_first_search.hpp>
#include <list>
#include "gltools.h"
#include "DefaultRenderer.h"
#include "NodePainter.h"
#include "Shaders.h"
class lwmatrix_update_visitor : public default_dfs_visitor
{
public:
lwmatrix_update_visitor(SceneGraph *sg)
: scene_graph(sg),
node_id_map(get(SceneGraph::node_info_t(), scene_graph->node_graph))
{
}
~lwmatrix_update_visitor()
{
assert(this->parent_stack.empty());
}
template<typename Vertex, typename Graph>
void discover_vertex(Vertex u, const Graph & g)
{
SceneGraph::NodeInfo &n = this->node_id_map[u];
Node *node = this->scene_graph->all_nodes.find(n.id.c_str());
assert(node);
Node *parent = NULL;
if(!this->parent_stack.empty())
{
parent = this->scene_graph->all_nodes.find(this->parent_stack.back().c_str());
assert(parent);
}
if(parent)
node->local_to_world_matrix = parent->local_to_world_matrix * node->local_matrix;
else
node->local_to_world_matrix = node->local_matrix;
node->inverse_local_to_world_matrix = inverse(node->local_to_world_matrix);
node->inverse_transpose_local_to_world_matrix = transpose(node->inverse_local_to_world_matrix);
this->parent_stack.push_back(n.id);
}
template<typename Vertex, typename Graph>
void finish_vertex(Vertex u, const Graph & g)
{
this->parent_stack.pop_back();
}
private:
SceneGraph *scene_graph;
typedef property_map<SceneGraph::NodeGraph, SceneGraph::node_info_t>::type node_id_map_t;
node_id_map_t node_id_map;
typedef std::list<std::string> IdStack;
IdStack parent_stack;
};
void
BuildLWMatrix(SceneGraph *scene_graph)
{
lwmatrix_update_visitor vis(scene_graph);
depth_first_search(scene_graph->node_graph, visitor(vis));
}
DefaultRenderer::DefaultRenderer(const LoggerFuncT &logger)
: scene_graph(NULL),
root_node(NULL),
projection_matrix(Matrix4::identity()),
perspective_matrix(Matrix4::identity()),
light_node(NULL),
printStatusMessage(logger)
{
GLint vMajor = 0;
GLint vMinor = 0;
GetOpenGLVersion(vMajor, vMinor);
std::ostringstream os;
os << "Running with OpenGL version " << vMajor << "." << vMinor;
os << std::ends;
this->printStatusMessage(os.str());
GLuint shader_prog =
LoadShaderPairSrcWithAttributes(this->printStatusMessage,
pointLightDiff.first,
pointLightDiff.second,
2,
ATTRIBUTE_VERTEX, "vVertex",
ATTRIBUTE_NORMAL, "vNormal");
ErrorMessages errors = CheckErrors(shader_prog);
for(ErrorMessages::const_iterator error_iter = errors.begin(); error_iter != errors.end(); ++error_iter)
this->printStatusMessage(*error_iter);
if(shader_prog == 0)
throw std::runtime_error("Error loading shaders. See output for more details.");
this->shaders.insert(std::make_pair(Effect::Constant, shader_prog));
shader_prog =
LoadShaderPairSrcWithAttributes(this->printStatusMessage,
ADSGouraud.first,
ADSGouraud.second,
2,
ATTRIBUTE_VERTEX, "vVertex",
ATTRIBUTE_NORMAL, "vNormal");
errors = CheckErrors(shader_prog);
for(ErrorMessages::const_iterator error_iter = errors.begin(); error_iter != errors.end(); ++error_iter)
this->printStatusMessage(*error_iter);
if(shader_prog == 0)
throw std::runtime_error("Error loading shaders. See output for more details.");
this->shaders.insert(std::make_pair(Effect::Lambert, shader_prog));
shader_prog =
LoadShaderPairSrcWithAttributes(this->printStatusMessage,
ADSPhong.first,
ADSPhong.second,
2,
ATTRIBUTE_VERTEX, "vVertex",
ATTRIBUTE_NORMAL, "vNormal");
errors = CheckErrors(shader_prog);
for(ErrorMessages::const_iterator error_iter = errors.begin(); error_iter != errors.end(); ++error_iter)
this->printStatusMessage(*error_iter);
if(shader_prog == 0)
throw std::runtime_error("Error loading shaders. See output for more details.");
this->shaders.insert(std::make_pair(Effect::Phong, shader_prog));
this->shaders.insert(std::make_pair(Effect::Blinn, shader_prog));
shader_prog =
LoadShaderPairSrcWithAttributes(this->printStatusMessage,
texturePointLightDiff.first,
texturePointLightDiff.second,
3,
ATTRIBUTE_VERTEX, "vVertex",
ATTRIBUTE_NORMAL, "vNormal",
ATTRIBUTE_TEXTURE0, "vTexCoord0");
errors = CheckErrors(shader_prog);
for(ErrorMessages::const_iterator error_iter = errors.begin(); error_iter != errors.end(); ++error_iter)
this->printStatusMessage(*error_iter);
if(shader_prog == 0)
throw std::runtime_error("Error loading shaders. See output for more details.");
this->shaders.insert(std::make_pair(Effect::Texture, shader_prog));
this->printStatusMessage("Shaders loaded and initialized");
}
void
DefaultRenderer::cleanupBufferObjects()
{
// Vertex buffer objects
for(GeometryBuffersList::const_iterator i = this->geometry_buffers_list.begin();
i != this->geometry_buffers_list.end(); ++i)
{
const GeometryBuffers &gb = i->second;
glDeleteBuffers(1, &(gb.vertex_data_array));
glDeleteBuffers(1, &(gb.normal_data_array));
glDeleteBuffers(1, &(gb.texture_data_array));
for(GeometryBuffers::IndexArrays::const_iterator i = gb.index_data_array.begin();
i != gb.index_data_array.end(); ++i)
glDeleteBuffers(1, &(i->first));
/*
glDeleteBuffers(1, &(gb.polygons_vertex_array));
glDeleteBuffers(1, &(gb.polygons_normal_array));
glDeleteBuffers(1, &(gb.polygons_color_array));
glDeleteBuffers(1, &(gb.triangles_vertex_array));
glDeleteBuffers(1, &(gb.triangles_normal_array));
glDeleteBuffers(1, &(gb.triangles_color_array));
glDeleteBuffers(1, &(gb.lines_vertex_array));
glDeleteBuffers(1, &(gb.lines_color_array));
glDeleteBuffers(1, &(gb.linestrips_vertex_array));
glDeleteBuffers(1, &(gb.linestrips_color_array));
glDeleteBuffers(1, &(gb.tristrips_vertex_array));
glDeleteBuffers(1, &(gb.tristrips_normal_array));
glDeleteBuffers(1, &(gb.tristrips_color_array));
glDeleteBuffers(1, &(gb.trifans_vertex_array));
glDeleteBuffers(1, &(gb.trifans_normal_array));
glDeleteBuffers(1, &(gb.trifans_color_array));
*/
#ifndef OPENGL_ES
glDeleteVertexArrays(1, &(gb.vertexArrayBufferObject));
#endif
}
this->geometry_buffers_list.clear();
for(TextureNameMap::const_iterator tn = this->texture_names.begin();
tn != this->texture_names.end(); ++tn)
{
glDeleteTextures(1, &(tn->second));
}
this->texture_names.clear();
}
DefaultRenderer::~DefaultRenderer()
{
this->cleanupBufferObjects();
}
void
DefaultRenderer::setScene(SceneGraph *sg)
{
this->cleanupBufferObjects();
this->scene_graph = sg;
// Build local-to-world and related matricies
BuildLWMatrix(this->scene_graph);
SceneGraph::node_id_map_t node_id_map(get(SceneGraph::node_info_t(), this->scene_graph->node_graph));
const SceneGraph::NodeInfo &n = node_id_map[this->scene_graph->root];
this->root_node = this->scene_graph->all_nodes.find(n.id.c_str());
assert(this->root_node);
// Walk through all geometry objects and build corresponding GL buffer objects
for(Geometry::GeometryList::const_iterator i = this->scene_graph->all_geometries.begin();
i != this->scene_graph->all_geometries.end(); ++i)
{
const Geometry::GeometryID &gid = i->first;
const Geometry &g = i->second;
GeometryBuffers gb;
#ifndef OPENGL_ES
// Create the master vertex array object
glGenVertexArrays(1, &(gb.vertexArrayBufferObject));
glBindVertexArray(gb.vertexArrayBufferObject);
#endif
// Copy data to video memory
if(!g.points.empty())
{// Vertex data
glGenBuffers(1, &(gb.vertex_data_array));
glBindBuffer(GL_ARRAY_BUFFER, gb.vertex_data_array);
glEnableVertexAttribArray(ATTRIBUTE_VERTEX);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * g.points.size(), &(g.points[0]), GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIBUTE_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
if(!g.normals.empty())
{// Normal data
glGenBuffers(1, &(gb.normal_data_array));
glBindBuffer(GL_ARRAY_BUFFER, gb.normal_data_array);
glEnableVertexAttribArray(ATTRIBUTE_NORMAL);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * g.normals.size(), &(g.normals[0]), GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIBUTE_NORMAL, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
if(!g.tex_coords[0].empty())
{// Texture coordinates
glGenBuffers(1, &(gb.texture_data_array));
glBindBuffer(GL_ARRAY_BUFFER, gb.texture_data_array);
glEnableVertexAttribArray(ATTRIBUTE_TEXTURE0);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * g.tex_coords[0].size(), &(g.tex_coords[0][0]), GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIBUTE_TEXTURE0, 2, GL_FLOAT, GL_FALSE, 0, 0);
}
// Indexes
for(Geometry::TrianglesList::const_iterator t = g.triangles_list.begin(); t != g.triangles_list.end(); ++t)
{
GLuint index_data_array;
glGenBuffers(1, &index_data_array);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_data_array);
const PolyGroup::IndexVector &iv = t->index_vector.front();
if(!iv.empty())
{
GLuint index_count = iv.size();
gb.index_data_array.push_back(std::make_pair(index_data_array, index_count));
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(PolyGroup::IndexVector::value_type) * index_count, &(iv[0]), GL_STATIC_DRAW);
}
else
glDeleteBuffers(1, &index_data_array);
}
// Done
#ifndef OPENGL_ES
glBindVertexArray(0);
#endif
this->geometry_buffers_list.insert(std::make_pair(gid, gb));
}
// Create textures for all effects
for(Effect::EffectList::const_iterator e = this->scene_graph->all_effects.begin();
e != this->scene_graph->all_effects.end(); ++e)
{
const Effect &effect = e->second;
for(Effect::ImageIDList::const_iterator id = effect.textures.begin();
id != effect.textures.end(); ++id)
{
const Image::ImageID &img_id = *id;
Image::ImageList::iterator img = this->scene_graph->all_images.find(img_id);
if(img != this->scene_graph->all_images.end())
{
GLuint texid = CreateTexture(img->second.image, NULL, img->second.should_flip);
this->texture_names.insert(std::make_pair(img_id, texid));
}
}
}
// Get light information.
// Only one light source is currently supported.
this->light_node = this->scene_graph->all_nodes.find(this->scene_graph->light_nodes.front().c_str());
assert(light_node);
this->light_iter = this->scene_graph->all_lights.find(light_node->instance_lights.front().abstract_light_ref);
assert(this->light_iter != this->scene_graph->all_lights.end());
}
void
DefaultRenderer::setupCamera(int window_width, int window_height)
{
if(this->scene_graph == NULL)
return;
Node *node;
InstanceCamera *inst;
tie(node, inst) = this->scene_graph->active_camera_info;
if(inst == NULL || node == NULL)
return;
// Recalculate the aspect in case the window size has changed.
Camera::CameraList::const_iterator ac = this->scene_graph->all_cameras.find(inst->abstract_camera_ref);
assert(ac != this->scene_graph->all_cameras.end());
const Camera &abstract_camera = ac->second;
float aspect;
/* if(window_width > 0 && window_height > 0)
{
// If the window size is set, make the aspect ratio match it
aspect = (float)window_width / (float)window_height;
glViewport(0, 0, window_width, window_height);
}
else*/ if(abstract_camera.aspect > 0.0)
// No window size set, use the aspect ratio from the camera
aspect = abstract_camera.aspect;
else // Otherwise default to 16 by 9 (HDTV)
aspect = 16.0f / 9.0f;
this->perspective_matrix = Matrix4::perspective(abstract_camera.Xfov / aspect,
aspect,
abstract_camera.ZNear,
abstract_camera.ZFar);
}
void
UpdateLocalMatricies(Node::NodeMap &all_nodes, const Animation::NodeIdSet &touched_nodes)
{
// Update local matricies
for(Animation::NodeIdSet::const_iterator n = touched_nodes.begin();
n != touched_nodes.end(); ++n)
{
Node *node = all_nodes.find(n->c_str());
node->local_matrix = Matrix4::identity();
for(int i = 0; i < node->transformations.size(); ++i)
{
switch(node->transformations[i].type)
{
case Transformation::Rotate:
case Transformation::Translate:
case Transformation::Scale:
node->local_matrix *= node->transformations[i].transform;
break;
case Transformation::Matrix:
case Transformation::LookAt:
node->local_matrix *= node->transformations[i].matrix;
break;
case Transformation::Skew:
case Transformation::Unknown:
break;
}
}
}
}
void
DefaultRenderer::render()
{
if(this->scene_graph == NULL)
return;
/*
static float time = 0.0f;
time += 0.1f;
Animation::NodeIdSet touched_nodes;
for(Animation::AnimationList::iterator a = this->scene_graph->all_animations.begin();
a != this->scene_graph->all_animations.end(); ++a)
{
a->second.animate(this->scene_graph->printStatusMessage,
this->scene_graph->all_nodes,
time,
touched_nodes);
}
if(touched_nodes.empty())
time = 0.0f;
else
UpdateLocalMatricies(this->scene_graph->all_nodes, touched_nodes);
*/
Node *camera_node = this->scene_graph->active_camera_info.first;
//static Vector3 v;
//v[0] = 0.2f;
//v[1] += 0.1f;
//v[2] += -0.02f;
// Reuild local-to-world and related matricies
BuildLWMatrix(this->scene_graph);
this->projection_matrix = this->perspective_matrix * camera_node->inverse_local_to_world_matrix;
//this->projection_matrix *= Transform3::rotationZYX(v);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
NodePainter node_painter(this);
for(int i = 0; i < this->scene_graph->all_nodes.size(); ++i)
{
Node *node = this->scene_graph->all_nodes.getAtIndex(i);
if(!node->is_font_node)
node_painter.paint(*node,
this->light_node->local_to_world_matrix.getTranslation(),
this->light_iter->second);
}
static const char *hello_world = "Hello, World!";
Vector3 t(-1.0f, 1.0f, 3.0f);
Transform3 text_transform = Transform3::translation(t);
char buff[8];
for(const char *c = hello_world; *c; ++c)
{
sprintf(buff, "%i", int(*c));
Node *node = this->scene_graph->all_nodes.find((SceneGraph::font_name + buff).c_str());
if(node)
{
Matrix4 l2w = node->local_to_world_matrix;
node->local_to_world_matrix *= text_transform;
node_painter.paint(*node,
this->light_node->local_to_world_matrix.getTranslation(),
this->light_iter->second);
node->local_to_world_matrix = l2w;
t.setX(t.getX() + (node->bbox_max.getX() - node->bbox_min.getX()) * 1.1f);
text_transform = Transform3::translation(t);
}
}
}
| 33.328452 | 130 | 0.657962 | [
"geometry",
"render",
"object",
"transform"
] |
52a593e9e635c408296d8193b7177c78a2674bbf | 413 | cpp | C++ | src/main.cpp | asaladino/classy-json-schema | 3086de9c4f19698267ca95c82d8a4aaa17f70c28 | [
"MIT"
] | null | null | null | src/main.cpp | asaladino/classy-json-schema | 3086de9c4f19698267ca95c82d8a4aaa17f70c28 | [
"MIT"
] | null | null | null | src/main.cpp | asaladino/classy-json-schema | 3086de9c4f19698267ca95c82d8a4aaa17f70c28 | [
"MIT"
] | null | null | null | #include "Model/Setting.h"
#include "Controller/CliController.h"
#include "Controller/GuiController.h"
int main(int argc, char *argv[]) {
auto setting = Setting(argc, argv);
if (setting.useCli) {
auto cliController = CliController(setting);
return cliController.run();
} else {
auto guiController = GuiController(setting);
return guiController.run(argc, argv);
}
} | 29.5 | 52 | 0.66586 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.