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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9ed38b1b2b3d4b848d5b34d58e3c61a289f243aa | 4,404 | cpp | C++ | openstudiocore/src/openstudio_lib/ModelObjectTreeWidget.cpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/openstudio_lib/ModelObjectTreeWidget.cpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/openstudio_lib/ModelObjectTreeWidget.cpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <openstudio_lib/ModelObjectTreeWidget.hpp>
#include <openstudio_lib/ModelObjectTreeItems.hpp>
#include <model/Model.hpp>
#include <model/Model_Impl.hpp>
#include <model/ModelObject.hpp>
#include <model/ModelObject_Impl.hpp>
#include <utilities/core/Assert.hpp>
#include <QVBoxLayout>
#include <QTreeWidget>
#include <QPainter>
#include <QTimer>
namespace openstudio {
ModelObjectTreeWidget::ModelObjectTreeWidget(const model::Model& model, QWidget* parent )
: OSItemSelector(parent), m_model(model)
{
m_vLayout = new QVBoxLayout();
m_vLayout->setContentsMargins(0,7,0,0);
m_vLayout->setSpacing(7);
setLayout(m_vLayout);
m_treeWidget = new QTreeWidget(parent);
m_treeWidget->setStyleSheet("QTreeWidget { border: none; border-top: 1px solid black; }");
m_treeWidget->setAttribute(Qt::WA_MacShowFocusRect,0);
m_vLayout->addWidget(m_treeWidget);
bool isConnected = false;
isConnected = connect(model.getImpl<model::detail::Model_Impl>().get(),
SIGNAL(addWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),
this,
SLOT(objectAdded(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),
Qt::QueuedConnection);
OS_ASSERT(isConnected);
isConnected = connect(model.getImpl<model::detail::Model_Impl>().get(),
SIGNAL(removeWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),
this,
SLOT(objectRemoved(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),
Qt::QueuedConnection);
OS_ASSERT(isConnected);
}
OSItem* ModelObjectTreeWidget::selectedItem() const
{
// todo: something
return NULL;
}
QTreeWidget* ModelObjectTreeWidget::treeWidget() const
{
return m_treeWidget;
}
QVBoxLayout* ModelObjectTreeWidget::vLayout() const
{
return m_vLayout;
}
openstudio::model::Model ModelObjectTreeWidget::model() const
{
return m_model;
}
void ModelObjectTreeWidget::objectAdded(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> impl, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)
{
onObjectAdded(impl->getObject<model::ModelObject>(), iddObjectType, handle);
}
void ModelObjectTreeWidget::objectRemoved(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> impl, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)
{
onObjectRemoved(impl->getObject<model::ModelObject>(), iddObjectType, handle);
}
void ModelObjectTreeWidget::refresh()
{
int N = m_treeWidget->topLevelItemCount();
for (int i = 0; i < N; ++i){
QTreeWidgetItem* treeItem = m_treeWidget->topLevelItem(i);
ModelObjectTreeItem* modelObjectTreeItem = dynamic_cast<ModelObjectTreeItem*>(treeItem);
if(modelObjectTreeItem){
if (!modelObjectTreeItem->isDirty()){
modelObjectTreeItem->makeDirty();
QTimer::singleShot(0, modelObjectTreeItem, SLOT(refresh()));
}
}
}
}
} // openstudio
| 38.295652 | 188 | 0.68574 | [
"model",
"solid"
] |
9ed3c074acfc1c1e865219e20b41b9a289cd85e3 | 16,664 | cc | C++ | wrappers/7.0.0/vtkSimpleCellTessellatorWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/7.0.0/vtkSimpleCellTessellatorWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/7.0.0/vtkSimpleCellTessellatorWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkGenericCellTessellatorWrap.h"
#include "vtkSimpleCellTessellatorWrap.h"
#include "vtkObjectWrap.h"
#include "vtkGenericAdaptorCellWrap.h"
#include "vtkGenericAttributeCollectionWrap.h"
#include "vtkDoubleArrayWrap.h"
#include "vtkCellArrayWrap.h"
#include "vtkPointDataWrap.h"
#include "vtkGenericDataSetWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkSimpleCellTessellatorWrap::ptpl;
VtkSimpleCellTessellatorWrap::VtkSimpleCellTessellatorWrap()
{ }
VtkSimpleCellTessellatorWrap::VtkSimpleCellTessellatorWrap(vtkSmartPointer<vtkSimpleCellTessellator> _native)
{ native = _native; }
VtkSimpleCellTessellatorWrap::~VtkSimpleCellTessellatorWrap()
{ }
void VtkSimpleCellTessellatorWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkSimpleCellTessellator").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("SimpleCellTessellator").ToLocalChecked(), ConstructorGetter);
}
void VtkSimpleCellTessellatorWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkSimpleCellTessellatorWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkGenericCellTessellatorWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkGenericCellTessellatorWrap::ptpl));
tpl->SetClassName(Nan::New("VtkSimpleCellTessellatorWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "GetFixedSubdivisions", GetFixedSubdivisions);
Nan::SetPrototypeMethod(tpl, "getFixedSubdivisions", GetFixedSubdivisions);
Nan::SetPrototypeMethod(tpl, "GetGenericCell", GetGenericCell);
Nan::SetPrototypeMethod(tpl, "getGenericCell", GetGenericCell);
Nan::SetPrototypeMethod(tpl, "GetMaxAdaptiveSubdivisions", GetMaxAdaptiveSubdivisions);
Nan::SetPrototypeMethod(tpl, "getMaxAdaptiveSubdivisions", GetMaxAdaptiveSubdivisions);
Nan::SetPrototypeMethod(tpl, "GetMaxSubdivisionLevel", GetMaxSubdivisionLevel);
Nan::SetPrototypeMethod(tpl, "getMaxSubdivisionLevel", GetMaxSubdivisionLevel);
Nan::SetPrototypeMethod(tpl, "Initialize", Initialize);
Nan::SetPrototypeMethod(tpl, "initialize", Initialize);
Nan::SetPrototypeMethod(tpl, "IsA", IsA);
Nan::SetPrototypeMethod(tpl, "isA", IsA);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "Reset", Reset);
Nan::SetPrototypeMethod(tpl, "reset", Reset);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetFixedSubdivisions", SetFixedSubdivisions);
Nan::SetPrototypeMethod(tpl, "setFixedSubdivisions", SetFixedSubdivisions);
Nan::SetPrototypeMethod(tpl, "SetMaxSubdivisionLevel", SetMaxSubdivisionLevel);
Nan::SetPrototypeMethod(tpl, "setMaxSubdivisionLevel", SetMaxSubdivisionLevel);
Nan::SetPrototypeMethod(tpl, "SetSubdivisionLevels", SetSubdivisionLevels);
Nan::SetPrototypeMethod(tpl, "setSubdivisionLevels", SetSubdivisionLevels);
Nan::SetPrototypeMethod(tpl, "Tessellate", Tessellate);
Nan::SetPrototypeMethod(tpl, "tessellate", Tessellate);
Nan::SetPrototypeMethod(tpl, "Triangulate", Triangulate);
Nan::SetPrototypeMethod(tpl, "triangulate", Triangulate);
#ifdef VTK_NODE_PLUS_VTKSIMPLECELLTESSELLATORWRAP_INITPTPL
VTK_NODE_PLUS_VTKSIMPLECELLTESSELLATORWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkSimpleCellTessellatorWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkSimpleCellTessellator> native = vtkSmartPointer<vtkSimpleCellTessellator>::New();
VtkSimpleCellTessellatorWrap* obj = new VtkSimpleCellTessellatorWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkSimpleCellTessellatorWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClassName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkSimpleCellTessellatorWrap::GetFixedSubdivisions(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetFixedSubdivisions();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkSimpleCellTessellatorWrap::GetGenericCell(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
vtkGenericAdaptorCell * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetGenericCell();
VtkGenericAdaptorCellWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkGenericAdaptorCellWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkGenericAdaptorCellWrap *w = new VtkGenericAdaptorCellWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkSimpleCellTessellatorWrap::GetMaxAdaptiveSubdivisions(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaxAdaptiveSubdivisions();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkSimpleCellTessellatorWrap::GetMaxSubdivisionLevel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaxSubdivisionLevel();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkSimpleCellTessellatorWrap::Initialize(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkGenericDataSetWrap::ptpl))->HasInstance(info[0]))
{
VtkGenericDataSetWrap *a0 = ObjectWrap::Unwrap<VtkGenericDataSetWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Initialize(
(vtkGenericDataSet *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSimpleCellTessellatorWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->IsA(
*a0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSimpleCellTessellatorWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
vtkSimpleCellTessellator * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkSimpleCellTessellatorWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkSimpleCellTessellatorWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkSimpleCellTessellatorWrap *w = new VtkSimpleCellTessellatorWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkSimpleCellTessellatorWrap::Reset(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Reset();
}
void VtkSimpleCellTessellatorWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
vtkSimpleCellTessellator * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObject *) a0->native.GetPointer()
);
VtkSimpleCellTessellatorWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkSimpleCellTessellatorWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkSimpleCellTessellatorWrap *w = new VtkSimpleCellTessellatorWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSimpleCellTessellatorWrap::SetFixedSubdivisions(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetFixedSubdivisions(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSimpleCellTessellatorWrap::SetMaxSubdivisionLevel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMaxSubdivisionLevel(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSimpleCellTessellatorWrap::SetSubdivisionLevels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() > 1 && info[1]->IsInt32())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetSubdivisionLevels(
info[0]->Int32Value(),
info[1]->Int32Value()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSimpleCellTessellatorWrap::Tessellate(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkGenericAdaptorCellWrap::ptpl))->HasInstance(info[0]))
{
VtkGenericAdaptorCellWrap *a0 = ObjectWrap::Unwrap<VtkGenericAdaptorCellWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkGenericAttributeCollectionWrap::ptpl))->HasInstance(info[1]))
{
VtkGenericAttributeCollectionWrap *a1 = ObjectWrap::Unwrap<VtkGenericAttributeCollectionWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsObject() && (Nan::New(VtkDoubleArrayWrap::ptpl))->HasInstance(info[2]))
{
VtkDoubleArrayWrap *a2 = ObjectWrap::Unwrap<VtkDoubleArrayWrap>(info[2]->ToObject());
if(info.Length() > 3 && info[3]->IsObject() && (Nan::New(VtkCellArrayWrap::ptpl))->HasInstance(info[3]))
{
VtkCellArrayWrap *a3 = ObjectWrap::Unwrap<VtkCellArrayWrap>(info[3]->ToObject());
if(info.Length() > 4 && info[4]->IsObject() && (Nan::New(VtkPointDataWrap::ptpl))->HasInstance(info[4]))
{
VtkPointDataWrap *a4 = ObjectWrap::Unwrap<VtkPointDataWrap>(info[4]->ToObject());
if(info.Length() != 5)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Tessellate(
(vtkGenericAdaptorCell *) a0->native.GetPointer(),
(vtkGenericAttributeCollection *) a1->native.GetPointer(),
(vtkDoubleArray *) a2->native.GetPointer(),
(vtkCellArray *) a3->native.GetPointer(),
(vtkPointData *) a4->native.GetPointer()
);
return;
}
}
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSimpleCellTessellatorWrap::Triangulate(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSimpleCellTessellatorWrap *wrapper = ObjectWrap::Unwrap<VtkSimpleCellTessellatorWrap>(info.Holder());
vtkSimpleCellTessellator *native = (vtkSimpleCellTessellator *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkGenericAdaptorCellWrap::ptpl))->HasInstance(info[0]))
{
VtkGenericAdaptorCellWrap *a0 = ObjectWrap::Unwrap<VtkGenericAdaptorCellWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkGenericAttributeCollectionWrap::ptpl))->HasInstance(info[1]))
{
VtkGenericAttributeCollectionWrap *a1 = ObjectWrap::Unwrap<VtkGenericAttributeCollectionWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsObject() && (Nan::New(VtkDoubleArrayWrap::ptpl))->HasInstance(info[2]))
{
VtkDoubleArrayWrap *a2 = ObjectWrap::Unwrap<VtkDoubleArrayWrap>(info[2]->ToObject());
if(info.Length() > 3 && info[3]->IsObject() && (Nan::New(VtkCellArrayWrap::ptpl))->HasInstance(info[3]))
{
VtkCellArrayWrap *a3 = ObjectWrap::Unwrap<VtkCellArrayWrap>(info[3]->ToObject());
if(info.Length() > 4 && info[4]->IsObject() && (Nan::New(VtkPointDataWrap::ptpl))->HasInstance(info[4]))
{
VtkPointDataWrap *a4 = ObjectWrap::Unwrap<VtkPointDataWrap>(info[4]->ToObject());
if(info.Length() != 5)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Triangulate(
(vtkGenericAdaptorCell *) a0->native.GetPointer(),
(vtkGenericAttributeCollection *) a1->native.GetPointer(),
(vtkDoubleArray *) a2->native.GetPointer(),
(vtkCellArray *) a3->native.GetPointer(),
(vtkPointData *) a4->native.GetPointer()
);
return;
}
}
}
}
}
Nan::ThrowError("Parameter mismatch");
}
| 36.147505 | 123 | 0.733917 | [
"object"
] |
9ee3acc3232f1a0a8f2558b1cdab49819c83262c | 3,626 | cpp | C++ | ofApp.cpp | sublimationAC/DDE | fcde429b0db65100b8bd8bf607626b6beff8a431 | [
"MIT"
] | null | null | null | ofApp.cpp | sublimationAC/DDE | fcde429b0db65100b8bd8bf607626b6beff8a431 | [
"MIT"
] | 1 | 2019-01-05T06:12:34.000Z | 2019-01-08T06:20:18.000Z | ofApp.cpp | sublimationAC/DDE | fcde429b0db65100b8bd8bf607626b6beff8a431 | [
"MIT"
] | null | null | null | #include "ofApp.h"
//#define test_coef
Mesh_my mesh;
Eigen::VectorXi cor(G_inner_land_num);
Eigen::MatrixX3f coef_land;
Eigen::MatrixX3f coef_mesh;
const int test_coef_num = 3;
//--------------------------------------------------------------
void ofApp::setup(){
init_mesh("D:\\sydney\\first\\data\\Tester_ (1)\\TrainingPose/pose_1.obj",mesh);
FILE *fp;
fopen_s(&fp, "D:\\sydney\\first\\code\\2017\\cal_coeffience_Q_M_u_e_3\\cal_coeffience_Q_M_u_e_3/inner_vertex_corr.txt", "r");
for (int i = 0; i<G_inner_land_num; i++)
fscanf_s(fp, "%d", &cor(i));
fclose(fp);
#ifdef test_coef
get_silhouette_vertex(mesh);
get_coef_land(coef_land);
get_coef_mesh(coef_mesh);
test_coef_mesh(mesh, coef_mesh, test_coef_num);
#endif // test_coef
lights.resize(2);
float light_distance = 300.;
lights[0].setPosition(2.0*light_distance, 1.0*light_distance, 0.);
lights[1].setPosition(-1.0*light_distance, -1.0*light_distance, -1.0* light_distance);
}
//--------------------------------------------------------------
void ofApp::update(){
//cameraOrbit += ofGetLastFrameTime() * 20.; // 20 degrees per second;
//cam.orbitDeg(cameraOrbit, 0., cam.getDistance(), { 0., 0., 0. });
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackgroundGradient(ofColor(200), ofColor(25));
glEnable(GL_DEPTH_TEST);//?????
ofEnableLighting();
for (int i = 0; i < lights.size(); ++i) { lights[i].enable(); }
cam.begin(); //?????????????
//ofPushMatrix();
//ofTranslate(500, 250);
//ofSetColor(ofColor(255, 5, 0));
ofScale(ofGetWidth() / 5);
//check_2d_3d_corr(mesh, cor);
ofSetColor(ofColor(255, 255, 250));
check_2d_3d_out_corr(mesh);
test_slt();
#ifdef test_coef
ofSetColor(ofColor(255, 0, 5));
ofScale(ofGetWidth() / 5);
test_coef_land(coef_land, test_coef_num);
#endif
ofSetColor(ofColor(133, 180, 250));
//ofScale(ofGetWidth() / 5);
draw_mesh(mesh);
//ofSetColor(ofColor(255, 255, 250));
//ofScale(ofGetWidth() / 5);
//check_2d_3d_out_corr(mesh);
//draw_line(mesh,0);
//check_2d_3d_corr(mesh);
//ofPopMatrix();
//sleep(10);
//ofDrawCircle(10, 100, 10);
cam.end();
for (int i = 0; i < lights.size(); i++) { lights[i].disable(); }
ofDisableLighting();
glDisable(GL_DEPTH_TEST);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 25.180556 | 127 | 0.483729 | [
"mesh"
] |
9eea6fcf585df93c3e2855c9f1f61a89f919e265 | 17,076 | cpp | C++ | cppconsole_win/helloctp/console.cpp | yuanfengyun/helloctp | 9113473ef6b4b6f0738e07280be7bd22f6bece73 | [
"MIT"
] | 8 | 2021-07-16T09:27:26.000Z | 2021-08-11T07:31:37.000Z | cppconsole_win/helloctp/console.cpp | yuanfengyun/helloctp | 9113473ef6b4b6f0738e07280be7bd22f6bece73 | [
"MIT"
] | null | null | null | cppconsole_win/helloctp/console.cpp | yuanfengyun/helloctp | 9113473ef6b4b6f0738e07280be7bd22f6bece73 | [
"MIT"
] | 1 | 2021-11-11T18:12:11.000Z | 2021-11-11T18:12:11.000Z | #include<string>
#include<cstring>
#include<stdio.h>
#include<map>
#include<vector>
#include<iostream>
//#include <readline/history.h>
#include "ThostFtdcUserApiStruct.h"
#include "console.h"
#include "util.h"
#include "msg.h"
#include "td_op.h"
#include "md_op.h"
#include "position.h"
#include "wxy_schedule.h"
using namespace std;
bool position_inited = false;
map<string,CThostFtdcDepthMarketDataField*> market_datas;
map<string,CThostFtdcInvestorPositionField*> position_datas;
map<string,CThostFtdcTradeField*> trade_datas;
map<string,CThostFtdcOrderField*> order_datas;
map<string,Position*> positions;
map<string,int> wxy_long_datas;
map<string,int> wxy_short_datas;
map<string,string> diff_map;
WxySchedule* schedule = NULL;
int n_2_order_n = 0;
map<int,string> n_2_order;
map<string,int> order_2_n;
map<string,int> ordersysid_2_key;
map<string,string> ordersysid_2_order;
void init_wxy_schedule(char* filename){
schedule = new WxySchedule;
schedule->init(filename);
}
int get_order_id(CThostFtdcOrderField* p){
char key_buff[256]={0};
sprintf(key_buff,"%d-%d-%s",p->FrontID,p->SessionID,p->OrderRef);
string key = string(key_buff);
auto it = order_2_n.find(key);
if(it ==order_2_n.end()) return 0;
return it->second;
}
void update_position_with_trade(CThostFtdcTradeField* t)
{
string key = t->InstrumentID;
auto itp = positions.find(key);
Position* p = NULL;
if(itp == positions.end()){
p = new Position(t->ExchangeID,t->InstrumentID);
positions[key] = p;
}else{
p = itp->second;
}
// ¿ª²Ö
if(t->OffsetFlag==THOST_FTDC_OF_Open){
if(t->Direction == THOST_FTDC_D_Buy){
p->Long += t->Volume;
}
else if(t->Direction == THOST_FTDC_D_Sell){
p->Short += t->Volume;
}
}else{
if(t->Direction == THOST_FTDC_D_Buy){
p->Short -= t->Volume;
}
else if(t->Direction == THOST_FTDC_D_Sell){
p->Long -= t->Volume;
}
}
}
// 开仓锁定(money)
int get_open_frozen(){
}
void update_position_with_order(){
}
float GetOrderPrice1(CThostFtdcTradeField* p){
auto it = ordersysid_2_order.find(string(p->OrderSysID));
if(it != ordersysid_2_order.end()){
auto it_order = order_datas.find(it->second);
if(it_order != order_datas.end() && it_order->second->OrderPriceType==THOST_FTDC_OPT_LimitPrice){
return it_order->second->LimitPrice;
}
}
return p->Price;
}
void* handle_msg(Msg* msg)
{
char key_buff[512];
memset(key_buff,0,sizeof(key_buff));
if(msg->id == msg_market_data){
auto* p = (CThostFtdcDepthMarketDataField*)msg->ptr;
string ins = string(p->InstrumentID);
auto it = market_datas.find(ins);
if(it!=market_datas.end()){
delete it->second;
}
market_datas[ins] = p;
//printf("data haha\n");
}
if(msg->id == msg_position_data){
//printf("position data\n");
auto* p = (CThostFtdcInvestorPositionField*)msg->ptr;
string ins = string(p->InstrumentID);
auto itp = positions.find(ins);
if(itp == positions.end()){
positions[ins] = new Position(p);
}else{
if(p->PosiDirection == THOST_FTDC_PD_Long){
itp->second->LastLong = p->YdPosition;
itp->second->Long = p->Position;
}
else if(p->PosiDirection == THOST_FTDC_PD_Short){
itp->second->LastShort = p->YdPosition;
itp->second->Short = p->Position;
}
}
// 根据成交记录整理出当前持仓
if(msg->isLast){
for(auto it = trade_datas.begin();it!=trade_datas.end();it++){
//dpdate_position_with_trade(it->second);
}
position_inited = true;
if(schedule !=NULL && market_datas.find(schedule->m_name)!=market_datas.end()) schedule->run();
}
ins += " ";
ins += getPositionDir(p->PosiDirection);
auto it = position_datas.find(ins);
if(it!=position_datas.end()){
delete it->second;
}
position_datas[ins] = p;
//printf("position msg:%s\n",ins.c_str());
}
if(msg->id == msg_trade_data){
auto* p = (CThostFtdcTradeField*)msg->ptr;
sprintf(key_buff,"%s-%s-%s-%s-%c",p->TradeDate,p->TradeTime,p->InstrumentID,p->TradeID,p->Direction);
string key = string(key_buff);
auto it = trade_datas.find(key);
if(it!=trade_datas.end()){
delete it->second;
return 0;
}
trade_datas[key] = p;
int id = ordersysid_2_key[string(p->OrderSysID)];
if(position_inited){
printf("[notify] %s ³É½»: %4d %s\t%s %s %6.0f %3dÊÖ\n",p->TradeTime,id,p->InstrumentID,
getDir(p->Direction),getOffset(p->OffsetFlag),p->Volume,p->Price);
update_position_with_trade(p);
auto it_long = wxy_long_datas.find(p->InstrumentID);
auto it_short = wxy_short_datas.find(p->InstrumentID);
if(it_long != wxy_long_datas.end()){
if(p->Direction==THOST_FTDC_D_Buy && p->OffsetFlag==THOST_FTDC_OF_Open){
TdOp::ReqOrderInsert(p->InstrumentID,"sell","close",GetOrderPrice1(p)+it_long->second,p->Volume);
}else if(p->Direction==THOST_FTDC_D_Sell && p->OffsetFlag!=THOST_FTDC_OF_Open){
TdOp::ReqOrderInsert(p->InstrumentID,"buy","open",GetOrderPrice1(p)-it_long->second,p->Volume);
}
}
if(it_short != wxy_short_datas.end()){
if(p->Direction==THOST_FTDC_D_Buy && p->OffsetFlag!=THOST_FTDC_OF_Open){
TdOp::ReqOrderInsert(p->InstrumentID,"sell","open",GetOrderPrice1(p)+it_short->second,p->Volume);
}else if(p->Direction==THOST_FTDC_D_Sell && p->OffsetFlag==THOST_FTDC_OF_Open){
TdOp::ReqOrderInsert(p->InstrumentID,"buy","close",GetOrderPrice1(p)-it_short->second,p->Volume);
}
}
}
}
if(msg->id == msg_order_data){
auto* p = (CThostFtdcOrderField*)msg->ptr;
sprintf(key_buff,"%d-%d-%s",p->FrontID,p->SessionID,p->OrderRef);
string key = string(key_buff);
auto it = order_datas.find(key);
int id = 0;
bool show = true;
if(it!=order_datas.end()){
id = order_2_n[key];
show = it->second->OrderStatus != p->OrderStatus;
delete it->second;
}else{
id = ++n_2_order_n;
order_2_n[key] = id;
}
order_datas[key] = p;
n_2_order[id] = key;
if(p->OrderSysID[0] > 0){
ordersysid_2_key[string(p->OrderSysID)] = id;
ordersysid_2_order[string(p->OrderSysID)] = key;
}
if(position_inited)
if(p->OrderStatus != THOST_FTDC_OST_AllTraded &&
p->OrderStatus != THOST_FTDC_OST_PartTradedQueueing &&
p->OrderStatus != THOST_FTDC_OST_Unknown && show)
printf("[notify] %s 订单: %4d %s\t%s %s %6.0lf %3d/%d\t 状态:%c %s\n",
p->InsertTime, id, p->InstrumentID,
getDir(p->Direction),getOffset(p->CombOffsetFlag[0]),
p->LimitPrice,p->VolumeTraded,p->VolumeTotalOriginal,p->OrderStatus,
getOrderStatus(p->OrderStatus,p->OrderSubmitStatus,p->StatusMsg).c_str());
}
}
void handle_cmd(char* cmd)
{
if(strlen(cmd)==0) return;
string scmd(cmd);
vector<std::string> array = splitWithStl(scmd," ");
string c = array[0];
if(c == ("help")){
printf("=============================\n");
printf("s or show (行情)\n");
printf("o (有效委托)\n");
printf("oo (所有委托)\n");
printf("r or trade (成交记录)\n");
printf("p (持仓)\n");
printf("kk 09 4 4600 (空4手09)\n");
printf("pk 09 4 4600 (平4手09空单)\n");
printf("kd 09 4 4600 (多4手09)\n");
printf("pd 09 4 4600 (平4手09多单)\n");
printf("zt 09 10 (多09空10各1手)\n");
printf("ft 09 10 (空09多10各1手)\n");
printf("pzt 09 10 (平多09空10各1手)\n");
printf("pft 09 10 (平空09多10各1手)\n");
printf("wxy kd 09 10 (10个点网格刷09多单)\n");
printf("wxy kk 09 10 (10个点网格刷09空单)\n");
printf("wxy cd 09 (取消刷09多单)\n");
printf("wxy ck 09 (取消刷09空单)\n");
}
if(c==string("cls") || c == string("clear")){
printf("\033[2J");
}
else if(c == string("s") || c == string("show")){
printf("========\n");
for(auto it=market_datas.begin();it!=market_datas.end();++it)
{
auto p = it->second;
printf("%s\t%5d %5d %5d %5d %d\t%d\n",
p->InstrumentID,
int(p->BidPrice1),
int(p->AskPrice1),
int(p->HighestPrice),
int(p->LowestPrice),
int(p->OpenInterest - p->PreOpenInterest),
int(p->OpenInterest));
}
for(auto it=diff_map.begin();it!=diff_map.end();++it){
string first = getFullName(it->first);
string second = getFullName(it->second);
auto it_first = market_datas.find(first);
auto it_second = market_datas.find(second);
if(it_first != market_datas.end() && it_second != market_datas.end()){
auto p1 = it_first->second;
auto p2 = it_second ->second;
printf("%s-%s\t%5d %5d\n",
it->first.c_str(),
it->second.c_str(),
int(p1->BidPrice1 - p2->AskPrice1),
int(p1->AskPrice1 - p2->BidPrice1));
}
}
}
else if(c == string("kd")){
if(array.size() < 3){
return;
}
string price = "";
if(array.size()>3)
price = array[3];
TdOp::ReqOrderInsert(array[1],"buy","open",price,array[2]);
}
else if(c == string("kk")){
if(array.size() < 3){
return;
}
string price = "";
if(array.size()>3)
price = array[3];
TdOp::ReqOrderInsert(array[1],"sell","open",price,array[2]);
}
else if(c == string("pd")){
if(array.size() < 3){
return;
}
string price = "";
if(array.size()>3)
price = array[3];
TdOp::ReqOrderInsert(array[1],"sell","close",price,array[2]);
}
else if(c == string("pk")){
if(array.size() < 3){
return;
}
string price = "";
if(array.size()>3)
price = array[3];
TdOp::ReqOrderInsert(array[1],"buy","close",price,array[2]);
}
else if(c == string("zt")){
if(array.size() < 3){
return;
}
TdOp::ReqOrderInsert(array[1],"buy","open","","1");
TdOp::ReqOrderInsert(array[2],"sell","open","","1");
}
else if(c == string("ft")){
if(array.size() < 3){
return;
}
TdOp::ReqOrderInsert(array[1],"sell","open","","1");
TdOp::ReqOrderInsert(array[2],"buy","open","","1");
}
else if(c == string("pzt")){
if(array.size() < 3){
return;
}
TdOp::ReqOrderInsert(array[1],"sell","close","","1");
TdOp::ReqOrderInsert(array[2],"buy","close","","1");
}
else if(c == string("pft")){
if(array.size() < 3){
return;
}
TdOp::ReqOrderInsert(array[1],"buy","close","","1");
TdOp::ReqOrderInsert(array[2],"sell","close","","1");
}
else if(c == string("p")){
printf("====position====\n");
for(auto it=positions.begin();it!=positions.end();++it)
{
if(it->second->Long == 0 && it->second->Short == 0) continue;
printf("%s\t long:%3d frozen:%3d\tshort:%3d frozen:%3d\n",
it->second->InstrumentID,
it->second->Long,
get_close_frozen(it->second->InstrumentID,"sell"),
it->second->Short,
get_close_frozen(it->second->InstrumentID,"buy")
);
}
}
else if(c==string("t") || c == string("trade")){
printf("====trade====\n");
for(auto it=trade_datas.begin();it!=trade_datas.end();++it)
{
printf("%s %s %s %s%4d手 %.0lf\n",
it->second->TradeTime,
it->second->InstrumentID,
getDir(it->second->Direction),
getOffset(it->second->OffsetFlag),
it->second->Volume,
it->second->Price);
}
}
else if(c == string("o")){
printf("====valid order====\n");
for(auto it=order_datas.begin();it!=order_datas.end();++it)
{
if(it->second->OrderStatus != THOST_FTDC_OST_PartTradedQueueing && it->second->OrderStatus != THOST_FTDC_OST_NoTradeQueueing) continue;
string msg = GbkToUtf8(it->second->StatusMsg);
printf("%s %d\t%s\t%s %s %6.0lf %2d/%d\t %s\n",
it->second->InsertTime, get_order_id(it->second), it->second->InstrumentID,
getDir(it->second->Direction),getOffset(it->second->CombOffsetFlag[0]),
it->second->LimitPrice,it->second->VolumeTraded,it->second->VolumeTotalOriginal,msg.c_str());
}
}
else if(c == string("oo")){
printf("====all order====\n");
for(auto it=order_datas.begin();it!=order_datas.end();++it)
{
string msg = GbkToUtf8(it->second->StatusMsg);
printf("%s %4d\t%s\t%s %s %6.0lf %2d/%d\t %c %s\n",
it->second->InsertTime, get_order_id(it->second), it->second->InstrumentID,
getDir(it->second->Direction),getOffset(it->second->CombOffsetFlag[0]),
it->second->LimitPrice,it->second->VolumeTraded,it->second->VolumeTotalOriginal,
it->second->OrderStatus,msg.c_str());
}
}
else if(c == string("c")){
if (array.size() < 2) return;
for (int i = 1; i < array.size(); i++) {
if (!isInt(array[i].c_str())) return;
int no = atoi(array[i].c_str());
string key = n_2_order[no];
auto p = order_datas[key];
TdOp::ReqOrderAction(p);
}
}
else if(c == string("password")){
if(array.size() < 2) return;
TdOp::ReqUserPasswordUpdate(array[1].c_str());
}
else if(c == string("wxy")){
if(array.size()<2) return;
if(array[1] == string("kd")){
if(array.size()<4) return;
int i = atoi(array[3].c_str());
string name = getFullName(array[2]);
wxy_long_datas[name] = i;
}
if(array[1] == string("kk")){
if(array.size()<4) return;
int i = atoi(array[3].c_str());
string name = getFullName(array[2]);
wxy_short_datas[name] = i;
}
if(array[1] == string("cd")){
if(array.size()<3) return;
string name = getFullName(array[2]);
wxy_long_datas.erase(name);
}
if(array[1] == string("ck")){
if(array.size()<3) return;
string name = getFullName(array[2]);
wxy_short_datas.erase(name);
}
if(array[1]==string("show")){
printf("========wxy=======\n");
for(auto it=wxy_long_datas.begin();it!=wxy_long_datas.end();++it){
printf("long %s %d\n",it->first.c_str(),it->second);
}
for(auto it=wxy_short_datas.begin();it!=wxy_short_datas.end();++it){
printf("short %s %d\n",it->first.c_str(),it->second);
}
}
}
else if(c == string("sub")){
if(array.size() < 2) return;
for(int i=1;i<array.size();i++){
MdOp::SubscribeMarketData(getFullName(array[i]).c_str());
}
}
else if(c == string("df")){
if(array.size() < 3) return;
diff_map[array[1]] = array[2];
}
else if(c == string("call")){
for(auto it=order_datas.begin();it!=order_datas.end();++it)
{
if(it->second->OrderStatus != THOST_FTDC_OST_PartTradedQueueing && it->second->OrderStatus != THOST_FTDC_OST_NoTradeQueueing) continue;
TdOp::ReqOrderAction(it->second);
}
}
//add_history(cmd);
}
| 36.643777 | 148 | 0.513938 | [
"vector",
"3d"
] |
9eefca6367d181cbdb81d150df6c601978bffbce | 5,237 | cpp | C++ | Chapters/Chapter13/GoldenEgg/Source/GoldenEgg/Monster.cpp | PacktPublishing/Learning-Cpp-by-Creating-Games-with-Unreal-Engine-4-Second-Edition | 751edc780ba4c87d0a62acd53eacd9f562e06736 | [
"MIT"
] | null | null | null | Chapters/Chapter13/GoldenEgg/Source/GoldenEgg/Monster.cpp | PacktPublishing/Learning-Cpp-by-Creating-Games-with-Unreal-Engine-4-Second-Edition | 751edc780ba4c87d0a62acd53eacd9f562e06736 | [
"MIT"
] | null | null | null | Chapters/Chapter13/GoldenEgg/Source/GoldenEgg/Monster.cpp | PacktPublishing/Learning-Cpp-by-Creating-Games-with-Unreal-Engine-4-Second-Edition | 751edc780ba4c87d0a62acd53eacd9f562e06736 | [
"MIT"
] | null | null | null | #include "GoldenEgg.h"
#include "Monster.h"
#include "Avatar.h"
#include "Bullet.h"
#include "MeleeWeapon.h"
AMonster::AMonster(const class FObjectInitializer& PCIP) : Super(PCIP)
{
Speed = 20;
HitPoints = 20;
Experience = 0;
BPLoot = NULL;
BPMeleeWeapon = NULL;
AttackTimeout = 1.5f;
BPBullet = NULL;
BulletLaunchImpulse = 100;
MeleeWeapon = NULL;
TimeSinceLastStrike = 0;
SightSphere = PCIP.CreateDefaultSubobject<USphereComponent>(this, TEXT("SightSphere"));
SightSphere->AttachTo( RootComponent );
AttackRangeSphere = PCIP.CreateDefaultSubobject<USphereComponent>(this, TEXT("AttackRangeSphere"));
AttackRangeSphere->AttachTo( RootComponent );
}
void AMonster::PostInitializeComponents()
{
Super::PostInitializeComponents();
// instantiate the melee weapon if a bp was selected
if( BPMeleeWeapon )
{
MeleeWeapon = GetWorld()->SpawnActor<AMeleeWeapon>(
BPMeleeWeapon, FVector(0), FRotator(0) );
// Always check that this did not fail. If a blueprint
// that does not derive from AMeleeWeapon is selected,
// then the above line would fail.
if( MeleeWeapon )
{
MeleeWeapon->WeaponHolder = this;
const USkeletalMeshSocket *socket = GetMesh()->GetSocketByName( "RightHandSocket" );
socket->AttachActor( MeleeWeapon, GetMesh() );
}
else
{
FString msg = GetName() + FString( " cannot instantiate meleeweapon " ) +
BPMeleeWeapon->GetName();
GEngine->AddOnScreenDebugMessage( 0, 5.f, FColor::Yellow, msg );
}
}
}
void AMonster::Tick(float DeltaSeconds)
{
Super::Tick( DeltaSeconds );
AddMovementInput( Knockback, 1.f );
Knockback *= 0.5f;
// move the monster towards the player
AAvatar *avatar = Cast<AAvatar>( UGameplayStatics::GetPlayerPawn(GetWorld(), 0) );
if( !avatar ) return;
FVector playerPos = avatar->GetActorLocation();
FVector toPlayer = playerPos - GetActorLocation();
float distanceToPlayer = toPlayer.Size();
// If the player is not the SightSphere of the monster,
// go back
if( distanceToPlayer > SightSphere->GetScaledSphereRadius() )
{
// If the player is OS, then the enemy cannot chase
return;
}
toPlayer /= distanceToPlayer; // normalizes the vector
// At least face the target
// Gets you the rotator to turn something
// that looks in the `toPlayer` direction.
FRotator toPlayerRotation = toPlayer.Rotation();
toPlayerRotation.Pitch = 0; // 0 off the pitch
RootComponent->SetWorldRotation( toPlayerRotation );
if( isInAttackRange(distanceToPlayer) )
{
// Perform the attack.
if( !TimeSinceLastStrike )
{
// If the cooldown is over, then attack again
// This resets the hit parameter.
Attack(avatar);
}
TimeSinceLastStrike += DeltaSeconds;
if( TimeSinceLastStrike > AttackTimeout )
{
TimeSinceLastStrike = 0;
}
return; // nothing else to do.
}
else
{
if( MeleeWeapon )
{
// rest the melee weapon (not swinging)
MeleeWeapon->Rest();
}
// not in attack range, so walk towards player
AddMovementInput(toPlayer, Speed*DeltaSeconds);
}
}
void AMonster::Attack(AActor* thing)
{
// If a MeleeWeapon was assigned to the Monster,
// then MeleeWeapon will be non-null, and the monster
// should attack using the melee weapon.
if( MeleeWeapon )
{
MeleeWeapon->Swing();
}
// Otherwise, if there was no meleeweapon assigned,
// we check to see if the Monster is holding a Bullet blueprint class to use
else if( BPBullet )
{
// When the Monster is holding a bullet, we fire one.
// First, set a location for where the bullet would fly out of.
FVector nozzle = GetMesh()->GetBoneLocation( "RightHand" );
// move it fwd of the monster so it doesn't
// collide with the monster model.
FVector fwd = GetActorForwardVector();
nozzle += fwd * 155;
FVector toOpponent = thing->GetActorLocation() - nozzle;
toOpponent.Normalize();
ABullet *bullet = GetWorld()->SpawnActor<ABullet>(
BPBullet, nozzle, RootComponent->GetComponentRotation() );
if( bullet )
{
bullet->Firer = this;
bullet->ProxSphere->AddImpulse( fwd*BulletLaunchImpulse );
}
else
{
GEngine->AddOnScreenDebugMessage( 0, 5.f, FColor::Yellow,
"monster: no bullet actor could be spawned. is the bullet overlapping something?" );
}
}
}
float AMonster::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
Super::TakeDamage( Damage, DamageEvent, EventInstigator, DamageCauser );
HitPoints -= Damage;
Knockback = GetActorLocation() - DamageCauser->GetActorLocation();
Knockback.Normalize();
Knockback *= 500;
if( HitPoints <= 0 )
{
// award the avatar exp
AAvatar *avatar = Cast<AAvatar>( UGameplayStatics::GetPlayerPawn(GetWorld(), 0) );
avatar->Experience += Experience;
Destroy();
}
return Damage;
}
bool AMonster::isInAttackRangeOfPlayer()
{
AAvatar *avatar = Cast<AAvatar>( UGameplayStatics::GetPlayerPawn(GetWorld(), 0) );
if( !avatar ) return false;
FVector playerPos = avatar->GetActorLocation();
FVector toPlayer = playerPos - GetActorLocation();
float distanceToPlayer = toPlayer.Size();
return distanceToPlayer < AttackRangeSphere->GetScaledSphereRadius();
}
void AMonster::SwordSwung()
{
if( MeleeWeapon )
{
MeleeWeapon->Swing();
}
}
| 26.316583 | 132 | 0.713576 | [
"vector",
"model"
] |
9ef1415579d7e89165971a0481ea344aa4a523eb | 3,267 | cpp | C++ | heekscad/interface/HeeksObjDlg.cpp | JohnyEngine/CNC | e4c77250ab2b749d3014022cbb5eb9924e939993 | [
"Apache-2.0"
] | null | null | null | heekscad/interface/HeeksObjDlg.cpp | JohnyEngine/CNC | e4c77250ab2b749d3014022cbb5eb9924e939993 | [
"Apache-2.0"
] | null | null | null | heekscad/interface/HeeksObjDlg.cpp | JohnyEngine/CNC | e4c77250ab2b749d3014022cbb5eb9924e939993 | [
"Apache-2.0"
] | null | null | null | // HeeksObjDlg.cpp
// Copyright (c) 2010, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "HeeksObjDlg.h"
#include "PictureFrame.h"
#include "NiceTextCtrl.h"
BEGIN_EVENT_TABLE(HeeksObjDlg, HDialog)
EVT_CHILD_FOCUS(HeeksObjDlg::OnChildFocus)
END_EVENT_TABLE()
HeeksObjDlg::HeeksObjDlg(wxWindow *parent, HeeksObj* object, const wxString& title, bool top_level, bool picture)
: HDialog(parent, wxID_ANY, title)
{
m_object = object;
// add picture to right side
if(picture)
{
m_picture = new PictureWindow(this, wxSize(300, 200));
wxBoxSizer *pictureSizer = new wxBoxSizer(wxVERTICAL);
pictureSizer->Add(m_picture, 1, wxGROW);
rightControls.push_back(HControl(pictureSizer, wxALL));
}
else
{
m_picture = NULL;
}
if(top_level)
{
HeeksObjDlg::AddControlsAndCreate();
m_picture->SetFocus();
}
}
void HeeksObjDlg::GetData(HeeksObj* object)
{
if(m_ignore_event_functions)return;
m_ignore_event_functions = true;
GetDataRaw(object);
m_ignore_event_functions = false;
}
void HeeksObjDlg::SetFromData(HeeksObj* object)
{
bool save_ignore_event_functions = m_ignore_event_functions;
m_ignore_event_functions = true;
SetFromDataRaw(object);
m_ignore_event_functions = save_ignore_event_functions;
}
void HeeksObjDlg::GetDataRaw(HeeksObj* object)
{
}
void HeeksObjDlg::SetFromDataRaw(HeeksObj* object)
{
}
void HeeksObjDlg::SetPicture(const wxString& name)
{
SetPicture(name, _T("heeksobj"));
}
void HeeksObjDlg::SetPicture(const wxString& name, const wxString& folder)
{
if(m_picture)m_picture->SetPicture(
#ifdef HEEKSCAD
wxGetApp().GetResFolder()
#else
theApp.GetResFolder()
#endif
+ _T("/bitmaps/") + folder + _T("/") + name + _T(".png"), wxBITMAP_TYPE_PNG);
}
void HeeksObjDlg::SetPictureByWindow(wxWindow* w)
{
SetPicture(_T("general"));
}
void HeeksObjDlg::SetPicture()
{
wxWindow* w = FindFocus();
if(m_picture)
SetPictureByWindow(w);
}
void HeeksObjDlg::OnChildFocus(wxChildFocusEvent& event)
{
if(m_ignore_event_functions)return;
if(event.GetWindow())
{
SetPicture();
}
}
void HeeksObjDlg::OnComboOrCheck( wxCommandEvent& event )
{
if(m_ignore_event_functions)return;
SetPicture();
}
void HeeksObjDlg::AddControlsAndCreate()
{
m_ignore_event_functions = true;
wxBoxSizer *sizerMain = new wxBoxSizer(wxHORIZONTAL);
// add left sizer
wxBoxSizer *sizerLeft = new wxBoxSizer(wxVERTICAL);
sizerMain->Add( sizerLeft, 0, wxALL, control_border );
// add left controls
for(std::list<HControl>::iterator It = leftControls.begin(); It != leftControls.end(); It++)
{
HControl c = *It;
c.AddToSizer(sizerLeft);
}
// add right sizer
wxBoxSizer *sizerRight = new wxBoxSizer(wxVERTICAL);
sizerMain->Add( sizerRight, 0, wxALL, control_border );
// add OK and Cancel to right side
rightControls.push_back(MakeOkAndCancel(wxHORIZONTAL));
// add right controls
for(std::list<HControl>::iterator It = rightControls.begin(); It != rightControls.end(); It++)
{
HControl c = *It;
c.AddToSizer(sizerRight);
}
SetFromData(m_object);
SetSizer( sizerMain );
sizerMain->SetSizeHints(this);
sizerMain->Fit(this);
m_ignore_event_functions = false;
HeeksObjDlg::SetPicture();
} | 22.22449 | 113 | 0.734007 | [
"object"
] |
9ef1e6e1679a7f250a8a1b63f8ad469fb54286b2 | 4,858 | cpp | C++ | src/main.cpp | stastaj/Svit | 7b9487fb43d205383612dd55f938247be5f39d90 | [
"BSD-2-Clause"
] | null | null | null | src/main.cpp | stastaj/Svit | 7b9487fb43d205383612dd55f938247be5f39d90 | [
"BSD-2-Clause"
] | null | null | null | src/main.cpp | stastaj/Svit | 7b9487fb43d205383612dd55f938247be5f39d90 | [
"BSD-2-Clause"
] | null | null | null | #include "camera/perspective.h"
#include "engine/cosine_debugger.h"
#include "engine/ray_casting.h"
#include "engine/ray_tracing.h"
#include "geom/rect.h"
#include "geom/vector.h"
#include "geom/point.h"
#include "image/image.h"
#include "node/group/simple.h"
#include "node/solid/sphere.h"
#include "node/solid/infinite_plane.h"
#include "node/solid/disc.h"
#include "renderer/settings.h"
#include "renderer/serial/serial.h"
#include "renderer/parallel/parallel.h"
#include "supersampling/random.h"
#include "trajectory/bspline.h"
#include "world/world.h"
#include "material/lambertian.h"
#include "material/phong.h"
#include "material/mirror.h"
#include "texture/constant.h"
#include "texture/checkerboard.h"
#include "texture/perlin_noise.h"
#include "texture/wood_perlin_noise.h"
#include "texture/marble_perlin_noise.h"
#include "light/point.h"
#include "light/directional.h"
#include "light/ambient.h"
#include <iostream>
#include <sstream>
#include <cmath>
#include <thread>
#include <memory>
using namespace Svit;
World
get_wood_world ()
{
SimpleGroup *scene = new SimpleGroup();
InfinitePlane *plane = new InfinitePlane(Point3(0.0, 0.02, 0.0),
Vector3(0.0, 1.0, 0.0));
std::unique_ptr<Texture> checker_texture(new CheckerboardTexture(Vector3(0.5f,
0.5f, 0.5f), Vector3(1.0, 1.0, 1.0), 0.25));
std::unique_ptr<Material> plane_material(new LambertianMaterial(
std::move(checker_texture)));
plane->set_material(std::move(plane_material));
Sphere *sphere = new Sphere(Point3(-0.9, 0.35, 0.0), 0.35);
WoodPerlinNoiseTexture *wood_texture = new WoodPerlinNoiseTexture(
Vector3(149.0f/255.0f, 69.0f/255.0f, 53.0f/255.0f), Vector3(237.0f/255.0f,
201.0f/255.0f, 175.0f/255.0f));
wood_texture->add_octave(1.0, 3.0);
std::unique_ptr<Texture> wood_sphere_tex(wood_texture);
std::unique_ptr<Material> sphere_material(new LambertianMaterial(
std::move(wood_sphere_tex)));
sphere->set_material(std::move(sphere_material));
scene->add(plane);
scene->add(sphere);
PerspectiveCamera *camera = new PerspectiveCamera(
Point3(0.0, 0.75, -2.0),
Vector3(0.0, -0.1, 1.0),
Vector3(0.0, 1.0, 0.0),
Rectangle(Point2i(0, 0), Vector2i(1280, 720)).get_aspect_ratio(),
M_PI/2.0);
World world;
world.scene = scene;
world.camera = camera;
std::unique_ptr<Light> ambient_light(new AmbientLight(
Vector3(1.0f, 1.0f, 1.0f)));
world.add_light(std::move(ambient_light));
std::unique_ptr<Light> point_light(new PointLight(Point3(0.0, 1.5, 0.0),
Vector3(1.0f, 1.0f, 1.0f) * 3.0f));
world.add_light(std::move(point_light));
return world;
}
World
get_marble_world ()
{
SimpleGroup *scene = new SimpleGroup();
InfinitePlane *plane = new InfinitePlane(Point3(0.0, 0.02, 0.0),
Vector3(0.0, 1.0, 0.0));
std::unique_ptr<Texture> checker_texture(new CheckerboardTexture(Vector3(0.5f,
0.5f, 0.5f), Vector3(1.0, 1.0, 1.0), 4.25));
std::unique_ptr<Material> plane_material(new LambertianMaterial(
std::move(checker_texture)));
plane->set_material(std::move(plane_material));
MarblePerlinNoiseTexture *marble_texture = new MarblePerlinNoiseTexture(
Vector3(1.0f, 1.0f, 1.0f), Vector3(0.0f, 0.0f, 0.0f));
for (int i = 1; i < 1024; i*=2)
marble_texture->add_octave(1.0f/(float)i, (float)i);
std::unique_ptr<Texture> marble_sphere_tex(marble_texture);
std::unique_ptr<Material> marble_sphere_mat(new LambertianMaterial(
std::move(marble_sphere_tex)));
Sphere *sphere = new Sphere(Point3(12.8, 15.35, 2.0), 15.35);
sphere->set_material(std::move(marble_sphere_mat));
scene->add(plane);
scene->add(sphere);
PerspectiveCamera *camera = new PerspectiveCamera(
Point3(0.0, 24.75, -47.0),
Vector3(0.0, -0.1, 1.0),
Vector3(0.0, 1.0, 0.0),
Rectangle(Point2i(0, 0), Vector2i(1280, 720)).get_aspect_ratio(),
M_PI/2.0);
World world;
world.scene = scene;
world.camera = camera;
std::unique_ptr<Light> ambient_light(new AmbientLight(
Vector3(1.0f, 1.0f, 1.0f) * 3.0f));
world.add_light(std::move(ambient_light));
return world;
}
int
main (void)
{
Settings settings;
settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
settings.max_thread_count = std::thread::hardware_concurrency();
settings.tile_size = Vector2i(100, 100);
settings.max_sample_count = 4;
settings.adaptive_sample_step = 1000;
RayTracingEngine engine;
ParallelRenderer renderer;
RandomSuperSampling super_sampling(true);
World marble_world = get_marble_world();
World wood_world = get_wood_world();
Image marble_image = renderer.render(marble_world, settings, engine,
super_sampling);
marble_image.write(std::string("marble_output.png"));
Image wood_image = renderer.render(wood_world, settings, engine,
super_sampling);
wood_image.write(std::string("wood_output.png"));
return 0;
}
| 30.173913 | 80 | 0.722725 | [
"render",
"vector",
"solid"
] |
9ef285832ab5c2785195a1a5f0b53ee573896f0d | 1,839 | cpp | C++ | src/plugins/intel_myriad/graph_transformer/src/stages/clamp.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/plugins/intel_myriad/graph_transformer/src/stages/clamp.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/plugins/intel_myriad/graph_transformer/src/stages/clamp.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vpu/frontend/frontend.hpp>
#include <vector>
#include <memory>
#include <set>
#include <string>
#include <vpu/stages/post_op_stage.hpp>
namespace vpu {
namespace {
class ClampStage final : public PostOpStage {
public:
using PostOpStage::PostOpStage;
protected:
StagePtr cloneImpl() const override {
return std::make_shared<ClampStage>(*this);
}
void serializeParamsImpl(BlobSerializer& serializer) const override {
auto min_value = attrs().get<float>("min_value");
auto max_value = attrs().get<float>("max_value");
serializer.append(static_cast<float>(min_value));
serializer.append(static_cast<float>(max_value));
}
};
} // namespace
void FrontEnd::parseClamp(const Model& model, const ie::CNNLayerPtr& _layer, const DataVector& inputs, const DataVector& outputs) const {
IE_ASSERT(inputs.size() == 1);
IE_ASSERT(outputs.size() == 1);
auto layer = std::dynamic_pointer_cast<ie::ClampLayer>(_layer);
IE_ASSERT(layer != nullptr);
_stageBuilder->addClampStage(model, layer->name, layer, layer->min_value, layer->max_value, inputs[0], outputs[0]);
}
Stage StageBuilder::addClampStage(
const Model& model,
const std::string& name,
const ie::CNNLayerPtr& layer,
float min,
float max,
const Data& input,
const Data& output) {
auto stage = model->addNewStage<ClampStage>(
name,
StageType::Clamp,
layer,
{input},
{output});
stage->attrs().set<float>("min_value", min);
stage->attrs().set<float>("max_value", max);
return stage;
}
} // namespace vpu
| 25.901408 | 137 | 0.62534 | [
"vector",
"model"
] |
9ef48ee8551760c9bac5491a8c66218eebf8bb4d | 1,228 | cpp | C++ | lib/TestFrameworks/Test.cpp | OMantere/mull | 0333c4ced2c407e6fffc48f5fda21dc10ab32c8b | [
"Apache-2.0"
] | null | null | null | lib/TestFrameworks/Test.cpp | OMantere/mull | 0333c4ced2c407e6fffc48f5fda21dc10ab32c8b | [
"Apache-2.0"
] | null | null | null | lib/TestFrameworks/Test.cpp | OMantere/mull | 0333c4ced2c407e6fffc48f5fda21dc10ab32c8b | [
"Apache-2.0"
] | 1 | 2019-06-10T02:43:04.000Z | 2019-06-10T02:43:04.000Z | #include "mull/TestFrameworks/Test.h"
#include <mull/TestFrameworks/Test.h>
#include <utility>
using namespace mull;
Test::Test(std::string test, std::string program,
std::string driverFunctionName, std::vector<std::string> args,
llvm::Function *testBody)
: testName(std::move(test)), programName(std::move(program)),
driverFunctionName(std::move(driverFunctionName)),
arguments(std::move(args)), testBody(testBody) {}
std::string Test::getTestName() const { return testName; }
std::string Test::getProgramName() const { return programName; }
std::string Test::getDriverFunctionName() const { return driverFunctionName; }
std::string Test::getTestDisplayName() const { return getTestName(); }
std::string Test::getUniqueIdentifier() const { return getTestName(); }
const std::vector<std::string> &Test::getArguments() const { return arguments; }
const llvm::Function *Test::getTestBody() const { return testBody; }
void Test::setExecutionResult(ExecutionResult result) {
executionResult = std::move(result);
}
const ExecutionResult &Test::getExecutionResult() const {
return executionResult;
}
InstrumentationInfo &Test::getInstrumentationInfo() {
return instrumentationInfo;
}
| 37.212121 | 80 | 0.737785 | [
"vector"
] |
9ef92194ebf5943467987bd7a453daa184bb099c | 9,384 | cpp | C++ | third_party/angle/src/tests/gl_tests/BuiltinVariableTest.cpp | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/angle/src/tests/gl_tests/BuiltinVariableTest.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/angle/src/tests/gl_tests/BuiltinVariableTest.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | //
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BuiltinVariableTest:
// Tests the correctness of the builtin GLSL variables.
//
#include "test_utils/ANGLETest.h"
#include "test_utils/gl_raii.h"
using namespace angle;
class BuiltinVariableVertexIdTest : public ANGLETest
{
protected:
BuiltinVariableVertexIdTest()
{
setWindowWidth(64);
setWindowHeight(64);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
setConfigDepthBits(24);
}
void SetUp() override
{
ANGLETest::SetUp();
const std::string vsSource =
"#version 300 es\n"
"precision highp float;\n"
"in vec4 position;\n"
"in int expectedID;"
"out vec4 color;\n"
"\n"
"void main()\n"
"{\n"
" gl_Position = position;\n"
" color = vec4(gl_VertexID != expectedID, gl_VertexID == expectedID, 0.0, 1.0);"
"}\n";
const std::string fsSource =
"#version 300 es\n"
"precision highp float;\n"
"in vec4 color;\n"
"out vec4 fragColor;\n"
"void main()\n"
"{\n"
" fragColor = color;\n"
"}\n";
mProgram = CompileProgram(vsSource, fsSource);
ASSERT_NE(0u, mProgram);
mPositionLocation = glGetAttribLocation(mProgram, "position");
ASSERT_NE(-1, mPositionLocation);
mExpectedIdLocation = glGetAttribLocation(mProgram, "expectedID");
ASSERT_NE(-1, mExpectedIdLocation);
static const float positions[] =
{
0.5, 0.5,
-0.5, 0.5,
0.5, -0.5,
-0.5, -0.5
};
glGenBuffers(1, &mPositionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mPositionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
ASSERT_GL_NO_ERROR();
}
void TearDown() override
{
glDeleteBuffers(1, &mPositionBuffer);
glDeleteBuffers(1, &mExpectedIdBuffer);
glDeleteBuffers(1, &mIndexBuffer);
glDeleteProgram(mProgram);
ANGLETest::TearDown();
}
// Renders a primitive using the specified mode, each vertex color will
// be green if gl_VertexID is correct, red otherwise.
void runTest(GLuint drawMode, const std::vector<GLint> &indices, int count)
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glGenBuffers(1, &mIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * indices.size(), indices.data(),
GL_STATIC_DRAW);
std::vector<GLint> expectedIds = makeRange(count);
glGenBuffers(1, &mExpectedIdBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mExpectedIdBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLint) * expectedIds.size(), expectedIds.data(),
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, mPositionBuffer);
glVertexAttribPointer(mPositionLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(mPositionLocation);
glBindBuffer(GL_ARRAY_BUFFER, mExpectedIdBuffer);
glVertexAttribIPointer(mExpectedIdLocation, 1, GL_INT, 0, 0);
glEnableVertexAttribArray(mExpectedIdLocation);
glUseProgram(mProgram);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glDrawElements(drawMode, count, GL_UNSIGNED_INT, 0);
std::vector<GLColor> pixels(getWindowWidth() * getWindowHeight());
glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE,
pixels.data());
ASSERT_GL_NO_ERROR();
const GLColor green(0, 255, 0, 255);
const GLColor black(0, 0, 0, 255);
for (const auto &pixel : pixels)
{
EXPECT_TRUE(pixel == green || pixel == black);
}
}
std::vector<GLint> makeRange(int n) const
{
std::vector<GLint> result;
for (int i = 0; i < n; i++)
{
result.push_back(i);
}
return result;
}
GLuint mPositionBuffer = 0;
GLuint mExpectedIdBuffer = 0;
GLuint mIndexBuffer = 0;
GLuint mProgram = 0;
GLint mPositionLocation = -1;
GLint mExpectedIdLocation = -1;
};
// Test gl_VertexID when rendering points
TEST_P(BuiltinVariableVertexIdTest, Points)
{
runTest(GL_POINTS, makeRange(4), 4);
}
// Test gl_VertexID when rendering line strips
TEST_P(BuiltinVariableVertexIdTest, LineStrip)
{
runTest(GL_LINE_STRIP, makeRange(4), 4);
}
// Test gl_VertexID when rendering line loops
TEST_P(BuiltinVariableVertexIdTest, LineLoop)
{
runTest(GL_LINE_LOOP, makeRange(4), 4);
}
// Test gl_VertexID when rendering lines
TEST_P(BuiltinVariableVertexIdTest, Lines)
{
runTest(GL_LINES, makeRange(4), 4);
}
// Test gl_VertexID when rendering triangle strips
TEST_P(BuiltinVariableVertexIdTest, TriangleStrip)
{
runTest(GL_TRIANGLE_STRIP, makeRange(4), 4);
}
// Test gl_VertexID when rendering triangle fans
TEST_P(BuiltinVariableVertexIdTest, TriangleFan)
{
std::vector<GLint> indices;
indices.push_back(0);
indices.push_back(1);
indices.push_back(3);
indices.push_back(2);
runTest(GL_TRIANGLE_FAN, indices, 4);
}
// Test gl_VertexID when rendering triangles
TEST_P(BuiltinVariableVertexIdTest, Triangles)
{
std::vector<GLint> indices;
indices.push_back(0);
indices.push_back(1);
indices.push_back(2);
indices.push_back(1);
indices.push_back(2);
indices.push_back(3);
runTest(GL_TRIANGLES, indices, 6);
}
ANGLE_INSTANTIATE_TEST(BuiltinVariableVertexIdTest, ES3_D3D11(), ES3_OPENGL(), ES3_OPENGLES());
class BuiltinVariableFragDepthClampingFloatRBOTest : public ANGLETest
{
protected:
void SetUp() override
{
ANGLETest::SetUp();
// Writes a fixed detph value and green.
// Section 15.2.3 of the GL 4.5 specification says that conversion is not
// done but clamping is so the output depth should be in [0.0, 1.0]
const std::string depthFs =
R"(#version 300 es
precision highp float;
layout(location = 0) out vec4 fragColor;
uniform float u_depth;
void main(){
gl_FragDepth = u_depth;
fragColor = vec4(0.0, 1.0, 0.0, 1.0);
})";
mProgram = CompileProgram(essl3_shaders::vs::Simple(), depthFs);
ASSERT_NE(0u, mProgram);
mDepthLocation = glGetUniformLocation(mProgram, "u_depth");
ASSERT_NE(-1, mDepthLocation);
glBindTexture(GL_TEXTURE_2D, mColorTexture);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 1, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, mDepthTexture);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT32F, 1, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mColorTexture,
0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, mDepthTexture,
0);
ASSERT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER));
ASSERT_GL_NO_ERROR();
}
void TearDown() override
{
glDeleteProgram(mProgram);
ANGLETest::TearDown();
}
void CheckDepthWritten(float expectedDepth, float fsDepth)
{
glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
glUseProgram(mProgram);
// Clear to red, the FS will write green on success
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
// Clear to the expected depth so it will be compared to the FS depth with
// DepthFunc(GL_EQUAL)
glClearDepthf(expectedDepth);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUniform1f(mDepthLocation, fsDepth);
glDepthFunc(GL_EQUAL);
glEnable(GL_DEPTH_TEST);
drawQuad(mProgram, "a_position", 0.0f);
EXPECT_GL_NO_ERROR();
EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::green);
}
private:
GLuint mProgram;
GLint mDepthLocation;
GLTexture mColorTexture;
GLTexture mDepthTexture;
GLFramebuffer mFramebuffer;
};
// Test that gl_FragDepth is clamped above 0
TEST_P(BuiltinVariableFragDepthClampingFloatRBOTest, Above0)
{
CheckDepthWritten(0.0f, -1.0f);
}
// Test that gl_FragDepth is clamped below 1
TEST_P(BuiltinVariableFragDepthClampingFloatRBOTest, Below1)
{
CheckDepthWritten(1.0f, 42.0f);
}
ANGLE_INSTANTIATE_TEST(BuiltinVariableFragDepthClampingFloatRBOTest,
ES3_D3D11(),
ES3_OPENGL(),
ES3_OPENGLES());
| 30.270968 | 98 | 0.642263 | [
"vector"
] |
9efed660f639b841567e36f8fa13882f8659f40a | 8,570 | cxx | C++ | Qt/Widgets/pqHeaderView.cxx | zenotech/ParaView | ef43912dc10d7a02e8ae0bcc4aa778f44f57be80 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Qt/Widgets/pqHeaderView.cxx | zenotech/ParaView | ef43912dc10d7a02e8ae0bcc4aa778f44f57be80 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Qt/Widgets/pqHeaderView.cxx | zenotech/ParaView | ef43912dc10d7a02e8ae0bcc4aa778f44f57be80 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: ParaView
Module: pqHeaderView.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqHeaderView.h"
#include <QAbstractItemModel>
#include <QMouseEvent>
#include <QPainter>
#include <QStyle>
#include <QtDebug>
//-----------------------------------------------------------------------------
pqHeaderView::pqHeaderView(Qt::Orientation orientation, QWidget* parentObject)
: Superclass(orientation, parentObject)
, ToggleCheckStateOnSectionClick(false)
, CustomIndicatorShown(false)
{
if (orientation == Qt::Vertical)
{
qDebug("pqHeaderView currently doesn't support vertical headers. "
"You may encounter rendering artifacts.");
}
}
//-----------------------------------------------------------------------------
pqHeaderView::~pqHeaderView()
{
}
//-----------------------------------------------------------------------------
void pqHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
{
if (!rect.isValid())
{
return;
}
auto amodel = this->model();
const QVariant hdata = amodel->headerData(logicalIndex, this->orientation(), Qt::CheckStateRole);
if (!hdata.isValid())
{
// if the model is not giving any header data for CheckStateRole, then we
// don't have any check support; nothing to do.
this->Superclass::paintSection(painter, rect, logicalIndex);
return;
}
// fill background for the whole section.
QStyleOptionHeader hoption;
this->initStyleOption(&hoption);
hoption.section = logicalIndex;
hoption.rect = rect;
this->style()->drawControl(QStyle::CE_HeaderSection, &hoption, painter, this);
// draw the checkbox.
QStyleOptionViewItem coption;
coption.initFrom(this);
coption.features = QStyleOptionViewItem::HasCheckIndicator | QStyleOptionViewItem::HasDisplay;
coption.viewItemPosition = QStyleOptionViewItem::OnlyOne;
QRect checkRect =
this->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &coption, this);
checkRect.moveLeft(rect.x() + checkRect.x());
coption.rect = checkRect;
coption.state = coption.state & ~QStyle::State_HasFocus;
switch (hdata.value<Qt::CheckState>())
{
case Qt::Checked:
coption.state |= QStyle::State_On;
break;
case Qt::PartiallyChecked:
coption.state |= QStyle::State_NoChange;
break;
case Qt::Unchecked:
default:
coption.state |= QStyle::State_Off;
break;
}
this->style()->drawPrimitive(QStyle::PE_IndicatorViewItemCheck, &coption, painter, this);
// finally draw the header in offset by size of the checkbox.
// let's determine the location where the "label" would be typically drawn in
// an item when a check. we'll place the header text at that location.
QStyleOptionViewItem vioption;
vioption.initFrom(this);
vioption.features = QStyleOptionViewItem::HasCheckIndicator | QStyleOptionViewItem::HasDisplay;
vioption.viewItemPosition = QStyleOptionViewItem::OnlyOne;
const QRect r2 = this->style()->subElementRect(QStyle::SE_ItemViewItemText, &vioption, this);
QRect newrect = rect;
newrect.setLeft(newrect.x() + r2.x());
if (this->CustomIndicatorShown)
{
// adjust width so that sort indicator doesn't overlap with the custom
// indicators.
newrect.setRight(
newrect.right() - (checkRect.width() * static_cast<int>(this->CustomIndicatorIcons.size())));
}
painter->save();
this->Superclass::paintSection(painter, newrect, logicalIndex);
painter->restore();
// let's save the checkbox rect to handle clicks.
this->CheckRect = checkRect;
this->CustomIndicatorRects.clear();
if (this->CustomIndicatorShown)
{
int leftpos = newrect.right();
for (auto iter = this->CustomIndicatorIcons.rbegin(); iter != this->CustomIndicatorIcons.rend();
++iter)
{
const auto& icon = iter->first;
const auto& role = iter->second;
QRect ciRect = checkRect;
ciRect.moveTo(leftpos, ciRect.y());
this->style()->drawItemPixmap(painter, ciRect, Qt::AlignCenter, icon.pixmap(ciRect.size()));
this->CustomIndicatorRects.push_back(std::make_pair(ciRect, role));
leftpos += checkRect.width();
}
}
}
//-----------------------------------------------------------------------------
void pqHeaderView::mousePressEvent(QMouseEvent* evt)
{
this->PressPosition = evt->pos();
}
//-----------------------------------------------------------------------------
void pqHeaderView::mouseReleaseEvent(QMouseEvent* evt)
{
if ((evt->pos() - this->PressPosition).manhattanLength() < 3)
{
this->mouseClickEvent(evt);
}
this->PressPosition = QPoint();
}
//-----------------------------------------------------------------------------
void pqHeaderView::mouseClickEvent(QMouseEvent* evt)
{
if (evt->button() != Qt::LeftButton)
{
return;
}
if (auto amodel = this->model())
{
int logicalIndex = this->logicalIndexAt(evt->pos());
if (this->CustomIndicatorShown)
{
for (const auto& pair : this->CustomIndicatorRects)
{
const auto& rect = pair.first;
const auto& role = pair.second;
if (rect.contains(this->PressPosition))
{
Q_EMIT this->customIndicatorClicked(logicalIndex, rect.bottomLeft(), role);
return;
}
}
}
const QVariant hdata =
amodel->headerData(logicalIndex, this->orientation(), Qt::CheckStateRole);
if (hdata.isValid())
{
if (this->ToggleCheckStateOnSectionClick == true ||
(this->CheckRect.isValid() && this->CheckRect.contains(evt->pos())))
{
QVariant newdata;
// supports toggling checkstate.
switch (hdata.value<Qt::CheckState>())
{
case Qt::Checked:
newdata.setValue(Qt::Unchecked);
break;
default:
newdata.setValue(Qt::Checked);
break;
}
amodel->setHeaderData(logicalIndex, this->orientation(), newdata, Qt::CheckStateRole);
}
}
}
}
//-----------------------------------------------------------------------------
void pqHeaderView::setCustomIndicatorShown(bool val)
{
if (this->CustomIndicatorShown != val)
{
this->CustomIndicatorShown = val;
this->update();
}
}
//-----------------------------------------------------------------------------
void pqHeaderView::addCustomIndicatorIcon(const QIcon& icon, const QString& role)
{
for (auto& pair : this->CustomIndicatorIcons)
{
if (pair.second == role)
{
pair.first = icon;
return;
}
}
this->CustomIndicatorIcons.push_back(std::make_pair(icon, role));
this->update();
}
//-----------------------------------------------------------------------------
void pqHeaderView::removeCustomIndicatorIcon(const QString& role)
{
for (auto iter = this->CustomIndicatorIcons.begin(); iter != this->CustomIndicatorIcons.end();)
{
if (iter->second == role)
{
iter = this->CustomIndicatorIcons.erase(iter);
}
else
{
++iter;
}
}
}
//-----------------------------------------------------------------------------
QIcon pqHeaderView::customIndicatorIcon(const QString& role) const
{
for (auto& pair : this->CustomIndicatorIcons)
{
if (pair.second == role)
{
return pair.first;
}
}
return QIcon();
}
| 31.391941 | 100 | 0.610268 | [
"model"
] |
73031c6ad60aae71f7b725239fc349d3f6519d25 | 10,408 | cc | C++ | worker/initialAC/VeriNFsMB/src/element/middleboxLB.cc | zeyu-zh/MB-verifier | 800f6a926a5ebb4c0f14d7f9580111c38b9e7940 | [
"Apache-2.0"
] | null | null | null | worker/initialAC/VeriNFsMB/src/element/middleboxLB.cc | zeyu-zh/MB-verifier | 800f6a926a5ebb4c0f14d7f9580111c38b9e7940 | [
"Apache-2.0"
] | null | null | null | worker/initialAC/VeriNFsMB/src/element/middleboxLB.cc | zeyu-zh/MB-verifier | 800f6a926a5ebb4c0f14d7f9580111c38b9e7940 | [
"Apache-2.0"
] | null | null | null | #include <click/config.h>
#include <click/args.hh>
#include <click/error.hh>
#include <click/integers.hh>
#include <cmath>
#include <sys/socket.h>
#include "middleboxLB.hh"
#include "veritools.hh"
CLICK_DECLS
using namespace std;
MiddleboxLB::MiddleboxLB()
{
}
static bool veriSwitch = true;
static bool justSend = false;
static bool localMode = false;
static bool bothway = false;
static int batch_element_size = 1024;
static int maxPktUsed = 1024 * 10 * 10 + 200;
static bool lbInTheChain = false;
static bool fwInTheChain = false;
static bool idsInTheChain = false;
int
MiddleboxLB::configure(Vector<String> &conf, ErrorHandler* errh)
{
//if (Args(conf, errh)
// .complete() < 0)
//{
// return -1;
//}
// Parsing
int inChain;
if (Args(conf, errh)
//.read_m("PATTERN_FILE", m_config.pattern_file)
.read_m("BATCH_SIZE", batch_element_size)
.read_m("EXP_SIZE", maxPktUsed)
.read_m("VERIFY", veriSwitch)
.read_m("DISABLE_NETWORK", localMode)
.read_m("BASELINE", justSend)
.read_m("QUEYR_TABLE", bothway)
.read_m("IN_CHAIN", inChain)
.complete() < 0)
{
return -1;
}
if (inChain)
{
lbInTheChain = true;
fwInTheChain = true;
idsInTheChain = true;
}
else
{
lbInTheChain = false;
fwInTheChain = false;
idsInTheChain = false;
}
return 0;
}
int MiddleboxLB::initialize(ErrorHandler *errh)
{
click_chatter("===============================================\n");
click_chatter("Batch size\t:\t%d\n", batch_element_size);
click_chatter("Packets count\t:\t%d\n", maxPktUsed);
click_chatter("Baseline test is %s\n", justSend ? "enable" : "disable");
click_chatter("Veri function is %s\n", veriSwitch ? "enable" : "disable");
click_chatter("Local test is %s\n", localMode ? "enable" : "disable");
click_chatter("Query Table is %s\n", bothway ? "enable" : "disable");
click_chatter("Box in chain is %s\n", lbInTheChain ? "yes" : "no");
//click_chatter("flowBased LB is %s\n", sampleLB ? "enable" : "disable");
//click_chatter("flowBased FW is %s\n", sampleFW ? "enable" : "disable");
//click_chatter("flowBased IDS is %s\n", sampleIDS ? "enable" : "disable");
click_chatter("===============================================\n");
std::string start = encTools::timeNow();
click_chatter("===============================================\n");
std::string end = encTools::timeNow();
click_chatter("output one line use %lf ns.\n", encTools::differTimeInNsec(start.data(), end.data()));
boxLogger.open(string(eleOutputPath).append(outputExtension));
pktLogger.open(string(pktOutputPath).append(outputExtension));
pktContainer.reserve(maxPktUsed);
validTotalPkgCount = 0;
boxCounter.no = 1;
preTime = encTools::timeNow();
activityTime = encTools::timeNow();
boxTotalTime = 0;
return 0;
}
void MiddleboxLB::push(int port, Packet * p_in)
{
if (localMode&& validTotalPkgCount >= maxPktUsed-10)
{
for (auto it = pktContainer.begin(); it != pktContainer.end(); ++it)
{
pktLogger << *it;
}
click_chatter("===============================================\n");
click_chatter("Write file end.\n");
click_chatter("===============================================\n");
validTotalPkgCount = 0;
}
//if (PktReader(p_in).getProtocol() == IPPROTO_UDP)
//{
// click_chatter("recv udp pkt\n");
// VeriTools::showPacket(p_in);
// ready_packet.push_back(p_in);
//}
//return;
std::string beginTime = encTools::timeNow();
if (!VeriTools::isTestPacket(p_in))
{
if (justSend)
{
WritablePacket *p = p_in->uniqueify();
//######################## different in each box
VeriTools::reDirectionPacket(p, boxLB_src_ip, boxLB_src_mac, boxLB_dst_ip, boxLB_dst_mac);
ready_packet.push_back(p);
boxCounter.pktCount += 1;
boxCounter.pktSize += p_in->length();
boxCounter.pktPageloadSize += PktReader(p_in).getDataLength();
VeriTools::checkElementCounter(boxCounter, preTime, eleContainer);
++validTotalPkgCount;
if (validTotalPkgCount == maxPktUsed)
{
for (auto it = eleContainer.begin(); it != eleContainer.end(); ++it)
{
boxLogger << *it;
}
click_chatter("base line test pkts :%d\n", validTotalPkgCount);
}
}
else
{
static bool wroteFile = false;
static string waitTime = "";
if (!wroteFile && (validTotalPkgCount == maxPktUsed || encTools::differTimeInNsec(activityTime.data(), encTools::timeNow().data()) > elementCounterBaseGap * 10.0))
{
if (waitTime.size() > 0)
{
if (encTools::differTimeInNsec(waitTime.data(), encTools::timeNow().data()) > elementCounterBaseGap*2)
{
for (auto it = eleContainer.begin(); it != eleContainer.end(); ++it)
{
boxLogger << *it;
}
for (auto it = pktContainer.begin(); it != pktContainer.end(); ++it)
{
pktLogger << *it;
}
wroteFile = true;
click_chatter("===============================================\n");
click_chatter("Write file end.\n");
click_chatter("===============================================\n");
}
}
else
{
click_chatter("===============================================\n");
click_chatter("wait to write, pkts :%d\n", validTotalPkgCount);
click_chatter("box avg use %lf ns.\n", boxTotalTime / maxPktUsed);
click_chatter("===============================================\n");
waitTime = encTools::timeNow();
boxCounter.useTime = elementCounterBaseGap;
VeriTools::checkElementCounter(boxCounter, preTime, eleContainer);
}
}
p_in->kill();
}
return;
}
// 1. get pkt batch
PktReader reader(p_in);
VeriHeader * pveri = (VeriHeader *)reader.getIpOption();
boxBatch& batch = batches[pveri->batchID];
if (batch.packetCount == 0)
{
//######################## different in each box
VeriTools::initBoxBatch(batch, pveri->batchID, flowBasedVerify, LB);
batch.readyToSendRoot = false;
}
WritablePacket *p = 0;
// 2. check if special pkt
if (pveri->flowID == trickFlowID)
{
batch.batchPktSize = pveri->cNum;
if(!lbInTheChain)
batch.readyToSendRoot = true;
if(verbose)
click_chatter("Recv batch size pkt, batchID:%d, size:%d\n", pveri->batchID, pveri->cNum);
WritablePacket *p = p_in->uniqueify();
VeriTools::reDirectionPacket(p, boxLB_src_ip, boxLB_src_mac, boxLB_dst_ip, boxLB_dst_mac);
ready_packet.push_back(p);
}
else if (pveri->flowID == merkletreeRootFlowID)
{
if (lbInTheChain)
batch.readyToSendRoot = true;
memcpy(batch.rootPacket, p_in->data(), p_in->length());
if(verbose)
click_chatter("Recv merkle_tree root pkt, tree root count is %d.\n", ((VeriHeader*)(reader.getIpOption()))->cNum);
p_in->kill();
}
else
{
pktCounter boxPktCounter;
VeriTools::setPktCounter(boxPktCounter, p_in);
// 3. add pkt to batch
batch.packetCount++;
pktFlow& flow = batch.flows[pveri->flowID];
if (flow.packetCount == 0)
{
VeriTools::initFlow(flow, batch.batchID, pveri->flowID);
}
flow.packetCount++;
// 4. do box function
//######################## different in each
p = p_in->uniqueify();
if (!p)
{
click_chatter("uniqueify error\n");
return;
}
//select a new server and write dst ip
uint32_t ip32bit = VeriTools::processLB(p);
memcpy((uint8_t*)p->data() + 14 + 16, &ip32bit, sizeof(ip32bit));
VeriTools::reDirectionPacket(p, boxLB_src_ip, boxLB_src_mac, boxLB_dst_ip, boxLB_dst_mac);
ready_packet.push_back(p);
//VeriTools::showPacket(p);
// 5. update veriInfo
if (veriSwitch)
{
veriInfo& veri = batch.veriRes[flow.flowID];
VeriTools::updateFlowVeri(veri, VeriTools::fflowLB(p), p);
}
activityTime = encTools::timeNow();
if (!startTime.size())
{
startTime = activityTime;
}
boxPktCounter.timestamp = encTools::differTimeInNsec(startTime.data(), activityTime.data());
startTime = activityTime;
boxPktCounter.processTime = encTools::differTimeInNsec(beginTime.data(), activityTime.data());
pktContainer.push_back(VeriTools::formatPktCounter(boxPktCounter));
boxCounter.pktCount += 1;
boxCounter.pktSize += p->length();
reader.attach(p);
boxCounter.pktPageloadSize += reader.getDataLength();
VeriTools::checkElementCounter(boxCounter, preTime, eleContainer);
validTotalPkgCount++;
if (verbose)
{
click_chatter("process batch:%d flow:%d cum:%d pkt use time :%lf ns .\n", pveri->batchID, pveri->flowID, pveri->cNum, boxPktCounter.processTime);
}
}
// 6.handle full batch
if (veriSwitch)
if (batch.readyToSendRoot)
if (batch.batchPktSize == batch.packetCount)
{
if ((batch.veriRes.size() & batch.veriRes.size() - 1) != 0)
{
click_chatter("batch flowCount error %d\n", batch.flows.size());
return;
}
buildTreeAndSendRootPkt(batch);
}
else
{
if (verbose)
{
click_chatter("batch need size %d, batch real size %d \n", batch.batchPktSize, batch.packetCount);
}
}
boxTotalTime += encTools::differTimeInNsec(beginTime.data(), encTools::timeNow().data());
}
Packet* MiddleboxLB::pull(int port) {
Packet* p = 0;
if (!ready_packet.empty())
{
p = ready_packet.front();
ready_packet.pop_front();
}
return p;
}
void MiddleboxLB::buildTreeAndSendRootPkt(boxBatch & batch)
{
VeriTools::buildVeriTree(batch);
WritablePacket* pktRoot = VeriTools::makeUDPPacket();
PktReader reader(pktRoot);
VeriHeader * pveri = (VeriHeader *)reader.getIpOption();
VeriHeader* oldVeriHeader = (VeriHeader*)(batch.rootPacket + ether_len + ip_default_len);
pveri->flowID = merkletreeRootFlowID;
pveri->batchID = batch.batchID;
pveri->cNum += oldVeriHeader->cNum+1;
if (pveri->cNum != 1)
{
if(verbose)
click_chatter("find box chain, this box is No.%d box.\n", pveri->cNum);
memcpy((uint8_t*)(pveri + 1) + udp_default_len, (uint8_t*)(oldVeriHeader + 1) + udp_default_len,
encTools::SHA256_len*(pveri->cNum - 1));
}
memcpy((char*)(pveri + 1) + encTools::SHA256_len*(pveri->cNum - 1) + udp_default_len,
batch.tree.getRoot().c_str(), encTools::SHA256_len);
//######################## different in each box
VeriTools::reDirectionPacket(pktRoot, boxLB_src_ip, boxLB_src_mac, boxLB_dst_ip, boxLB_dst_mac);
if (verbose)
click_chatter("batch %d root packet generated and flow count is %d, veri count is %d \n", batch.batchID, batch.flows.size(), batch.veriRes.size());
//VeriTools::showPacket(pktRoot);
ready_packet.push_back(pktRoot);
}
CLICK_ENDDECLS
EXPORT_ELEMENT(MiddleboxLB)
ELEMENT_MT_SAFE(MiddleboxLB)
ELEMENT_LIBS(-lverimb -lcryptopp)
| 28.911111 | 166 | 0.64902 | [
"vector"
] |
7305298c9dd992e802567f8c7bd362dd0b3bc442 | 41,469 | cpp | C++ | src/widgets/splits/SplitContainer.cpp | swills/chatterino2 | a79081f4413e65f8437e937bdcc199a5b73f267d | [
"MIT"
] | 2 | 2018-12-26T15:41:08.000Z | 2021-04-30T11:41:39.000Z | src/widgets/splits/SplitContainer.cpp | RAnders00/chatterino2 | 8b2c3c7386bc65c770f8678dbb24234b5338f42a | [
"MIT"
] | 22 | 2020-11-17T16:22:49.000Z | 2022-03-31T10:05:34.000Z | src/widgets/splits/SplitContainer.cpp | RAnders00/chatterino2 | 8b2c3c7386bc65c770f8678dbb24234b5338f42a | [
"MIT"
] | null | null | null | #include "widgets/splits/SplitContainer.hpp"
#include "Application.hpp"
#include "common/Common.hpp"
#include "debug/AssertInGuiThread.hpp"
#include "singletons/Fonts.hpp"
#include "singletons/Theme.hpp"
#include "singletons/WindowManager.hpp"
#include "util/Helpers.hpp"
#include "util/LayoutCreator.hpp"
#include "widgets/Notebook.hpp"
#include "widgets/helper/ChannelView.hpp"
#include "widgets/helper/NotebookTab.hpp"
#include "widgets/splits/Split.hpp"
#include <QApplication>
#include <QDebug>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonObject>
#include <QMimeData>
#include <QObject>
#include <QPainter>
#include <QVBoxLayout>
#include <QWidget>
#include <algorithm>
#include <boost/foreach.hpp>
namespace chatterino {
bool SplitContainer::isDraggingSplit = false;
Split *SplitContainer::draggingSplit = nullptr;
SplitContainer::SplitContainer(Notebook *parent)
: BaseWidget(parent)
, overlay_(this)
, mouseOverPoint_(-10000, -10000)
, tab_(nullptr)
{
this->refreshTabTitle();
this->managedConnect(Split::modifierStatusChanged, [this](auto modifiers) {
this->layout();
if (modifiers == showResizeHandlesModifiers)
{
for (auto &handle : this->resizeHandles_)
{
handle->show();
handle->raise();
}
}
else
{
for (auto &handle : this->resizeHandles_)
{
handle->hide();
}
}
if (modifiers == showSplitOverlayModifiers)
{
this->setCursor(Qt::PointingHandCursor);
}
else
{
this->unsetCursor();
}
});
this->setCursor(Qt::PointingHandCursor);
this->setAcceptDrops(true);
this->managedConnect(this->overlay_.dragEnded, [this]() {
this->isDragging_ = false;
this->layout();
});
this->overlay_.hide();
this->setMouseTracking(true);
this->setAcceptDrops(true);
}
NotebookTab *SplitContainer::getTab() const
{
return this->tab_;
}
void SplitContainer::setTab(NotebookTab *_tab)
{
this->tab_ = _tab;
this->tab_->page = this;
this->refreshTab();
}
void SplitContainer::hideResizeHandles()
{
this->overlay_.hide();
for (auto &handle : this->resizeHandles_)
{
handle->hide();
}
}
void SplitContainer::resetMouseStatus()
{
this->mouseOverPoint_ = QPoint(-10000, -10000);
this->update();
}
Split *SplitContainer::appendNewSplit(bool openChannelNameDialog)
{
assertInGuiThread();
Split *split = new Split(this);
this->appendSplit(split);
if (openChannelNameDialog)
{
split->showChangeChannelPopup("Open channel name", true, [=](bool ok) {
if (!ok)
{
this->deleteSplit(split);
}
});
}
return split;
}
void SplitContainer::appendSplit(Split *split)
{
this->insertSplit(split, Direction::Right);
}
void SplitContainer::insertSplit(Split *split, const Position &position)
{
this->insertSplit(split, position.direction_,
reinterpret_cast<Node *>(position.relativeNode_));
}
void SplitContainer::insertSplit(Split *split, Direction direction,
Split *relativeTo)
{
Node *node = this->baseNode_.findNodeContainingSplit(relativeTo);
assert(node != nullptr);
this->insertSplit(split, direction, node);
}
void SplitContainer::insertSplit(Split *split, Direction direction,
Node *relativeTo)
{
// Queue up save because: Split added
getApp()->windows->queueSave();
assertInGuiThread();
split->setContainer(this);
if (relativeTo == nullptr)
{
if (this->baseNode_.type_ == Node::EmptyRoot)
{
this->baseNode_.setSplit(split);
}
else if (this->baseNode_.type_ == Node::_Split)
{
this->baseNode_.nestSplitIntoCollection(split, direction);
}
else
{
this->baseNode_.insertSplitRelative(split, direction);
}
}
else
{
assert(this->baseNode_.isOrContainsNode(relativeTo));
relativeTo->insertSplitRelative(split, direction);
}
this->addSplit(split);
}
Split *SplitContainer::getSelectedSplit() const
{
// safety check
if (std::find(this->splits_.begin(), this->splits_.end(),
this->selected_) == this->splits_.end())
{
return nullptr;
}
return this->selected_;
}
void SplitContainer::addSplit(Split *split)
{
assertInGuiThread();
split->setParent(this);
split->show();
split->giveFocus(Qt::MouseFocusReason);
this->unsetCursor();
this->splits_.push_back(split);
this->refreshTab();
split->getChannelView().tabHighlightRequested.connect(
[this](HighlightState state) {
if (this->tab_ != nullptr)
{
this->tab_->setHighlightState(state);
}
});
split->getChannelView().liveStatusChanged.connect([this]() {
this->refreshTabLiveStatus();
});
split->focused.connect([this, split] {
this->setSelected(split);
});
this->layout();
}
void SplitContainer::setSelected(Split *split)
{
// safety
if (std::find(this->splits_.begin(), this->splits_.end(), split) ==
this->splits_.end())
{
return;
}
this->selected_ = split;
if (Node *node = this->baseNode_.findNodeContainingSplit(split))
{
this->focusSplitRecursive(node);
this->setPreferedTargetRecursive(node);
}
}
void SplitContainer::setPreferedTargetRecursive(Node *node)
{
if (node->parent_ != nullptr)
{
node->parent_->preferedFocusTarget_ = node;
this->setPreferedTargetRecursive(node->parent_);
}
}
SplitContainer::Position SplitContainer::releaseSplit(Split *split)
{
assertInGuiThread();
Node *node = this->baseNode_.findNodeContainingSplit(split);
assert(node != nullptr);
this->splits_.erase(
std::find(this->splits_.begin(), this->splits_.end(), split));
split->setParent(nullptr);
Position position = node->releaseSplit();
this->layout();
if (splits_.size() == 0)
{
this->setSelected(nullptr);
this->setCursor(Qt::PointingHandCursor);
}
else
{
this->splits_.front()->giveFocus(Qt::MouseFocusReason);
}
this->refreshTab();
// fourtf: really bad
split->getChannelView().tabHighlightRequested.disconnectAll();
split->getChannelView().tabHighlightRequested.disconnectAll();
return position;
}
SplitContainer::Position SplitContainer::deleteSplit(Split *split)
{
// Queue up save because: Split removed
getApp()->windows->queueSave();
assertInGuiThread();
assert(split != nullptr);
split->deleteLater();
return releaseSplit(split);
}
void SplitContainer::selectNextSplit(Direction direction)
{
assertInGuiThread();
if (Node *node = this->baseNode_.findNodeContainingSplit(this->selected_))
{
this->selectSplitRecursive(node, direction);
}
}
void SplitContainer::selectSplitRecursive(Node *node, Direction direction)
{
if (node->parent_ != nullptr)
{
if (node->parent_->type_ == Node::toContainerType(direction))
{
auto &siblings = node->parent_->children_;
auto it = std::find_if(siblings.begin(), siblings.end(),
[node](const auto &other) {
return other.get() == node;
});
assert(it != siblings.end());
if (direction == Direction::Left || direction == Direction::Above)
{
if (it == siblings.begin())
{
this->selectSplitRecursive(node->parent_, direction);
}
else
{
this->focusSplitRecursive(
siblings[it - siblings.begin() - 1].get());
}
}
else
{
if (it->get() == siblings.back().get())
{
this->selectSplitRecursive(node->parent_, direction);
}
else
{
this->focusSplitRecursive(
siblings[it - siblings.begin() + 1].get());
}
}
}
else
{
this->selectSplitRecursive(node->parent_, direction);
}
}
}
void SplitContainer::focusSplitRecursive(Node *node)
{
switch (node->type_)
{
case Node::_Split: {
node->split_->giveFocus(Qt::OtherFocusReason);
}
break;
case Node::HorizontalContainer:
case Node::VerticalContainer: {
auto &children = node->children_;
auto it = std::find_if(
children.begin(), children.end(), [node](const auto &other) {
return node->preferedFocusTarget_ == other.get();
});
if (it != children.end())
{
this->focusSplitRecursive(it->get());
}
else
{
this->focusSplitRecursive(node->children_.front().get());
}
}
break;
default:;
}
}
Split *SplitContainer::getTopRightSplit(Node &node)
{
switch (node.getType())
{
case Node::_Split:
return node.getSplit();
case Node::VerticalContainer:
if (!node.getChildren().empty())
return getTopRightSplit(*node.getChildren().front());
break;
case Node::HorizontalContainer:
if (!node.getChildren().empty())
return getTopRightSplit(*node.getChildren().back());
break;
default:;
}
return nullptr;
}
void SplitContainer::layout()
{
// update top right split
auto topRight = this->getTopRightSplit(this->baseNode_);
if (this->topRight_)
this->topRight_->setIsTopRightSplit(false);
this->topRight_ = topRight;
if (topRight)
this->topRight_->setIsTopRightSplit(true);
// layout
this->baseNode_.geometry_ = this->rect().adjusted(-1, -1, 0, 0);
std::vector<DropRect> _dropRects;
std::vector<ResizeRect> _resizeRects;
this->baseNode_.layout(
Split::modifierStatus == showAddSplitRegions || this->isDragging_,
this->scale(), _dropRects, _resizeRects);
this->dropRects_ = _dropRects;
for (Split *split : this->splits_)
{
const QRect &g = split->geometry();
Node *node = this->baseNode_.findNodeContainingSplit(split);
// left
_dropRects.push_back(
DropRect(QRect(g.left(), g.top(), g.width() / 3, g.height()),
Position(node, Direction::Left)));
// right
_dropRects.push_back(DropRect(QRect(g.right() - g.width() / 3, g.top(),
g.width() / 3, g.height()),
Position(node, Direction::Right)));
// top
_dropRects.push_back(
DropRect(QRect(g.left(), g.top(), g.width(), g.height() / 2),
Position(node, Direction::Above)));
// bottom
_dropRects.push_back(
DropRect(QRect(g.left(), g.bottom() - g.height() / 2, g.width(),
g.height() / 2),
Position(node, Direction::Below)));
}
if (this->splits_.empty())
{
QRect g = this->rect();
_dropRects.push_back(
DropRect(QRect(g.left(), g.top(), g.width() - 1, g.height() - 1),
Position(nullptr, Direction::Below)));
}
this->overlay_.setRects(std::move(_dropRects));
// handle resizeHandles
if (this->resizeHandles_.size() < _resizeRects.size())
{
while (this->resizeHandles_.size() < _resizeRects.size())
{
this->resizeHandles_.push_back(
std::make_unique<ResizeHandle>(this));
}
}
else if (this->resizeHandles_.size() > _resizeRects.size())
{
this->resizeHandles_.resize(_resizeRects.size());
}
{
size_t i = 0;
for (ResizeRect &resizeRect : _resizeRects)
{
ResizeHandle *handle = this->resizeHandles_[i].get();
handle->setGeometry(resizeRect.rect);
handle->setVertical(resizeRect.vertical);
handle->node = resizeRect.node;
if (Split::modifierStatus == showResizeHandlesModifiers)
{
handle->show();
handle->raise();
}
i++;
}
}
// redraw
this->update();
}
void SplitContainer::resizeEvent(QResizeEvent *event)
{
BaseWidget::resizeEvent(event);
this->layout();
}
void SplitContainer::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
if (this->splits_.size() == 0)
{
// "Add Chat" was clicked
this->appendNewSplit(true);
this->mouseOverPoint_ = QPoint(-10000, -10000);
// this->setCursor(QCursor(Qt::ArrowCursor));
}
else
{
auto it =
std::find_if(this->dropRects_.begin(), this->dropRects_.end(),
[event](DropRect &rect) {
return rect.rect.contains(event->pos());
});
if (it != this->dropRects_.end())
{
this->insertSplit(new Split(this), it->position);
}
}
}
}
void SplitContainer::paintEvent(QPaintEvent *)
{
QPainter painter(this);
if (this->splits_.size() == 0)
{
painter.fillRect(rect(), this->theme->splits.background);
painter.setPen(this->theme->splits.header.text);
const auto font =
getApp()->fonts->getFont(FontStyle::ChatMedium, this->scale());
painter.setFont(font);
QString text = "Click to add a split";
Notebook *notebook = dynamic_cast<Notebook *>(this->parentWidget());
if (notebook != nullptr)
{
if (notebook->getPageCount() > 1)
{
text += "\n\nAfter adding hold <Ctrl+Alt> to move or split it.";
}
}
painter.drawText(rect(), text, QTextOption(Qt::AlignCenter));
}
else
{
if (getApp()->themes->isLightTheme())
{
painter.fillRect(rect(), QColor("#999"));
}
else
{
painter.fillRect(rect(), QColor("#555"));
}
}
for (DropRect &dropRect : this->dropRects_)
{
QColor border = getApp()->themes->splits.dropTargetRectBorder;
QColor background = getApp()->themes->splits.dropTargetRect;
if (!dropRect.rect.contains(this->mouseOverPoint_))
{
// border.setAlphaF(0.1);
// background.setAlphaF(0.1);
}
else
{
// background.setAlphaF(0.1);
border.setAlpha(255);
}
painter.setPen(border);
painter.setBrush(background);
auto rect = dropRect.rect.marginsRemoved(QMargins(2, 2, 2, 2));
painter.drawRect(rect);
int s =
std::min<int>(dropRect.rect.width(), dropRect.rect.height()) - 12;
if (this->theme->isLightTheme())
{
painter.setPen(QColor(0, 0, 0));
}
else
{
painter.setPen(QColor(255, 255, 255));
}
painter.drawLine(rect.left() + rect.width() / 2 - (s / 2),
rect.top() + rect.height() / 2,
rect.left() + rect.width() / 2 + (s / 2),
rect.top() + rect.height() / 2);
painter.drawLine(rect.left() + rect.width() / 2,
rect.top() + rect.height() / 2 - (s / 2),
rect.left() + rect.width() / 2,
rect.top() + rect.height() / 2 + (s / 2));
}
QBrush accentColor =
(QApplication::activeWindow() == this->window()
? this->theme->tabs.selected.backgrounds.regular
: this->theme->tabs.selected.backgrounds.unfocused);
painter.fillRect(0, 0, width(), 1, accentColor);
}
void SplitContainer::dragEnterEvent(QDragEnterEvent *event)
{
if (!event->mimeData()->hasFormat("chatterino/split"))
return;
if (!SplitContainer::isDraggingSplit)
return;
this->isDragging_ = true;
this->layout();
this->overlay_.setGeometry(this->rect());
this->overlay_.show();
this->overlay_.raise();
}
void SplitContainer::mouseMoveEvent(QMouseEvent *event)
{
if (Split::modifierStatus == showSplitOverlayModifiers)
{
this->setCursor(Qt::PointingHandCursor);
}
this->mouseOverPoint_ = event->pos();
this->update();
}
void SplitContainer::leaveEvent(QEvent *)
{
this->mouseOverPoint_ = QPoint(-10000, -10000);
this->update();
}
void SplitContainer::focusInEvent(QFocusEvent *)
{
if (this->baseNode_.findNodeContainingSplit(this->selected_) != nullptr)
{
this->selected_->setFocus();
return;
}
if (this->splits_.size() != 0)
{
this->splits_.front()->setFocus();
}
}
void SplitContainer::refreshTab()
{
this->refreshTabTitle();
this->refreshTabLiveStatus();
}
int SplitContainer::getSplitCount()
{
return this->splits_.size();
}
const std::vector<Split *> SplitContainer::getSplits() const
{
return this->splits_;
}
SplitContainer::Node *SplitContainer::getBaseNode()
{
return &this->baseNode_;
}
void SplitContainer::applyFromDescriptor(const NodeDescriptor &rootNode)
{
assert(this->baseNode_.type_ == Node::EmptyRoot);
this->applyFromDescriptorRecursively(rootNode, &this->baseNode_);
}
void SplitContainer::applyFromDescriptorRecursively(
const NodeDescriptor &rootNode, Node *node)
{
if (std::holds_alternative<SplitNodeDescriptor>(rootNode))
{
auto *n = std::get_if<SplitNodeDescriptor>(&rootNode);
if (!n)
{
return;
}
const auto &splitNode = *n;
auto *split = new Split(this);
split->setChannel(WindowManager::decodeChannel(splitNode));
split->setModerationMode(splitNode.moderationMode_);
split->setFilters(splitNode.filters_);
this->appendSplit(split);
}
else if (std::holds_alternative<ContainerNodeDescriptor>(rootNode))
{
auto *n = std::get_if<ContainerNodeDescriptor>(&rootNode);
if (!n)
{
return;
}
const auto &containerNode = *n;
bool vertical = containerNode.vertical_;
Direction direction = vertical ? Direction::Below : Direction::Right;
node->type_ =
vertical ? Node::VerticalContainer : Node::HorizontalContainer;
for (const auto &item : containerNode.items_)
{
if (std::holds_alternative<SplitNodeDescriptor>(item))
{
auto *n = std::get_if<SplitNodeDescriptor>(&item);
if (!n)
{
return;
}
const auto &splitNode = *n;
auto *split = new Split(this);
split->setChannel(WindowManager::decodeChannel(splitNode));
split->setModerationMode(splitNode.moderationMode_);
split->setFilters(splitNode.filters_);
Node *_node = new Node();
_node->parent_ = node;
_node->split_ = split;
_node->type_ = Node::_Split;
_node->flexH_ = splitNode.flexH_;
_node->flexV_ = splitNode.flexV_;
node->children_.emplace_back(_node);
this->addSplit(split);
}
else
{
Node *_node = new Node();
_node->parent_ = node;
node->children_.emplace_back(_node);
this->applyFromDescriptorRecursively(item, _node);
}
}
}
}
void SplitContainer::refreshTabTitle()
{
if (this->tab_ == nullptr)
{
return;
}
QString newTitle = "";
bool first = true;
for (const auto &chatWidget : this->splits_)
{
auto channelName = chatWidget->getChannel()->getName();
if (channelName.isEmpty())
{
continue;
}
if (!first)
{
newTitle += ", ";
}
newTitle += channelName;
first = false;
}
if (newTitle.isEmpty())
{
newTitle = "empty";
}
this->tab_->setDefaultTitle(newTitle);
}
void SplitContainer::refreshTabLiveStatus()
{
if (this->tab_ == nullptr)
{
return;
}
bool liveStatus = false;
for (const auto &s : this->splits_)
{
auto c = s->getChannel();
if (c->isLive())
{
liveStatus = true;
break;
}
}
this->tab_->setLive(liveStatus);
}
//
// Node
//
SplitContainer::Node::Type SplitContainer::Node::getType()
{
return this->type_;
}
Split *SplitContainer::Node::getSplit()
{
return this->split_;
}
SplitContainer::Node *SplitContainer::Node::getParent()
{
return this->parent_;
}
qreal SplitContainer::Node::getHorizontalFlex()
{
return this->flexH_;
}
qreal SplitContainer::Node::getVerticalFlex()
{
return this->flexV_;
}
const std::vector<std::unique_ptr<SplitContainer::Node>>
&SplitContainer::Node::getChildren()
{
return this->children_;
}
SplitContainer::Node::Node()
: type_(SplitContainer::Node::Type::EmptyRoot)
, split_(nullptr)
, parent_(nullptr)
{
}
SplitContainer::Node::Node(Split *_split, Node *_parent)
: type_(Type::_Split)
, split_(_split)
, parent_(_parent)
{
}
bool SplitContainer::Node::isOrContainsNode(SplitContainer::Node *_node)
{
if (this == _node)
{
return true;
}
return std::any_of(this->children_.begin(), this->children_.end(),
[_node](std::unique_ptr<Node> &n) {
return n->isOrContainsNode(_node);
});
}
SplitContainer::Node *SplitContainer::Node::findNodeContainingSplit(
Split *_split)
{
if (this->type_ == Type::_Split && this->split_ == _split)
{
return this;
}
for (std::unique_ptr<Node> &node : this->children_)
{
Node *a = node->findNodeContainingSplit(_split);
if (a != nullptr)
{
return a;
}
}
return nullptr;
}
void SplitContainer::Node::insertSplitRelative(Split *_split,
Direction _direction)
{
if (this->parent_ == nullptr)
{
switch (this->type_)
{
case Node::EmptyRoot: {
this->setSplit(_split);
}
break;
case Node::_Split: {
this->nestSplitIntoCollection(_split, _direction);
}
break;
case Node::HorizontalContainer: {
this->nestSplitIntoCollection(_split, _direction);
}
break;
case Node::VerticalContainer: {
this->nestSplitIntoCollection(_split, _direction);
}
break;
}
return;
}
// parent != nullptr
if (parent_->type_ == toContainerType(_direction))
{
// hell yeah we'll just insert it next to outselves
this->insertNextToThis(_split, _direction);
}
else
{
this->nestSplitIntoCollection(_split, _direction);
}
}
void SplitContainer::Node::nestSplitIntoCollection(Split *_split,
Direction _direction)
{
if (toContainerType(_direction) == this->type_)
{
this->children_.emplace_back(new Node(_split, this));
}
else
{
// we'll need to nest outselves
// move all our data into a new node
Node *clone = new Node();
clone->type_ = this->type_;
clone->children_ = std::move(this->children_);
for (std::unique_ptr<Node> &node : clone->children_)
{
node->parent_ = clone;
}
clone->split_ = this->split_;
clone->parent_ = this;
// add the node to our children and change our type
this->children_.push_back(std::unique_ptr<Node>(clone));
this->type_ = toContainerType(_direction);
this->split_ = nullptr;
clone->insertNextToThis(_split, _direction);
}
}
void SplitContainer::Node::insertNextToThis(Split *_split, Direction _direction)
{
auto &siblings = this->parent_->children_;
qreal width = this->parent_->geometry_.width() /
std::max<qreal>(0.0001, siblings.size());
qreal height = this->parent_->geometry_.height() /
std::max<qreal>(0.0001, siblings.size());
if (siblings.size() == 1)
{
this->geometry_ = QRect(0, 0, int(width), int(height));
}
auto it =
std::find_if(siblings.begin(), siblings.end(), [this](auto &node) {
return this == node.get();
});
assert(it != siblings.end());
if (_direction == Direction::Right || _direction == Direction::Below)
{
it++;
}
Node *node = new Node(_split, this->parent_);
node->geometry_ = QRectF(0, 0, width, height);
siblings.insert(it, std::unique_ptr<Node>(node));
}
void SplitContainer::Node::setSplit(Split *_split)
{
assert(this->split_ == nullptr);
assert(this->children_.size() == 0);
this->split_ = _split;
this->type_ = Type::_Split;
}
SplitContainer::Position SplitContainer::Node::releaseSplit()
{
assert(this->type_ == Type::_Split);
if (parent_ == nullptr)
{
this->type_ = Type::EmptyRoot;
this->split_ = nullptr;
Position pos;
pos.relativeNode_ = nullptr;
pos.direction_ = Direction::Right;
return pos;
}
else
{
auto &siblings = this->parent_->children_;
auto it =
std::find_if(begin(siblings), end(siblings), [this](auto &node) {
return this == node.get();
});
assert(it != siblings.end());
Position position;
if (siblings.size() == 2)
{
// delete this and move split to parent
position.relativeNode_ = this->parent_;
if (this->parent_->type_ == Type::VerticalContainer)
{
position.direction_ = siblings.begin() == it ? Direction::Above
: Direction::Below;
}
else
{
position.direction_ =
siblings.begin() == it ? Direction::Left : Direction::Right;
}
Node *_parent = this->parent_;
siblings.erase(it);
std::unique_ptr<Node> &sibling = siblings.front();
_parent->type_ = sibling->type_;
_parent->split_ = sibling->split_;
std::vector<std::unique_ptr<Node>> nodes =
std::move(sibling->children_);
for (auto &node : nodes)
{
node->parent_ = _parent;
}
_parent->children_ = std::move(nodes);
}
else
{
if (this == siblings.back().get())
{
position.direction_ =
this->parent_->type_ == Type::VerticalContainer
? Direction::Below
: Direction::Right;
siblings.erase(it);
position.relativeNode_ = siblings.back().get();
}
else
{
position.relativeNode_ = (it + 1)->get();
position.direction_ =
this->parent_->type_ == Type::VerticalContainer
? Direction::Above
: Direction::Left;
siblings.erase(it);
}
}
return position;
}
}
qreal SplitContainer::Node::getFlex(bool isVertical)
{
return isVertical ? this->flexV_ : this->flexH_;
}
qreal SplitContainer::Node::getSize(bool isVertical)
{
return isVertical ? this->geometry_.height() : this->geometry_.width();
}
qreal SplitContainer::Node::getChildrensTotalFlex(bool isVertical)
{
return std::accumulate(this->children_.begin(), this->children_.end(),
qreal(0),
[=](qreal val, std::unique_ptr<Node> &node) {
return val + node->getFlex(isVertical);
});
}
void SplitContainer::Node::layout(bool addSpacing, float _scale,
std::vector<DropRect> &dropRects,
std::vector<ResizeRect> &resizeRects)
{
for (std::unique_ptr<Node> &node : this->children_)
{
if (node->flexH_ <= 0)
node->flexH_ = 0;
if (node->flexV_ <= 0)
node->flexV_ = 0;
}
switch (this->type_)
{
case Node::_Split: {
QRect rect = this->geometry_.toRect();
this->split_->setGeometry(
rect.marginsRemoved(QMargins(1, 1, 0, 0)));
}
break;
case Node::VerticalContainer:
case Node::HorizontalContainer: {
bool isVertical = this->type_ == Node::VerticalContainer;
// vars
qreal minSize = qreal(48 * _scale);
qreal totalFlex = std::max<qreal>(
0.0001, this->getChildrensTotalFlex(isVertical));
qreal totalSize = std::accumulate(
this->children_.begin(), this->children_.end(), qreal(0),
[=](int val, std::unique_ptr<Node> &node) {
return val + std::max<qreal>(
this->getSize(isVertical) /
std::max<qreal>(0.0001, totalFlex) *
node->getFlex(isVertical),
minSize);
});
totalSize = std::max<qreal>(0.0001, totalSize);
qreal sizeMultiplier = this->getSize(isVertical) / totalSize;
QRectF childRect = this->geometry_;
// add spacing if reqested
if (addSpacing)
{
qreal offset = std::min<qreal>(this->getSize(!isVertical) * 0.1,
qreal(_scale * 24));
// droprect left / above
dropRects.emplace_back(
QRectF(this->geometry_.left(), this->geometry_.top(),
isVertical ? offset : this->geometry_.width(),
isVertical ? this->geometry_.height() : offset)
.toRect(),
Position(this,
isVertical ? Direction::Left : Direction::Above));
// droprect right / below
if (isVertical)
{
dropRects.emplace_back(
QRectF(this->geometry_.right() - offset,
this->geometry_.top(), offset,
this->geometry_.height())
.toRect(),
Position(this, Direction::Right));
}
else
{
dropRects.emplace_back(
QRectF(this->geometry_.left(),
this->geometry_.bottom() - offset,
this->geometry_.width(), offset)
.toRect(),
Position(this, Direction::Below));
}
// shrink childRect
if (isVertical)
{
childRect.setLeft(childRect.left() + offset);
childRect.setRight(childRect.right() - offset);
}
else
{
childRect.setTop(childRect.top() + offset);
childRect.setBottom(childRect.bottom() - offset);
}
}
// iterate children
auto pos = int(isVertical ? childRect.top() : childRect.left());
for (std::unique_ptr<Node> &child : this->children_)
{
// set rect
QRect rect = childRect.toRect();
if (isVertical)
{
rect.setTop(pos);
rect.setHeight(
std::max<qreal>(this->geometry_.height() / totalFlex *
child->flexV_,
minSize) *
sizeMultiplier);
}
else
{
rect.setLeft(pos);
rect.setWidth(std::max<qreal>(this->geometry_.width() /
totalFlex * child->flexH_,
minSize) *
sizeMultiplier);
}
if (child == this->children_.back())
{
rect.setRight(childRect.right() - 1);
rect.setBottom(childRect.bottom() - 1);
}
child->geometry_ = rect;
child->layout(addSpacing, _scale, dropRects, resizeRects);
pos += child->getSize(isVertical);
// add resize rect
if (child != this->children_.front())
{
QRectF r = isVertical ? QRectF(this->geometry_.left(),
child->geometry_.top() - 4,
this->geometry_.width(), 8)
: QRectF(child->geometry_.left() - 4,
this->geometry_.top(), 8,
this->geometry_.height());
resizeRects.push_back(
ResizeRect(r.toRect(), child.get(), isVertical));
}
// normalize flex
if (isVertical)
{
child->flexV_ =
child->flexV_ / totalFlex * this->children_.size();
child->flexH_ = 1;
}
else
{
child->flexH_ =
child->flexH_ / totalFlex * this->children_.size();
child->flexV_ = 1;
}
}
}
break;
}
}
SplitContainer::Node::Type SplitContainer::Node::toContainerType(Direction _dir)
{
return _dir == Direction::Left || _dir == Direction::Right
? Type::HorizontalContainer
: Type::VerticalContainer;
}
//
// DropOverlay
//
SplitContainer::DropOverlay::DropOverlay(SplitContainer *_parent)
: QWidget(_parent)
, mouseOverPoint_(-10000, -10000)
, parent_(_parent)
{
this->setMouseTracking(true);
this->setAcceptDrops(true);
}
void SplitContainer::DropOverlay::setRects(
std::vector<SplitContainer::DropRect> _rects)
{
this->rects_ = std::move(_rects);
}
// pajlada::Signals::NoArgSignal dragEnded;
void SplitContainer::DropOverlay::paintEvent(QPaintEvent *)
{
QPainter painter(this);
// painter.fillRect(this->rect(), QColor("#334"));
bool foundMover = false;
for (DropRect &rect : this->rects_)
{
if (!foundMover && rect.rect.contains(this->mouseOverPoint_))
{
painter.setBrush(getApp()->themes->splits.dropPreview);
painter.setPen(getApp()->themes->splits.dropPreviewBorder);
foundMover = true;
}
else
{
painter.setBrush(QColor(0, 0, 0, 0));
painter.setPen(QColor(0, 0, 0, 0));
// painter.setPen(getApp()->themes->splits.dropPreviewBorder);
}
painter.drawRect(rect.rect);
}
}
void SplitContainer::DropOverlay::dragEnterEvent(QDragEnterEvent *event)
{
event->acceptProposedAction();
}
void SplitContainer::DropOverlay::dragMoveEvent(QDragMoveEvent *event)
{
event->acceptProposedAction();
this->mouseOverPoint_ = event->pos();
this->update();
}
void SplitContainer::DropOverlay::dragLeaveEvent(QDragLeaveEvent *)
{
this->mouseOverPoint_ = QPoint(-10000, -10000);
this->close();
this->dragEnded.invoke();
}
void SplitContainer::DropOverlay::dropEvent(QDropEvent *event)
{
Position *position = nullptr;
for (DropRect &rect : this->rects_)
{
if (rect.rect.contains(this->mouseOverPoint_))
{
position = &rect.position;
break;
}
}
if (position != nullptr)
{
this->parent_->insertSplit(SplitContainer::draggingSplit, *position);
event->acceptProposedAction();
}
this->mouseOverPoint_ = QPoint(-10000, -10000);
this->close();
this->dragEnded.invoke();
}
//
// ResizeHandle
//
void SplitContainer::ResizeHandle::setVertical(bool isVertical)
{
this->setCursor(isVertical ? Qt::SplitVCursor : Qt::SplitHCursor);
this->vertical_ = isVertical;
}
SplitContainer::ResizeHandle::ResizeHandle(SplitContainer *_parent)
: QWidget(_parent)
, parent(_parent)
{
this->setMouseTracking(true);
this->hide();
}
void SplitContainer::ResizeHandle::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setPen(QPen(getApp()->themes->splits.resizeHandle, 2));
painter.fillRect(this->rect(),
getApp()->themes->splits.resizeHandleBackground);
if (this->vertical_)
{
painter.drawLine(0, this->height() / 2, this->width(),
this->height() / 2);
}
else
{
painter.drawLine(this->width() / 2, 0, this->width() / 2,
this->height());
}
}
void SplitContainer::ResizeHandle::mousePressEvent(QMouseEvent *event)
{
this->isMouseDown_ = true;
if (event->button() == Qt::RightButton)
{
this->resetFlex();
}
}
void SplitContainer::ResizeHandle::mouseReleaseEvent(QMouseEvent *)
{
this->isMouseDown_ = false;
}
void SplitContainer::ResizeHandle::mouseMoveEvent(QMouseEvent *event)
{
if (!this->isMouseDown_)
{
return;
}
assert(node != nullptr);
assert(node->parent_ != nullptr);
auto &siblings = node->parent_->getChildren();
auto it = std::find_if(siblings.begin(), siblings.end(),
[this](const std::unique_ptr<Node> &n) {
return n.get() == this->node;
});
assert(it != siblings.end());
Node *before = siblings[it - siblings.begin() - 1].get();
QPoint topLeft =
this->parent->mapToGlobal(before->geometry_.topLeft().toPoint());
QPoint bottomRight = this->parent->mapToGlobal(
this->node->geometry_.bottomRight().toPoint());
int globalX = topLeft.x() > event->globalX()
? topLeft.x()
: (bottomRight.x() < event->globalX() ? bottomRight.x()
: event->globalX());
int globalY = topLeft.y() > event->globalY()
? topLeft.y()
: (bottomRight.y() < event->globalY() ? bottomRight.y()
: event->globalY());
QPoint mousePoint(globalX, globalY);
if (this->vertical_)
{
qreal totalFlexV = this->node->flexV_ + before->flexV_;
before->flexV_ = totalFlexV * (mousePoint.y() - topLeft.y()) /
(bottomRight.y() - topLeft.y());
this->node->flexV_ = totalFlexV - before->flexV_;
this->parent->layout();
// move handle
this->move(this->x(), int(before->geometry_.bottom() - 4));
}
else
{
qreal totalFlexH = this->node->flexH_ + before->flexH_;
before->flexH_ = totalFlexH * (mousePoint.x() - topLeft.x()) /
(bottomRight.x() - topLeft.x());
this->node->flexH_ = totalFlexH - before->flexH_;
this->parent->layout();
// move handle
this->move(int(before->geometry_.right() - 4), this->y());
}
}
void SplitContainer::ResizeHandle::mouseDoubleClickEvent(QMouseEvent *event)
{
event->accept();
this->resetFlex();
}
void SplitContainer::ResizeHandle::resetFlex()
{
for (auto &sibling : this->node->getParent()->getChildren())
{
sibling->flexH_ = 1;
sibling->flexV_ = 1;
}
this->parent->layout();
}
} // namespace chatterino
| 27.426587 | 80 | 0.531071 | [
"geometry",
"vector"
] |
730a6da6e5a90a59dab3670595f43666f860f34b | 6,041 | cc | C++ | tensorflow_serving/servables/tensorflow/saved_model_warmup_test.cc | mzhang-code/serving | 527c6f2173eba584ebdca4f8b11ae3c0550ab1a9 | [
"Apache-2.0"
] | 5,791 | 2016-02-16T17:50:06.000Z | 2022-03-31T11:53:10.000Z | tensorflow_serving/servables/tensorflow/saved_model_warmup_test.cc | mzhang-code/serving | 527c6f2173eba584ebdca4f8b11ae3c0550ab1a9 | [
"Apache-2.0"
] | 1,618 | 2016-02-16T18:04:00.000Z | 2022-03-30T07:24:28.000Z | tensorflow_serving/servables/tensorflow/saved_model_warmup_test.cc | mzhang-code/serving | 527c6f2173eba584ebdca4f8b11ae3c0550ab1a9 | [
"Apache-2.0"
] | 2,501 | 2016-02-16T19:57:43.000Z | 2022-03-27T02:43:49.000Z | /* Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_serving/servables/tensorflow/saved_model_warmup.h"
#include "google/protobuf/wrappers.pb.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/cc/saved_model/constants.h"
#include "tensorflow/cc/saved_model/signature_constants.h"
#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/example/feature.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/io/record_writer.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/threadpool_options.h"
#include "tensorflow_serving/apis/classification.pb.h"
#include "tensorflow_serving/apis/inference.pb.h"
#include "tensorflow_serving/apis/input.pb.h"
#include "tensorflow_serving/apis/model.pb.h"
#include "tensorflow_serving/apis/predict.pb.h"
#include "tensorflow_serving/apis/prediction_log.pb.h"
#include "tensorflow_serving/apis/regression.pb.h"
#include "tensorflow_serving/core/test_util/mock_session.h"
#include "tensorflow_serving/servables/tensorflow/saved_model_warmup_test_util.h"
#include "tensorflow_serving/servables/tensorflow/session_bundle_config.pb.h"
namespace tensorflow {
namespace serving {
namespace {
using test_util::MockSession;
using ::testing::_;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::SetArgPointee;
using ::testing::SizeIs;
class SavedModelBundleWarmupOptionsTest
: public ::testing::TestWithParam<bool> {
public:
bool EnableNumRequestIterations() { return GetParam(); }
ModelWarmupOptions GetModelWarmupOptions() {
ModelWarmupOptions options;
if (EnableNumRequestIterations()) {
options.mutable_num_request_iterations()->set_value(2);
}
return options;
}
int GetNumRequestIterations() {
if (EnableNumRequestIterations()) {
return 2;
}
return 1;
}
};
TEST_P(SavedModelBundleWarmupOptionsTest, MixedWarmupData) {
string base_path = io::JoinPath(testing::TmpDir(), "MixedWarmupData");
TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));
string fname = io::JoinPath(base_path, kSavedModelAssetsExtraDirectory,
internal::WarmupConsts::kRequestsFileName);
int num_warmup_records = 10;
std::vector<string> warmup_records;
AddMixedWarmupData(&warmup_records);
TF_ASSERT_OK(WriteWarmupData(fname, warmup_records, num_warmup_records));
SavedModelBundle saved_model_bundle;
AddSignatures(&saved_model_bundle.meta_graph_def);
MockSession* mock = new MockSession;
saved_model_bundle.session.reset(mock);
Tensor scores(DT_FLOAT, TensorShape({1, 1}));
Tensor classes(DT_STRING, TensorShape({1, 1}));
// Regress and Predict cases
EXPECT_CALL(*mock, Run(_, _, SizeIs(1), _, _, _, _))
.Times(num_warmup_records * 2 * GetNumRequestIterations())
.WillRepeatedly(DoAll(SetArgPointee<4>(std::vector<Tensor>({scores})),
Return(Status::OK())));
// Classify case
EXPECT_CALL(*mock, Run(_, _, SizeIs(2), _, _, _, _))
.Times(num_warmup_records * GetNumRequestIterations())
.WillRepeatedly(
DoAll(SetArgPointee<4>(std::vector<Tensor>({classes, scores})),
Return(Status::OK())));
// MultiInference case
EXPECT_CALL(*mock, Run(_, _, SizeIs(3), _, _, _, _))
.Times(num_warmup_records * GetNumRequestIterations())
.WillRepeatedly(DoAll(
SetArgPointee<4>(std::vector<Tensor>({classes, scores, scores})),
Return(Status::OK())));
TF_EXPECT_OK(RunSavedModelWarmup(GetModelWarmupOptions(), RunOptions(),
base_path, &saved_model_bundle));
}
INSTANTIATE_TEST_SUITE_P(WarmupOptions, SavedModelBundleWarmupOptionsTest,
::testing::Bool());
TEST(SavedModelBundleWarmupTest, UnsupportedLogType) {
string base_path = io::JoinPath(testing::TmpDir(), "UnsupportedLogType");
TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));
string fname = io::JoinPath(base_path, kSavedModelAssetsExtraDirectory,
internal::WarmupConsts::kRequestsFileName);
std::vector<string> warmup_records;
// Add unsupported log type
PredictionLog prediction_log;
PopulatePredictionLog(&prediction_log, PredictionLog::kSessionRunLog);
warmup_records.push_back(prediction_log.SerializeAsString());
TF_ASSERT_OK(WriteWarmupData(fname, warmup_records, 10));
SavedModelBundle saved_model_bundle;
AddSignatures(&saved_model_bundle.meta_graph_def);
MockSession* mock = new MockSession;
saved_model_bundle.session.reset(mock);
EXPECT_CALL(*mock, Run(_, _, _, _, _, _, _))
.WillRepeatedly(Return(Status::OK()));
const Status status = RunSavedModelWarmup(ModelWarmupOptions(), RunOptions(),
base_path, &saved_model_bundle);
ASSERT_FALSE(status.ok());
EXPECT_EQ(::tensorflow::error::UNIMPLEMENTED, status.code()) << status;
EXPECT_THAT(status.ToString(),
::testing::HasSubstr("Unsupported log_type for warmup"));
}
} // namespace
} // namespace serving
} // namespace tensorflow
| 40.817568 | 81 | 0.725873 | [
"vector",
"model"
] |
730ab5c3d30df4c8d2287d01e58994b979d29fc3 | 35,404 | cpp | C++ | src/core/hw/gfxip/gfx6/gfx6ColorTargetView.cpp | dnovillo/pal | f924a4fb84efde321f7754031f8cfa5ab35055d3 | [
"MIT"
] | null | null | null | src/core/hw/gfxip/gfx6/gfx6ColorTargetView.cpp | dnovillo/pal | f924a4fb84efde321f7754031f8cfa5ab35055d3 | [
"MIT"
] | null | null | null | src/core/hw/gfxip/gfx6/gfx6ColorTargetView.cpp | dnovillo/pal | f924a4fb84efde321f7754031f8cfa5ab35055d3 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2015-2018 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
#include "core/image.h"
#include "core/hw/gfxip/universalCmdBuffer.h"
#include "core/hw/gfxip/gfx6/g_gfx6PalSettings.h"
#include "core/hw/gfxip/gfx6/gfx6CmdStream.h"
#include "core/hw/gfxip/gfx6/gfx6CmdUtil.h"
#include "core/hw/gfxip/gfx6/gfx6ColorBlendState.h"
#include "core/hw/gfxip/gfx6/gfx6ColorTargetView.h"
#include "core/hw/gfxip/gfx6/gfx6Device.h"
#include "core/hw/gfxip/gfx6/gfx6FormatInfo.h"
#include "core/hw/gfxip/gfx6/gfx6Image.h"
#include "palFormatInfo.h"
using namespace Util;
using namespace Pal::Formats::Gfx6;
namespace Pal
{
namespace Gfx6
{
// Value for CB_COLOR_DCC_CONTROL when compressed rendering is disabled.
constexpr uint32 CbColorDccControlDecompressed = 0;
// Value for CB_COLOR_CMASK_SLICE when compressed rendering is disabled.
constexpr uint32 CbColorCmaskSliceDecompressed = 0;
// Mask of CB_COLOR_INFO bits to clear when compressed rendering is disabled.
constexpr uint32 CbColorInfoDecompressedMask = (CB_COLOR0_INFO__DCC_ENABLE_MASK__VI |
CB_COLOR0_INFO__COMPRESSION_MASK |
CB_COLOR0_INFO__FAST_CLEAR_MASK |
CB_COLOR0_INFO__CMASK_IS_LINEAR_MASK |
CB_COLOR0_INFO__CMASK_ADDR_TYPE_MASK__VI |
CB_COLOR0_INFO__FMASK_COMPRESSION_DISABLE_MASK__CI__VI |
CB_COLOR0_INFO__FMASK_COMPRESS_1FRAG_ONLY_MASK__VI);
// =====================================================================================================================
ColorTargetView::ColorTargetView(
const Device& device,
const ColorTargetViewCreateInfo& createInfo,
const ColorTargetViewInternalCreateInfo& internalInfo)
:
m_pImage(nullptr)
{
m_flags.u32All = 0;
// Note that buffew views have their VA ranges locked because they cannot have their memory rebound.
m_flags.isBufferView = createInfo.flags.isBufferView;
m_flags.viewVaLocked = createInfo.flags.imageVaLocked | createInfo.flags.isBufferView;
m_flags.usesLoadRegIndexPkt = device.Parent()->ChipProperties().gfx6.supportLoadRegIndexPkt;
if (m_flags.isBufferView == 0)
{
PAL_ASSERT(createInfo.imageInfo.pImage != nullptr);
// Retain a pointer to the attached image.
m_pImage = GetGfx6Image(createInfo.imageInfo.pImage);
// If this assert triggers the caller is probably trying to select z slices using the subresource range
// instead of the zRange as required by the PAL interface.
PAL_ASSERT((m_pImage->Parent()->GetImageCreateInfo().imageType != ImageType::Tex3d) ||
((createInfo.imageInfo.baseSubRes.arraySlice == 0) && (createInfo.imageInfo.arraySize == 1)));
// Sets the base subresource for this mip.
m_subresource.aspect = createInfo.imageInfo.baseSubRes.aspect;
m_subresource.mipLevel = createInfo.imageInfo.baseSubRes.mipLevel;
m_subresource.arraySlice = 0;
// Set all of the metadata flags.
m_flags.hasCmask = m_pImage->HasCmaskData();
m_flags.hasFmask = m_pImage->HasFmaskData();
m_flags.hasDcc = m_pImage->HasDccData();
m_flags.hasDccStateMetaData = m_pImage->HasDccStateMetaData();
m_flags.fastClearSupported = (m_pImage->HasFastClearMetaData() && !internalInfo.flags.depthStencilCopy);
m_flags.dccCompressionEnabled = (m_flags.hasDcc && m_pImage->GetDcc(m_subresource)->IsCompressionEnabled());
m_layoutToState = m_pImage->LayoutToColorCompressionState(m_subresource);
}
else
{
memset(&m_subresource, 0, sizeof(m_subresource));
}
m_cbColorAttribDecompressed.u32All = 0;
memset(&m_pm4Cmds, 0, sizeof(m_pm4Cmds));
BuildPm4Headers(device);
InitRegisters(device, createInfo, internalInfo);
if (m_flags.viewVaLocked && (m_flags.isBufferView == 0))
{
UpdateImageVa(&m_pm4Cmds);
}
}
// =====================================================================================================================
// Builds the PM4 packet headers for an image of PM4 commands used to write this View object to hardware.
void ColorTargetView::BuildPm4Headers(
const Device& device)
{
const CmdUtil& cmdUtil = device.CmdUtil();
// NOTE: The register offset will be updated at bind-time to reflect the actual slot this View is being bound to.
size_t spaceNeeded = cmdUtil.BuildSetSeqContextRegs(mmCB_COLOR0_BASE,
mmCB_COLOR0_VIEW,
&m_pm4Cmds.hdrCbColorBaseToView);
// NOTE: The register offset will be updated at bind-time to reflect the actual slot this View is being bound to.
spaceNeeded += CmdUtil::GetContextRegRmwSize();
// NOTE: The register offset will be updated at bind-time to reflect the actual slot this view is being bound to.
spaceNeeded += cmdUtil.BuildSetSeqContextRegs(mmCB_COLOR0_ATTRIB,
mmCB_COLOR0_FMASK_SLICE,
&m_pm4Cmds.hdrCbColorAttribToFmaskSlice);
spaceNeeded += cmdUtil.BuildSetSeqContextRegs(mmPA_SC_GENERIC_SCISSOR_TL,
mmPA_SC_GENERIC_SCISSOR_BR,
&m_pm4Cmds.hdrPaScGenericScissorTlBr);
// NOTE: The register offset will be updated at bind-time to reflect the actual slot this view is being bound to.
// NOTE: This register is an unused location on pre-VI ASICs; writing to it doesn't do anything.
spaceNeeded += cmdUtil.BuildSetOneContextReg(mmCB_COLOR0_DCC_BASE__VI, &m_pm4Cmds.hdrCbColorDccBase);
m_pm4Cmds.spaceNeeded = spaceNeeded;
m_pm4Cmds.spaceNeededDecompressed = spaceNeeded;
if (m_flags.fastClearSupported)
{
// If the parent Image supports fast clears, then we need to add a LOAD_CONTEXT_REG packet to load the
// image's fast-clear metadata.
//
// NOTE: We do not know the GPU virtual address of the metadata until bind-time.
constexpr uint32 RegCount = (mmCB_COLOR0_CLEAR_WORD1 - mmCB_COLOR0_CLEAR_WORD0 + 1);
if (m_flags.usesLoadRegIndexPkt != 0)
{
m_pm4Cmds.spaceNeeded += cmdUtil.BuildLoadContextRegsIndex<true>(0,
mmCB_COLOR0_CLEAR_WORD0,
RegCount,
&m_pm4Cmds.loadMetaDataIndex);
}
else
{
m_pm4Cmds.spaceNeeded +=
cmdUtil.BuildLoadContextRegs(0, mmCB_COLOR0_CLEAR_WORD0, RegCount, &m_pm4Cmds.loadMetaData);
}
}
if (m_flags.dccCompressionEnabled && m_flags.hasDccStateMetaData)
{
// Our PM4 image layout assumes that the loadMetaData packet is always used in this case.
PAL_ASSERT(m_flags.fastClearSupported);
// We also need to update the DCC state metadata when compression is enabled.
//
// NOTE: We do not know the GPU virtual address of the metadata until bind-time.
constexpr gpusize NumDwords = sizeof(m_pm4Cmds.mipMetaData) / sizeof(uint32);
m_pm4Cmds.spaceNeeded += cmdUtil.BuildWriteData(0,
NumDwords,
WRITE_DATA_ENGINE_PFP,
WRITE_DATA_DST_SEL_MEMORY_ASYNC,
true,
nullptr,
PredDisable,
&m_pm4Cmds.hdrMipMetaData);
}
}
// =====================================================================================================================
// Finalizes the PM4 packet image by setting up the register values used to write this View object to hardware.
void ColorTargetView::InitRegisters(
const Device& device,
const ColorTargetViewCreateInfo& createInfo,
const ColorTargetViewInternalCreateInfo& internalInfo)
{
// By default, assume linear general tiling and no Fmask texture fetches.
int32 baseTileIndex = TileIndexLinearGeneral;
uint32 baseBankHeight = 0;
bool fMaskTexFetchAllowed = false;
// Most register values are simple to compute but vary based on whether or not this is a buffer view. Let's set
// them all up-front before we get on to the harder register values.
if (m_flags.isBufferView)
{
PAL_ASSERT(createInfo.bufferInfo.pGpuMemory != nullptr);
// The buffer virtual address is simply "offset" pixels from the start of the GPU memory's virtual address.
const gpusize bufferOffset = createInfo.bufferInfo.offset *
Formats::BytesPerPixel(createInfo.swizzledFormat.format);
const gpusize bufferAddr = createInfo.bufferInfo.pGpuMemory->Desc().gpuVirtAddr + bufferOffset;
// Convert to a 256-bit aligned base address and a base offset. Note that we don't need to swizzle the base
// address because buffers aren't macro tiled.
const gpusize baseOffset = bufferAddr & 0xFF;
const gpusize baseAddr = bufferAddr & (~0xFF);
m_pm4Cmds.cbColorBase.bits.BASE_256B = Get256BAddrLo(baseAddr);
// The CI addressing doc states that the CB requires linear general surfaces pitches to be 8-element aligned.
const uint32 alignedExtent = Pow2Align(createInfo.bufferInfo.extent, 8);
m_pm4Cmds.cbColorPitch.bits.TILE_MAX = (alignedExtent / TileWidth) - 1;
m_pm4Cmds.cbColorSlice.bits.TILE_MAX = (alignedExtent / TilePixels) - 1;
// The view slice_start is overloaded to specify the base offset.
m_pm4Cmds.cbColorView.bits.SLICE_START = baseOffset;
m_pm4Cmds.cbColorView.bits.SLICE_MAX = 0;
m_pm4Cmds.cbColorAttrib.bits.TILE_MODE_INDEX = baseTileIndex;
m_pm4Cmds.cbColorAttrib.bits.FORCE_DST_ALPHA_1 = Formats::HasUnusedAlpha(createInfo.swizzledFormat) ? 1 : 0;
m_pm4Cmds.cbColorAttrib.bits.NUM_SAMPLES = 0;
m_pm4Cmds.cbColorAttrib.bits.NUM_FRAGMENTS = 0;
m_pm4Cmds.paScGenericScissorTl.bits.WINDOW_OFFSET_DISABLE = true;
m_pm4Cmds.paScGenericScissorTl.bits.TL_X = 0;
m_pm4Cmds.paScGenericScissorTl.bits.TL_Y = 0;
m_pm4Cmds.paScGenericScissorBr.bits.BR_X = createInfo.bufferInfo.extent;
m_pm4Cmds.paScGenericScissorBr.bits.BR_Y = 1;
}
else
{
// Override the three variables defined above.
const SubResourceInfo*const pSubResInfo = m_pImage->Parent()->SubresourceInfo(m_subresource);
const AddrMgr1::TileInfo*const pTileInfo = AddrMgr1::GetTileInfo(m_pImage->Parent(), m_subresource);
const ImageCreateInfo& imageCreateInfo = m_pImage->Parent()->GetImageCreateInfo();
const auto& swizzledFmt = imageCreateInfo.swizzledFormat;
const bool imgIsBc = Formats::IsBlockCompressed(swizzledFmt.format);
// Check if we can keep fmask in a compressed state and avoid corresponding fmask decompression
fMaskTexFetchAllowed = m_pImage->IsComprFmaskShaderReadable(pSubResInfo);
const Gfx6::Device* pGfxDevice = static_cast<Gfx6::Device*>(m_pImage->Parent()->GetDevice()->GetGfxDevice());
baseTileIndex = (internalInfo.flags.depthStencilCopy == 1) ?
pGfxDevice->OverridedTileIndexForDepthStencilCopy(pTileInfo->tileIndex) : pTileInfo->tileIndex;
baseBankHeight = pTileInfo->bankHeight;
// NOTE: The color base address will be determined later, we don't need to do anything here.
Extent3d extent = pSubResInfo->extentTexels;
Extent3d actualExtent = pSubResInfo->actualExtentTexels;
// The view should be in terms of texels except in the below cases when we're operating in terms of elements:
// 1. Viewing a compressed image in terms of blocks. For BC images elements are blocks, so if the caller gave
// us an uncompressed view format we assume they want to view blocks.
// 2. Copying to an "expanded" format (e.g., R32G32B32). In this case we can't do native format writes so we're
// going to write each element independently. The trigger for this case is a mismatched bpp.
// 3. Viewing a YUV-packed image with a non-YUV-packed format when the view format is allowed for view formats
// with twice the bpp. In this case, the effective width of the view is half that of the base image.
// 4. Viewing a YUV planar Image. The view must be associated with a single plane. Since all planes of an array
// slice are packed together for YUV formats, we need to tell the CB hardware to "skip" the other planes if
// the view either spans multiple array slices or starts at a nonzero array slice.
if (imgIsBc || (pSubResInfo->bitsPerTexel != Formats::BitsPerPixel(createInfo.swizzledFormat.format)))
{
extent = pSubResInfo->extentElements;
actualExtent = pSubResInfo->actualExtentElements;
}
if (Formats::IsYuvPacked(pSubResInfo->format.format) &&
(Formats::IsYuvPacked(createInfo.swizzledFormat.format) == false) &&
((pSubResInfo->bitsPerTexel << 1) == Formats::BitsPerPixel(createInfo.swizzledFormat.format)))
{
// Changing how we interpret the bits-per-pixel of the subresource wreaks havoc with any tile swizzle
// pattern used. This will only work for linear-tiled Images.
PAL_ASSERT(m_pImage->IsSubResourceLinear(m_subresource));
extent.width >>= 1;
actualExtent.width >>= 1;
}
else if (Formats::IsYuvPlanar(imageCreateInfo.swizzledFormat.format) &&
((createInfo.imageInfo.arraySize > 1) || (createInfo.imageInfo.baseSubRes.arraySlice != 0)))
{
m_pImage->PadYuvPlanarViewActualExtent(m_subresource, &actualExtent);
}
m_pm4Cmds.cbColorPitch.bits.TILE_MAX = (actualExtent.width / TileWidth) - 1;
m_pm4Cmds.cbColorSlice.bits.TILE_MAX = (actualExtent.width * actualExtent.height / TilePixels) - 1;
if ((createInfo.flags.zRangeValid == 1) && (imageCreateInfo.imageType == ImageType::Tex3d))
{
m_pm4Cmds.cbColorView.bits.SLICE_START = createInfo.zRange.offset;
m_pm4Cmds.cbColorView.bits.SLICE_MAX = (createInfo.zRange.offset + createInfo.zRange.extent - 1);
}
else
{
const uint32 baseArraySlice = createInfo.imageInfo.baseSubRes.arraySlice;
m_pm4Cmds.cbColorView.bits.SLICE_START = baseArraySlice;
m_pm4Cmds.cbColorView.bits.SLICE_MAX = (baseArraySlice + createInfo.imageInfo.arraySize - 1);
}
m_pm4Cmds.cbColorAttrib.bits.TILE_MODE_INDEX = baseTileIndex;
m_pm4Cmds.cbColorAttrib.bits.FORCE_DST_ALPHA_1 = Formats::HasUnusedAlpha(createInfo.swizzledFormat) ? 1 : 0;
m_pm4Cmds.cbColorAttrib.bits.NUM_SAMPLES = Log2(imageCreateInfo.samples);
m_pm4Cmds.cbColorAttrib.bits.NUM_FRAGMENTS = Log2(imageCreateInfo.fragments);
m_pm4Cmds.paScGenericScissorTl.bits.WINDOW_OFFSET_DISABLE = 1;
m_pm4Cmds.paScGenericScissorTl.bits.TL_X = 0;
m_pm4Cmds.paScGenericScissorTl.bits.TL_Y = 0;
m_pm4Cmds.paScGenericScissorBr.bits.BR_X = extent.width;
m_pm4Cmds.paScGenericScissorBr.bits.BR_Y = extent.height;
}
const auto& parent = *device.Parent();
const auto gfxLevel = parent.ChipProperties().gfxLevel;
m_flags.isGfx7OrHigher = (gfxLevel >= GfxIpLevel::GfxIp7);
regCB_COLOR0_INFO cbColorInfo = { };
cbColorInfo.bits.ENDIAN = ENDIAN_NONE;
cbColorInfo.bits.FORMAT = Formats::Gfx6::HwColorFmt(MergedChannelFmtInfoTbl(gfxLevel),
createInfo.swizzledFormat.format);
cbColorInfo.bits.NUMBER_TYPE = Formats::Gfx6::ColorSurfNum(MergedChannelFmtInfoTbl(gfxLevel),
createInfo.swizzledFormat.format);
cbColorInfo.bits.COMP_SWAP = Formats::Gfx6::ColorCompSwap(createInfo.swizzledFormat);
// Set bypass blending for any format that is not blendable. Blend clamp must be cleared if blend_bypass is set.
// Otherwise, it must be set iff any component is SNORM, UNORM, or SRGB.
const bool blendBypass = (parent.SupportsBlend(createInfo.swizzledFormat.format, ImageTiling::Optimal) == false);
const bool isNormOrSrgb = Formats::IsNormalized(createInfo.swizzledFormat.format) ||
Formats::IsSrgb(createInfo.swizzledFormat.format);
const bool blendClamp = (blendBypass == false) && isNormOrSrgb;
// Selects between truncating (standard for floats) and rounding (standard for most other cases) to convert blender
// results to frame buffer components. Round mode must be set to ROUND_BY_HALF if any component is UNORM, SNORM or
// SRGB otherwise ROUND_TRUNCATE.
const RoundMode roundMode = isNormOrSrgb ? ROUND_BY_HALF : ROUND_TRUNCATE;
cbColorInfo.bits.BLEND_CLAMP = blendClamp;
cbColorInfo.bits.BLEND_BYPASS = blendBypass;
cbColorInfo.bits.SIMPLE_FLOAT = Pal::Device::CbSimpleFloatEnable;
cbColorInfo.bits.ROUND_MODE = roundMode;
cbColorInfo.bits.LINEAR_GENERAL = (baseTileIndex == TileIndexLinearGeneral);
if (m_flags.hasDcc != 0)
{
const Gfx6Dcc*const pDcc = m_pImage->GetDcc(m_subresource);
m_pm4Cmds.cbColorDccControl = pDcc->GetControlReg();
// We have DCC memory for this surface, but if it's not available for use by the HW, then
// we can't actually use it.
cbColorInfo.bits.DCC_ENABLE__VI = m_flags.dccCompressionEnabled;
// If this view has DCC data and this is a decompress operation we must set "isCompressed"
// to zero. If the view has DCC data and this is a normal render operation we should set
// "isCompressed" to one as we expect the CB to write to DCC.
if (pDcc->IsCompressionEnabled())
{
m_pm4Cmds.mipMetaData.isCompressed = (internalInfo.flags.dccDecompress == 0);
}
}
if (m_flags.hasCmask != 0)
{
const Gfx6Cmask*const pCmask = m_pImage->GetCmask(m_subresource);
// Setup CB_COLOR*_INFO register fields which depend on CMask state:
cbColorInfo.bits.COMPRESSION = 1;
// If the workaround isn't enabled or if there's no DCC data, then set the bit as
// normal, otherwise, always keep FAST_CLEAR disabled except for CB operations fast-clear
// eliminate operations.
if ((device.WaNoFastClearWithDcc() == false) || !m_flags.hasDcc)
{
// No DCC data or the workaround isn't needed, so just set the FAST_CLEAR bit as
// always done on previous ASICs
cbColorInfo.bits.FAST_CLEAR = pCmask->UseFastClear();
}
else if (m_pImage->HasDccData() && internalInfo.flags.fastClearElim)
{
cbColorInfo.bits.FAST_CLEAR = 1;
}
if ((gfxLevel == GfxIpLevel::GfxIp6) || (gfxLevel == GfxIpLevel::GfxIp7))
{
// This bit is obsolete on gfxip 8 (VI), although it still exists in the reg spec (therefore,
// there's no __SI__CI extension on its name).
cbColorInfo.bits.CMASK_IS_LINEAR = pCmask->IsLinear();
}
else
{
// If the fMask is going to be texture-fetched, then the fMask SRD will contain a
// pointer to the cMask, which also needs to be in a tiling mode that the texture
// block can understand.
if (!fMaskTexFetchAllowed)
{
cbColorInfo.bits.CMASK_ADDR_TYPE__VI = pCmask->IsLinear() ? CMASK_ADDR_LINEAR : CMASK_ADDR_TILED;
}
else
{
// Put the cmask into a tiling format that allows the texture block to read
// it directly.
cbColorInfo.bits.CMASK_ADDR_TYPE__VI = CMASK_ADDR_COMPATIBLE;
}
}
m_pm4Cmds.cbColorCmaskSlice.u32All = pCmask->CbColorCmaskSlice().u32All;
}
if (m_flags.hasFmask != 0)
{
const Gfx6Fmask* const pFmask = m_pImage->GetFmask(m_subresource);
// Setup CB_COLOR*_INFO, CB_COLOR*_ATTRIB and CB_COLOR*_PITCH register fields which
// depend on FMask state:
m_pm4Cmds.cbColorAttrib.bits.FMASK_TILE_MODE_INDEX = pFmask->TileIndex();
m_pm4Cmds.cbColorAttrib.bits.FMASK_BANK_HEIGHT = pFmask->BankHeight();
if (gfxLevel != GfxIpLevel::GfxIp6)
{
m_pm4Cmds.cbColorPitch.bits.FMASK_TILE_MAX__CI__VI = (pFmask->Pitch() / TileWidth) - 1;
cbColorInfo.bits.FMASK_COMPRESSION_DISABLE__CI__VI = !pFmask->UseCompression();
if (fMaskTexFetchAllowed && !internalInfo.flags.dccDecompress && !internalInfo.flags.fmaskDecompress)
{
// Setting this bit means two things:
// 1) The texture block can read fmask data directly without needing
// a decompress stage (documented).
// 2) If this bit is set then the fMask decompress operation will not occur
// whether happening explicitly through fmaskdecompress or as a part of
// dcc decompress.(not documented)
cbColorInfo.bits.FMASK_COMPRESS_1FRAG_ONLY__VI = 1;
}
}
m_pm4Cmds.cbColorFmaskSlice.u32All = pFmask->CbColorFmaskSlice().u32All;
}
else
{
// NOTE: Due to a quirk in the hardware when FMask is not in-use, we need to set some
// FMask-specific register fields to match the attributes of the base subResource.
m_pm4Cmds.cbColorAttrib.bits.FMASK_TILE_MODE_INDEX = baseTileIndex;
m_pm4Cmds.cbColorAttrib.bits.FMASK_BANK_HEIGHT = baseBankHeight;
if (gfxLevel != GfxIpLevel::GfxIp6)
{
m_pm4Cmds.cbColorPitch.bits.FMASK_TILE_MAX__CI__VI = m_pm4Cmds.cbColorPitch.bits.TILE_MAX;
}
m_pm4Cmds.cbColorFmaskSlice.bits.TILE_MAX = m_pm4Cmds.cbColorSlice.bits.TILE_MAX;
}
// NOTE: As mentioned above, due to quirks in the hardware when FMask is not being used, it is necessary to
// save a separate copy of CB_COLOR_ATTRIB.
m_cbColorAttribDecompressed.u32All = m_pm4Cmds.cbColorAttrib.u32All;
m_cbColorAttribDecompressed.bits.FMASK_TILE_MODE_INDEX = baseTileIndex;
m_cbColorAttribDecompressed.bits.FMASK_BANK_HEIGHT = baseBankHeight;
// Initialize blend optimization register bits. The blend optimizer will override these bits at draw time
// based on bound blend state. See ColorBlendState::WriteBlendOptimizations.
if (device.Settings().blendOptimizationsEnable)
{
cbColorInfo.bits.BLEND_OPT_DONT_RD_DST = FORCE_OPT_AUTO;
cbColorInfo.bits.BLEND_OPT_DISCARD_PIXEL = FORCE_OPT_AUTO;
}
else
{
cbColorInfo.bits.BLEND_OPT_DONT_RD_DST = FORCE_OPT_DISABLE;
cbColorInfo.bits.BLEND_OPT_DISCARD_PIXEL = FORCE_OPT_DISABLE;
}
// The CB_COLOR0_INFO RMW packet requires a mask. We want everything but these two bits,
// so we'll use the inverse of them.
constexpr uint32 RmwCbColorInfoMask =
static_cast<const uint32>(~(CB_COLOR0_INFO__BLEND_OPT_DONT_RD_DST_MASK |
CB_COLOR0_INFO__BLEND_OPT_DISCARD_PIXEL_MASK));
// All relevent register data has now been calculated; create the RMW packet.
device.CmdUtil().BuildContextRegRmw(mmCB_COLOR0_INFO,
RmwCbColorInfoMask,
cbColorInfo.u32All,
&m_pm4Cmds.colorBufferInfo);
}
// =====================================================================================================================
// Updates the specified PM4 image with the virtual addresses of the image and the image's various metadata addresses.
// This can never be called on buffer views; the buffer view address will be computed elsewhere.
void ColorTargetView::UpdateImageVa(
ColorTargetViewPm4Img* pPm4Img
) const
{
// The "GetSubresource256BAddrSwizzled" function will crash if no memory has been bound to
// the associated image yet, so don't do anything if it's not safe
if (m_pImage->Parent()->GetBoundGpuMemory().IsBound())
{
// Program Color Buffer base address
pPm4Img->cbColorBase.bits.BASE_256B = m_pImage->GetSubresource256BAddrSwizzled(m_subresource);
// Either cMask or DCC could have been used for a fast-clear. The load-meta-data packet updates the cb color
// regs to indicate what the clear color is. (See Gfx6FastColorClearMetaData in gfx6MaskRam.h).
if (m_flags.fastClearSupported)
{
// Program fast-clear metadata base address.
gpusize metaDataVirtAddr = m_pImage->FastClearMetaDataAddr(MipLevel());
PAL_ASSERT((metaDataVirtAddr & 0x3) == 0);
// If this view uses the legacy LOAD_CONTEXT_REG packet to load the fast-clear registers, we need to
// subtract the register offset for the LOAD packet from the address we specify to account for the fact that
// the CP uses that register offset for both the register address and to compute the final GPU address to
// fetch from. The newer LOAD_CONTEXT_REG_INDEX packet does not add the register offset to the GPU address.
if (m_flags.usesLoadRegIndexPkt == 0)
{
metaDataVirtAddr -= (sizeof(uint32) * pPm4Img->loadMetaData.regOffset);
pPm4Img->loadMetaData.addrLo = LowPart(metaDataVirtAddr);
pPm4Img->loadMetaData.addrHi.ADDR_HI = HighPart(metaDataVirtAddr);
}
else
{
// Note that the packet header doesn't provide a proper addr_hi alias (it goes into the addrOffset).
pPm4Img->loadMetaDataIndex.addrLo.ADDR_LO = (LowPart(metaDataVirtAddr) >> 2);
pPm4Img->loadMetaDataIndex.addrOffset = HighPart(metaDataVirtAddr);
}
}
if (m_flags.hasDcc)
{
pPm4Img->cbColorDccBase.bits.BASE_256B = m_pImage->GetDcc256BAddr(m_subresource);
if (m_flags.dccCompressionEnabled && m_flags.hasDccStateMetaData)
{
// Program the DCC state metadata address. (See Gfx6DccMipMetaData in gfx6MaskRam.h).
const gpusize metaDataVirtAddr = m_pImage->GetDccStateMetaDataAddr(MipLevel());
PAL_ASSERT((metaDataVirtAddr & 0x3) == 0);
pPm4Img->hdrMipMetaData.dstAddrLo = LowPart(metaDataVirtAddr);
pPm4Img->hdrMipMetaData.dstAddrHi = HighPart(metaDataVirtAddr);
}
}
if (m_flags.hasCmask)
{
// Program CMask base address.
pPm4Img->cbColorCmask.bits.BASE_256B = m_pImage->GetCmask256BAddr(m_subresource);
}
if (m_flags.hasFmask)
{
// Program FMask base address.
pPm4Img->cbColorFmask.bits.BASE_256B = m_pImage->GetFmask256BAddrSwizzled(m_subresource);
}
else
{
// According to the CB doc, fast-cleared surfaces without Fmask must program the
// Fmask base address reg to the same value as the base surface address reg.
pPm4Img->cbColorFmask.bits.BASE_256B = pPm4Img->cbColorBase.bits.BASE_256B;
}
}
}
// =====================================================================================================================
// Writes the PM4 commands required to bind to a certain slot. Returns the next unused DWORD in pCmdSpace.
uint32* ColorTargetView::WriteCommands(
uint32 slot,
ImageLayout imageLayout,
CmdStream* pCmdStream,
uint32* pCmdSpace
) const
{
const bool decompressedImage =
(m_flags.isBufferView == 0) &&
(ImageLayoutToColorCompressionState(m_layoutToState, imageLayout) != ColorCompressed);
const ColorTargetViewPm4Img* pPm4Commands = &m_pm4Cmds;
// Spawn a local copy of the PM4 image, since some register values and/or offsets may need to be updated in this
// method. For some clients, the base address, Fmask address and Cmask address also need to be updated. The
// contents of the local copy will depend on which Image state is specified.
ColorTargetViewPm4Img patchedPm4Commands;
if (slot != 0)
{
PAL_ASSERT(slot < MaxColorTargets);
patchedPm4Commands = *pPm4Commands;
pPm4Commands = &patchedPm4Commands;
// Offset to add to most PM4 headers' register offset.
const uint32 slotDelta = (slot * CbRegsPerSlot);
patchedPm4Commands.hdrCbColorBaseToView.regOffset += slotDelta;
patchedPm4Commands.hdrCbColorDccBase.regOffset += slotDelta;
patchedPm4Commands.hdrCbColorAttribToFmaskSlice.regOffset += slotDelta;
patchedPm4Commands.colorBufferInfo.regOffset += slotDelta;
patchedPm4Commands.loadMetaData.regOffset += slotDelta;
if ((m_flags.usesLoadRegIndexPkt == 0) && (m_flags.viewVaLocked != 0))
{
// If this view uses the legacy LOAD_CONTEXT_REG packet to load fast-clear registers, we need to update
// the metadata load address along with the register offset. See UpdateImageVa() for more details.
const gpusize metaDataVirtAddr =
((static_cast<uint64>(patchedPm4Commands.loadMetaData.addrHi.ADDR_HI) << 32) |
patchedPm4Commands.loadMetaData.addrLo) -
(sizeof(uint32) * slotDelta);
patchedPm4Commands.loadMetaData.addrHi.ADDR_HI = HighPart(metaDataVirtAddr);
patchedPm4Commands.loadMetaData.addrLo = LowPart(metaDataVirtAddr);
}
}
size_t spaceNeeded = pPm4Commands->spaceNeeded;
if (decompressedImage)
{
if (pPm4Commands != &patchedPm4Commands)
{
patchedPm4Commands = *pPm4Commands;
pPm4Commands = &patchedPm4Commands;
}
// For decompressed rendering to an Image, we need to override the values for CB_COLOR_INFO,,
// CB_COLOR_CMASK_SLICE and for CB_COLOR_DCC_CONTROL__VI.
patchedPm4Commands.cbColorCmaskSlice.u32All = CbColorCmaskSliceDecompressed;
patchedPm4Commands.cbColorDccControl.u32All = CbColorDccControlDecompressed;
patchedPm4Commands.colorBufferInfo.regData &= ~CbColorInfoDecompressedMask;
// NOTE: Due to a quirk in the hardware when FMask is not in-use, we need to set some FMask-specific register
// fields to match the attributes of the base subResource.
if (m_flags.isGfx7OrHigher)
{
patchedPm4Commands.cbColorPitch.bits.FMASK_TILE_MAX__CI__VI = patchedPm4Commands.cbColorPitch.bits.TILE_MAX;
}
patchedPm4Commands.cbColorFmaskSlice.bits.TILE_MAX = patchedPm4Commands.cbColorSlice.bits.TILE_MAX;
patchedPm4Commands.cbColorAttrib.u32All = m_cbColorAttribDecompressed.u32All;
spaceNeeded = pPm4Commands->spaceNeededDecompressed;
}
if ((m_flags.viewVaLocked == 0) && m_pImage->Parent()->GetBoundGpuMemory().IsBound())
{
if (pPm4Commands != &patchedPm4Commands)
{
patchedPm4Commands = *pPm4Commands;
pPm4Commands = &patchedPm4Commands;
}
UpdateImageVa(&patchedPm4Commands);
}
PAL_ASSERT(pCmdStream != nullptr);
return pCmdStream->WritePm4Image(spaceNeeded, pPm4Commands, pCmdSpace);
}
// =====================================================================================================================
// Writes the fast clear color register only to a new value. This function is sometimes called after a fast clear
// when it is detected that the cleared image is already bound with the old fast clear value loaded.
uint32* ColorTargetView::WriteUpdateFastClearColor(
uint32 slot,
const uint32 color[4],
CmdStream* pCmdStream,
uint32* pCmdSpace)
{
const uint32 slotRegIncr = (slot * CbRegsPerSlot);
pCmdSpace = pCmdStream->WriteSetSeqContextRegs(
mmCB_COLOR0_CLEAR_WORD0 + slotRegIncr,
mmCB_COLOR0_CLEAR_WORD1 + slotRegIncr,
color,
pCmdSpace);
return pCmdSpace;
}
// =====================================================================================================================
// Helper method which checks if DCC is enabled for a particular slot & image-layout combination. This is useful for a
// hardware workaround for the DCC overwrite combiner.
bool ColorTargetView::IsDccEnabled(
ImageLayout imageLayout
) const
{
bool enabled = false;
if ((m_flags.isBufferView == 0) &&
(ImageLayoutToColorCompressionState(m_layoutToState, imageLayout) == ColorCompressed))
{
enabled = ((m_pm4Cmds.colorBufferInfo.regData & CB_COLOR0_INFO__DCC_ENABLE_MASK__VI) != 0);
}
return enabled;
}
} // Gfx6
} // Pal
| 50.076379 | 120 | 0.638402 | [
"render",
"object"
] |
731210951ffc41f77b9b1af54ba82cc186284433 | 22,618 | cpp | C++ | tgmm-paper/src/temporalLogicalRules/trackletCalculation.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | tgmm-paper/src/temporalLogicalRules/trackletCalculation.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | tgmm-paper/src/temporalLogicalRules/trackletCalculation.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2011-2012 by Fernando Amat
* See license.txt for full license and copyright notice.
*
* Authors: Fernando Amat
*
* temporalLogicalRules.cpp
*
* Created on: October 29th, 2012
* Author: Fernando Amat
*
* \brief Methods to calculate tracklets from super-voxel decomposition
*
*/
#include <queue>
#include "trackletCalculation.h"
using namespace std;
int calculateTrackletsWithSparseHungarianAlgorithm(list< supervoxel > &svListT0, int distanceMethod, double thrCost, vector<SibilingTypeSupervoxel>& assignmentId, SibilingTypeSupervoxel* nullAssignment)
{
//calculate maximum number of edges
int E = 0;
//reset all the candidates to setup indexes
for(list< supervoxel >::iterator iter = svListT0.begin(); iter != svListT0.end(); ++iter)
{
for(vector<SibilingTypeSupervoxel>::iterator iterNeigh = iter->nearestNeighborsInTimeForward.begin(); iterNeigh != iter->nearestNeighborsInTimeForward.end(); ++iterNeigh)
{
(*iterNeigh)->tempWildcard = -1.0f; //so we know which ones have not been assigned
E++;
}
}
//setup distance method
float (supervoxel::*dd_func_ptr)(const supervoxel&) const;//define pointer to function-member class
switch(distanceMethod)
{
case 0://Jaccard
dd_func_ptr = &supervoxel::JaccardDistance;
break;
case 1://Euclidean
dd_func_ptr = &supervoxel::Euclidean2Distance;
thrCost = thrCost * thrCost;//the distance is calculate without sqrt to save operations
break;
default:
cout<<"ERROR: at calculateTrackletsWithSparseHungarianAlgorithm: distanceMEthod not supported by the code"<<endl;
return 1;
}
//set workspace
workspaceSparseHungarian* W = (workspaceSparseHungarian*) malloc(sizeof(workspaceSparseHungarian));
workspaceSpraseHungarian_init(W, svListT0.size(), 0, E, thrCost);//we need to update M after going trhough all the neighbors
//calculate distances
int M = 0;
E = 0;//reset
float dd;
W->edgesPtr[0] = 0;
int countS = 0;
for(list< supervoxel >::iterator iter = svListT0.begin(); iter != svListT0.end(); ++iter)
{
for(vector<SibilingTypeSupervoxel>::iterator iterNeigh = iter->nearestNeighborsInTimeForward.begin(); iterNeigh != iter->nearestNeighborsInTimeForward.end(); ++iterNeigh)
{
dd = ((*iter).*dd_func_ptr)(*(*iterNeigh));//call the selected distance
if(dd < thrCost)//better than assigning to Garbage potential
{
//check if this supervoxel has already been assigned an id
if((*iterNeigh)->tempWildcard < 0.0f)
{
(*iterNeigh)->tempWildcard = (float)M;
M++;
}
W->edgesId[E] = (int)((*iterNeigh)->tempWildcard);
W->edgesW[E] = dd;
E++;
}
}
countS++;
W->edgesPtr[countS] = E;
}
//update number of edges and number of candidates
W->E = E;
W->M = M;
//solve assignment problem
int* assignmentIdAux = new int[W->N];
if(W->E == 0)//degenerate case
{
for(int ii = 0;ii<W->N;ii++)
assignmentIdAux[ii] = -1;//garbage potential (no assignment) for all of them
}
else{//regular case
int err = solveSparseHungarianAlgorithm(W, assignmentIdAux);
if(err > 0)
return err;
}
//remap id to iterators to supervoxels
countS = 0;
assignmentId.resize(W->N);
for(list< supervoxel >::iterator iter = svListT0.begin(); iter != svListT0.end(); ++iter, countS++)
{
if(assignmentIdAux[countS] < 0)//garbage potential
{
assignmentId[countS] = *nullAssignment;//to signal not assignment!!
continue;
}
dd = (float)(assignmentIdAux[countS]);
for(vector<SibilingTypeSupervoxel>::iterator iterNeigh = iter->nearestNeighborsInTimeForward.begin(); iterNeigh != iter->nearestNeighborsInTimeForward.end(); ++iterNeigh)
{
if( dd == (*iterNeigh)->tempWildcard)
{
assignmentId[countS] = (*iterNeigh);
break;
}
}
}
//release memory
delete[] assignmentIdAux;
workspaceSpraseHungarian_destroy(W);
free(W);
return 0;
}
//=====================================================================================================
int calculateTrackletsWithSparseHungarianAlgorithm(lineageHyperTree& lht, int distanceMethod, double thrCost, unsigned int numThreads)
{
if(numThreads > 0)
{
cout<<"WARNING: at calculateTrackletsWithSparseHungarianAlgorithm: code is not multi-threaded yet"<<endl;//TODO
}
//calculate assignment for each pair of time points. TODO: parallelize this piece of code. Ishould be straight forward
vector< vector<SibilingTypeSupervoxel> > assignmentId;//assignmentId[ii] contains assignments from time jj->jj+1
assignmentId.resize(lht.getMaxTM()-1);
list< supervoxel> nullAssignmentList;//temporary supervoxel list to simulate null assignment
nullAssignmentList.push_back(supervoxel());
SibilingTypeSupervoxel nullAssignment = nullAssignmentList.begin();
nullAssignment->centroid[0] = -1e32f;//characteristic to find out no assignment
for(int ii = 0; ii< lht.getMaxTM()-1; ii++)
{
//recalculate nearest neighbors
lht.supervoxelNearestNeighborsInTimeForward(ii);
//calculate association
int err = calculateTrackletsWithSparseHungarianAlgorithm(lht.supervoxelsList[ii], distanceMethod, thrCost, assignmentId[ii], &nullAssignment);
if (err > 0)
return err;
}
//delete all the lineages
for(list<lineage>::iterator iterL = lht.lineagesList.begin(); iterL != lht.lineagesList.end(); ++iterL)
{
iterL->bt.remove( iterL->bt.pointer_mainRoot() );//deletes all the lineage recursively
}
lht.lineagesList.clear();
//delete all the nuclei
for( int ii = 0; ii< lht.getMaxTM(); ii++)
{
lht.nucleiList[ii].clear();
}
//delete all references to nuclei from supervoxels
for( int ii = 0; ii< lht.getMaxTM(); ii++)
{
int count = 0;//so I know index for each superovoxel
for(list<supervoxel>::iterator iterS = lht.supervoxelsList[ii].begin(); iterS != lht.supervoxelsList[ii].end(); ++iterS, count++)
{
iterS->treeNode.deleteParent();
iterS->tempWildcard = (float)count;
}
}
//reconstruct nuclei and lineages from assignments (in this case one nuclei correspond to one supervoxel)
//in this case it is a little bit easier since there are no divisions
SibilingTypeNucleus iterN;
for( int ii = 0; ii< lht.getMaxTM()-1; ii++)
{
int countS = 0;
for(list<supervoxel>::iterator iterS = lht.supervoxelsList[ii].begin(); iterS != lht.supervoxelsList[ii].end(); ++iterS, countS++)
{
//if(iterS->tempWildcard < 0.0f || assignmentId[ii][countS]->centroid[0] < -1e30f) //supervoxel has already been visited or it was not assigned
if(iterS->tempWildcard < 0.0f ) //supervoxel has already been visited. Thus, we allow tracklets of single supervoxels
continue;
//we start a new lineage
SibilingTypeSupervoxel auxS = iterS;
lht.lineagesList.push_back(lineage());
ParentTypeNucleus iterL = (++ ( lht.lineagesList.rbegin() ) ).base();//iterator to last added lineage
int posTM = ii, posID;
while((auxS)->centroid[0] > 0.0f)//compare to null assignment
{
//create nucleus
iterN = lht.addNucleusFromSupervoxel(posTM,auxS);
//update lineage
iterL->bt.SetCurrent( iterL->bt.insert(iterN) );
//update hypertree
iterN->treeNode.setParent(iterL);
iterN->treeNodePtr = iterL->bt.pointer_current();
//find next element
posID = (int)((auxS)->tempWildcard);
(auxS)->tempWildcard = -1.0f;//signal that supervoxel has been visited
if(posTM >= lht.getMaxTM() - 1)
break;//we reached final time point->there is no next element
auxS = assignmentId[posTM][posID];
posTM++;
}
}
}
//add supervoxels in the last frame that have not been assigned to anybody
int posTM = lht.getMaxTM()-1;
for(list<supervoxel>::iterator iterS = lht.supervoxelsList[posTM].begin(); iterS != lht.supervoxelsList[posTM].end(); ++iterS)
{
if(iterS->tempWildcard < 0.0f ) //supervoxel has already been visited. Thus, we allow tracklets of single supervoxels
continue;
//we start a new lineage
lht.lineagesList.push_back(lineage());
ParentTypeNucleus iterL = (++ ( lht.lineagesList.rbegin() ) ).base();//iterator to last added lineage
//create nucleus
iterN = lht.addNucleusFromSupervoxel(posTM,iterS);
//update lineage
iterL->bt.SetCurrent( iterL->bt.insert(iterN) );
//update hypertree
iterN->treeNode.setParent(iterL);
iterN->treeNodePtr = iterL->bt.pointer_current();
}
return 0;
}
//==============================================================================================================
int extendMatchingWithClearOneToOneAssignments(list< supervoxel > &superVoxelA, list< supervoxel > &superVoxelB, vector< vector< SibilingTypeSupervoxel > > &nearestNeighborVecAtoB, vector< vector< SibilingTypeSupervoxel > > &nearestNeighborVecBtoA, assignmentOneToMany* assignmentId)
{
int N = (int) superVoxelA.size();
int M = (int) superVoxelB.size();
if( superVoxelB.size() != nearestNeighborVecBtoA.size() )
{
std::cout<<"ERROR: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: size of nearest neighbor vector BtoA is not the same as candidates list"<<endl;
return 2;
}
if( superVoxelA.size() != nearestNeighborVecAtoB.size() )
{
std::cout<<"ERROR: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: size of nearest neighbor vector AtoB is not the same as input list"<<endl;
return 2;
}
//generate a list of candidate elements that have been matched already (so we do not duplicate)
bool* assignedId = new bool[M];
memset(assignedId, 0, sizeof(bool) * M );//reset
for(int ii = 0; ii<N; ii++)
{
for(int jj = 0; jj<assignmentId[ii].numAssignments; jj++)
{
assignedId[ assignmentId[ii].assignmentId[jj] ] = true;
}
}
//set indexes for the list
int ii = 0;
for(list<supervoxel>::iterator iterS = superVoxelA.begin(); iterS != superVoxelA.end(); ++iterS, ++ii)
iterS->tempWildcard = ((float) ii);
ii = 0;
vector< list<supervoxel>::iterator > vecIterB( M );//array of iterators to be able to access list
for(list<supervoxel>::iterator iterS = superVoxelB.begin(); iterS != superVoxelB.end(); ++iterS, ++ii)
{
iterS->tempWildcard = ((float) ii);
vecIterB[ii] = iterS;
}
ii = 0;
int numDeaths = 0, numExtended = 0;
for(list<supervoxel>::iterator iterS = superVoxelA.begin(); iterS != superVoxelA.end(); ++iterS, ++ii)
{
if( assignmentId[ii].numAssignments > 0 )
continue;//this elements has been assigned already
numDeaths++;
//find the best candidate from A->B
float costAux, costBestAB = 0.0f;
int idBestAB = -1;
for(vector<SibilingTypeSupervoxel>::iterator iter = nearestNeighborVecAtoB[ii].begin(); iter != nearestNeighborVecAtoB[ii].end(); ++iter )
{
if( assignedId[ (int) ( (*iter)->tempWildcard ) ] == true ) // already assigned
continue;
costAux = iterS->intersectionCost( *(*iter) );
if( costAux > costBestAB )
{
costBestAB = costAux;
idBestAB = (int) ( (*iter)->tempWildcard );
}
}
//check if the best candidate from A->B is also from B->A
int idBestBA = ii;
if( idBestAB >= 0)
{
list< supervoxel >::iterator iterSB = vecIterB[idBestAB];
float costBestBA = costBestAB + 0.1f;//to avoid floating point error in comparison
for(vector<SibilingTypeSupervoxel>::iterator iter = nearestNeighborVecBtoA[ idBestAB ].begin(); iter != nearestNeighborVecBtoA[idBestAB].end(); ++iter )
{
costAux = iterSB->intersectionCost( *(*iter) );
if( costAux > costBestBA )
{
idBestBA = (int) ( (*iter)->tempWildcard );
break;
}
}
//check if there was the one-to-one correspondence to extend element
if (idBestBA == ii)
{
assignmentId[ii].assignmentId[0] = idBestAB;
assignmentId[ii].assignmentCost[0] = costBestAB;
assignmentId[ii].numAssignments = 1;
assignedId[ idBestAB ] = true;
numExtended++;
}
}
}
std::cout<<"INFO: extendMatchingWithClearOneToOneAssignments: number of extended deaths "<<numExtended<<" out of "<<numDeaths<<" elements that are not assigned yet."<<endl;
//release memory
delete[] assignedId;
return 0;
}
//==============================================================================================================
//very similar to extendMatchingWithClearOneToOneAssignments but in this case is a distance (->we try to MINIMIZE)
int extendMatchingWithClearOneToOneAssignmentsEuclidean(list< supervoxel > &superVoxelA, list< supervoxel > &superVoxelB, vector< vector< SibilingTypeSupervoxel > > &nearestNeighborVecAtoB, vector< vector< SibilingTypeSupervoxel > > &nearestNeighborVecBtoA, assignmentOneToMany* assignmentId)
{
int N = (int) superVoxelA.size();
int M = (int) superVoxelB.size();
if( superVoxelB.size() != nearestNeighborVecBtoA.size() )
{
std::cout<<"ERROR: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: size of nearest neighbor vector BtoA is not the same as candidates list"<<endl;
return 2;
}
if( superVoxelA.size() != nearestNeighborVecAtoB.size() )
{
std::cout<<"ERROR: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: size of nearest neighbor vector AtoB is not the same as input list"<<endl;
return 2;
}
//set indexes for the list
int ii = 0;
for(list<supervoxel>::iterator iterS = superVoxelA.begin(); iterS != superVoxelA.end(); ++iterS, ++ii)
iterS->tempWildcard = ((float) ii);
ii = 0;
vector< list<supervoxel>::iterator > vecIterB( M );//array of iterators to be able to access list
for(list<supervoxel>::iterator iterS = superVoxelB.begin(); iterS != superVoxelB.end(); ++iterS, ++ii)
{
iterS->tempWildcard = ((float) ii);
vecIterB[ii] = iterS;
}
//generate a list of candidate elements that have been matched already (so we do not duplicate)
bool* assignedId = new bool[M];
memset(assignedId, 0, sizeof(bool) * M );//reset
float thrDist2 = 0.0f;
int thrDistN = 0;
ii = 0;
for(list<supervoxel>::iterator iter = superVoxelA.begin(); iter!= superVoxelA.end(); ++iter, ++ii)
{
for(int jj = 0; jj<assignmentId[ii].numAssignments; jj++)
{
assignedId[ assignmentId[ii].assignmentId[jj] ] = true;
thrDist2 += iter->Euclidean2Distance( *(vecIterB[ assignmentId[ii].assignmentId[jj] ]) );//we need to calculate average displacement to set an adaptive threshold for matching
thrDistN++;
}
}
thrDist2 *= 5.0f / ( (float) thrDistN );//threshold is K times teh average displacement (we are looking for things that do not intersect, so we can be generous)
ii = 0;
int numDeaths = 0, numExtended = 0;
for(list<supervoxel>::iterator iterS = superVoxelA.begin(); iterS != superVoxelA.end(); ++iterS, ++ii)
{
if( assignmentId[ii].numAssignments > 0 )
continue;//this elements has been assigned already
numDeaths++;
//find the best candidate from A->B
float costAux, costBestAB = thrDist2;//it has to be better than the threshold
int idBestAB = -1;
for(vector<SibilingTypeSupervoxel>::iterator iter = nearestNeighborVecAtoB[ii].begin(); iter != nearestNeighborVecAtoB[ii].end(); ++iter )
{
if( assignedId[ (int) ( (*iter)->tempWildcard ) ] == true ) // already assigned
continue;
costAux = iterS->Euclidean2Distance( *(*iter) );
if( costAux < costBestAB )
{
costBestAB = costAux;
idBestAB = (int) ( (*iter)->tempWildcard );
}
}
//check if the best candidate from A->B is also from B->A
int idBestBA = ii;
if( idBestAB >= 0)
{
list< supervoxel >::iterator iterSB = vecIterB[idBestAB];
float costBestBA = costBestAB - 0.001f;//to avoid floating point error in comparison
for(vector<SibilingTypeSupervoxel>::iterator iter = nearestNeighborVecBtoA[ idBestAB ].begin(); iter != nearestNeighborVecBtoA[idBestAB].end(); ++iter )
{
//if( assignmentId[ (int) ( (*iter)->tempWildcard ) ].numAssignments > 0 ) continue; //uncommment this line to only check the ones that have not been assigned yet
costAux = iterSB->Euclidean2Distance( *(*iter) );
if( costAux < costBestBA )
{
idBestBA = (int) ( (*iter)->tempWildcard );
break;
}
}
//check if there was the one-to-one correspondence to extend element
if (idBestBA == ii)
{
assignmentId[ii].assignmentId[0] = idBestAB;
assignmentId[ii].assignmentCost[0] = -1.0f;//useless here
assignmentId[ii].numAssignments = 1;
assignedId[ idBestAB ] = true;
numExtended++;
}
}
}
std::cout<<"INFO: extendMatchingWithClearOneToOneAssignmentsEuclidean: number of extended deaths "<<numExtended<<" out of "<<numDeaths<<" elements that are not assigned yet. ThrDist2 = "<<thrDist2<<endl;
//release memory
delete[] assignedId;
return 0;
}
//==============================================================================================
int calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm(list< supervoxel > &superVoxelA, list< supervoxel > &superVoxelB, vector< vector< SibilingTypeSupervoxel > > &nearestNeighborVec, int costMethod, double thrCost, assignmentOneToMany* assignmentId)
{
int N = (int) superVoxelA.size();
int M = (int) superVoxelB.size();
if( superVoxelB.size() != nearestNeighborVec.size() )
{
cout<<"ERROR: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: size of nearest neighbor vector is not the same as candidates list"<<endl;
return 2;
}
//setup distance method
float (supervoxel::*cost_func_ptr)(const supervoxel&) const;//define pointer to function-member class
switch(costMethod)
{
case 0://absolute number of intersecting points
cost_func_ptr = &supervoxel::intersectionCost;
break;
case 1://relative number of intersecting points with respect to candidate size. Maximum value is 1.0
cost_func_ptr = &supervoxel::intersectionCostRelativeToCandidate;
break;
default:
cout<<"ERROR: at calculateTrackletsWithSparseHungarianAlgorithm: distanceMEthod not supported by the code"<<endl;
return 1;
}
//to keep the best assignment for each input (we need it later to try to extend dead)
int* bestAssignmentId = new int[N];
float* bestAssignmentCost = new float[N];
//reset solution
for(int ii = 0;ii<N;ii++)
{
assignmentId[ii].numAssignments = 0;//garbage potential (no assignment) for all of them
bestAssignmentId[ii] = -1;
bestAssignmentCost[ii] = thrCost;
}
//reset wildcard in supervoxelA to identify id
int count = 0;
for(list< supervoxel >::iterator iter = superVoxelA.begin(); iter != superVoxelA.end(); ++iter, ++count)
{
iter->tempWildcard = count;
}
//since we allow one-to-many, we do not need Hungarian. It is just a greedy selection from the point of view of the candidates
count = 0;
int k, kAux;
float costAux, costBest;
for(list< supervoxel >::iterator iter = superVoxelB.begin(); iter != superVoxelB.end(); ++iter, ++count)
{
costBest = thrCost;
k = -1;
for(vector<SibilingTypeSupervoxel>::iterator iterNeigh = nearestNeighborVec[count].begin(); iterNeigh != nearestNeighborVec[count].end(); ++iterNeigh)
{
costAux = ((*iter).*cost_func_ptr)(*(*iterNeigh));//call the selected distance
kAux = ( (int) (*iterNeigh)->tempWildcard );
if( (costAux > costBest) )//better than assigning to garbage potential
{
k = kAux;
costBest = costAux;
}
//if we were assigning it greedy (without uniqueness constraints)
if( bestAssignmentCost[kAux] < costAux )
{
bestAssignmentCost[kAux] = costAux;
bestAssignmentId[kAux] = count;
}
}
if( k >= 0)
{
if( assignmentId[k].numAssignments < MAX_NUMBER_ASSINGMENTS_SHA )
{
assignmentId[k].assignmentCost[ assignmentId[k].numAssignments ] = costBest;
assignmentId[k].assignmentId[ assignmentId[k].numAssignments++ ] = count;
}else
{
cout<<"WARNING: at calculateTrackletsWithSparseHungarianAlgorithm: supervoxel "<<k<<" has exceeded the maximum number of possible assignments"<<endl;
//return 3;
}
}
}
#ifdef USE_DEATH_EXTENSION_ALGORITHM
//we want to try to impose that every input nucleus has an assignment so we run a greedy matching to see if some of the elements that have not been assigned can "steal" an element from elements with multiple assignments
int numExtended = 0, numNotAssigned = 0;
vector<int> deadId;
deadId.reserve(500);
for(int ii = 0;ii<N;ii++)
{
if( assignmentId[ii].numAssignments == 0 )
{
numNotAssigned++;
if(bestAssignmentId[ii] >= 0)
{
deadId.push_back(ii);
}
}
}
//find who has "stolen" the best assignment
int auxId;
vector<int> stolenId(deadId.size(), -1);
for(int ii = 0;ii<N;ii++)
{
for( int jj = 0;jj < assignmentId[ii].numAssignments; jj++)
{
//linear search (we do not expect deadId to be ver large
auxId = assignmentId[ii].assignmentId[jj];
for(size_t kk = 0; kk < deadId.size(); kk++)
{
if( auxId == bestAssignmentId [ deadId[kk] ])
{
stolenId[kk] = ii;
break;
}
}
}
}
//check if we can extend death
int auxId2, old;
for(size_t ii = 0; ii < deadId.size(); ii++)
{
if( stolenId[ii] >= 0 && assignmentId[ stolenId[ii] ].numAssignments > 1 )
{
numExtended++;
//place new assignment
auxId = deadId[ii];
assignmentId[ auxId ].assignmentId[0] = bestAssignmentId [ auxId ];
assignmentId[ auxId ].assignmentCost[0] = bestAssignmentCost [ auxId ];
assignmentId[ auxId ].numAssignments = 1;
//remove from previous "owner"
auxId2 = stolenId[ii];
old = assignmentId[ auxId2 ].numAssignments;
for( int jj = 0;jj < assignmentId[ auxId2 ].numAssignments; jj++)
{
if( bestAssignmentId [ auxId ] == assignmentId[ auxId2 ].assignmentId[jj] )
{
//delete element
for( int kk = jj; kk < assignmentId[ auxId2 ].numAssignments -1; kk++ )
{
assignmentId[ auxId2 ].assignmentId[ kk ] = assignmentId[ auxId2 ].assignmentId[ kk+1 ];
assignmentId[ auxId2 ].assignmentCost[ kk ] = assignmentId[ auxId2 ].assignmentCost[ kk+1 ];
}
assignmentId[ auxId2 ].numAssignments--;
break;
}
}
if( old - assignmentId[ auxId2 ].numAssignments != 1 )
{
cout<<"ERROR: at calculateTrackletsWithSparseHungarianAlgorithm: I should never reach this line!!!"<<endl;
return 4;
}
}
}
cout<<"INFO: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: number of extended deaths "<<numExtended<<" out of "<<deadId.size()<<" elements that are not assigned but have an edge."<<endl;
cout<<"INFO: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: total of not assignments is "<<numNotAssigned<<" out of "<<N<<" input elements to be matched"<<endl;
#else
cout<<"INFO: calculateSupervoxelMatchingOneToManyWithSparseHungarianAlgorithm: greedy algorithm to try to extend deaths not in use"<<endl;
#endif
//release memory
delete[] bestAssignmentId;
delete[] bestAssignmentCost;
return 0;
} | 35.012384 | 292 | 0.687992 | [
"vector"
] |
73135e55b313c29f706877280f25478812198bd8 | 39,468 | cpp | C++ | src/special.cpp | FaultyRAM/MuckyFoot-UrbanChaos | 45c9553189f80785a4ea0ec34b960d864782155b | [
"MIT"
] | 5 | 2017-10-02T00:20:06.000Z | 2021-07-09T10:00:18.000Z | src/special.cpp | FaultyRAM/MuckyFoot-UrbanChaos | 45c9553189f80785a4ea0ec34b960d864782155b | [
"MIT"
] | null | null | null | src/special.cpp | FaultyRAM/MuckyFoot-UrbanChaos | 45c9553189f80785a4ea0ec34b960d864782155b | [
"MIT"
] | null | null | null | // Special.cpp
// Guy Simmons, 28th March 1998.
//
//
//
// WILLIAM SHAKESPEARE (1564-1616)
//
// Shall I compare thee to a summer's day?
// Thou art more lovely and more temperate.
// Rough winds do shake the darling buds of May,
// And summer's lease hath all too short a date.
// Sometime too hot the eye of heaven shines,
// And often is his gold complexion dimm'd;
// And every fair from fair sometime declines,
// By chance or nature's changing course untrimm'd;
// But thy eternal summer shall not fade
// Nor lose possession of that fair thou ow'st;
// Nor shall Death brag thou wander'st in his shade,
// When in eternal lines to time thou grow'st:
// So long as men can breathe or eyes can see,
// So long lives this, and this gives life to thee.
//
#include <fallen/game.h>
#include <fallen/state_def.h>
#include <fallen/special.h>
#include <fallen/eway.h>
#include <fallen/pcom.h>
#include <fallen/night.h>
#include <fallen/dirt.h>
#include <fallen/animate.h>
#include <fallen/cnet.h>
#include <fallen/pow.h>
#include <fallen/memory.h>
#include <fallen/xlat_str.h>
#include <fallen/sound.h>
#include <fallen/grenade.h>
#ifndef PSX
#include <ddengine/panel.h>
#else
#include "c:\fallen\psxeng\headers\panel.h"
#endif
extern void add_damage_text(SWORD x,SWORD y,SWORD z,CBYTE *text);
SPECIAL_Info SPECIAL_info[SPECIAL_NUM_TYPES] =
{
{"None", 0, 0 },
{"Key", PRIM_OBJ_ITEM_KEY, SPECIAL_GROUP_USEFUL },
{"Gun", PRIM_OBJ_ITEM_GUN, SPECIAL_GROUP_ONEHANDED_WEAPON },
{"Health", PRIM_OBJ_ITEM_HEALTH, SPECIAL_GROUP_COOKIE },
{"Bomb", PRIM_OBJ_THERMODROID, SPECIAL_GROUP_STRANGE },
{"Shotgun", PRIM_OBJ_ITEM_SHOTGUN, SPECIAL_GROUP_TWOHANDED_WEAPON },
{"Knife", PRIM_OBJ_ITEM_KNIFE, SPECIAL_GROUP_ONEHANDED_WEAPON },
{"Explosives", PRIM_OBJ_ITEM_EXPLOSIVES, SPECIAL_GROUP_USEFUL },
{"Grenade", PRIM_OBJ_ITEM_GRENADE, SPECIAL_GROUP_ONEHANDED_WEAPON },
{"Ak47", PRIM_OBJ_ITEM_AK47, SPECIAL_GROUP_TWOHANDED_WEAPON },
{"Mine", PRIM_OBJ_MINE, SPECIAL_GROUP_STRANGE },
{"Thermodroid", PRIM_OBJ_THERMODROID, SPECIAL_GROUP_STRANGE },
{"Baseballbat", PRIM_OBJ_ITEM_BASEBALLBAT, SPECIAL_GROUP_TWOHANDED_WEAPON },
{"Ammo pistol", PRIM_OBJ_ITEM_AMMO_PISTOL, SPECIAL_GROUP_AMMO },
{"Ammo shotgun", PRIM_OBJ_ITEM_AMMO_SHOTGUN, SPECIAL_GROUP_AMMO },
{"Ammo AK47", PRIM_OBJ_ITEM_AMMO_AK47, SPECIAL_GROUP_AMMO },
{"Keycard", PRIM_OBJ_ITEM_KEYCARD, SPECIAL_GROUP_USEFUL },
{"File", PRIM_OBJ_ITEM_FILE, SPECIAL_GROUP_USEFUL },
{"Floppy_disk", PRIM_OBJ_ITEM_FLOPPY_DISK, SPECIAL_GROUP_USEFUL },
{"Crowbar", PRIM_OBJ_ITEM_CROWBAR, SPECIAL_GROUP_USEFUL },
{"Video", PRIM_OBJ_ITEM_VIDEO, SPECIAL_GROUP_USEFUL },
{"Gloves", PRIM_OBJ_ITEM_GLOVES, SPECIAL_GROUP_USEFUL },
{"WeedAway", PRIM_OBJ_ITEM_WEEDKILLER, SPECIAL_GROUP_USEFUL },
{"Badge", PRIM_OBJ_ITEM_TREASURE, SPECIAL_GROUP_COOKIE },
{"Red Car Keys", PRIM_OBJ_ITEM_KEY, SPECIAL_GROUP_USEFUL },
{"Blue Car Keys", PRIM_OBJ_ITEM_KEY, SPECIAL_GROUP_USEFUL },
{"Green Car Keys", PRIM_OBJ_ITEM_KEY, SPECIAL_GROUP_USEFUL },
{"Black Car Keys", PRIM_OBJ_ITEM_KEY, SPECIAL_GROUP_USEFUL },
{"White Car Keys", PRIM_OBJ_ITEM_KEY, SPECIAL_GROUP_USEFUL },
{"Wire Cutters", PRIM_OBJ_ITEM_WRENCH, SPECIAL_GROUP_USEFUL },
};
void free_special(Thing *s_thing);
//
// Adds/removes the special from a person's
//
void special_pickup(Thing *p_special, Thing *p_person)
{
ASSERT(p_special->Class == CLASS_SPECIAL);
ASSERT(p_person ->Class == CLASS_PERSON);
ASSERT(p_special->Genus.Special->SpecialType!=SPECIAL_MINE);
p_special->Genus.Special->OwnerThing = THING_NUMBER(p_person);
p_special->Genus.Special->NextSpecial = p_person->Genus.Person->SpecialList;
p_person->Genus.Person->SpecialList = THING_NUMBER(p_special);
if (p_special->SubState == SPECIAL_SUBSTATE_PROJECTILE)
{
p_special->SubState = SPECIAL_SUBSTATE_NONE;
}
}
void special_drop(Thing *p_special, Thing *p_person)
{
#ifndef NDEBUG
SLONG count = 0;
#endif
ASSERT(p_special->Class == CLASS_SPECIAL);
ASSERT(p_person ->Class == CLASS_PERSON );
ASSERT(p_special->Genus.Special->SpecialType!=SPECIAL_MINE);
UWORD next = p_person->Genus.Person->SpecialList;
UWORD *prev = &p_person->Genus.Person->SpecialList;
while(1)
{
#ifndef NDEBUG
ASSERT(count++ < 100);
#endif
if (next == NULL)
{
//
// We haven't found the special... is this an error? I guess so.
//
// ASSERT(0);
return;
}
Thing* p_next = TO_THING(next);
ASSERT(p_next->Class == CLASS_SPECIAL);
if (next == THING_NUMBER(p_special))
{
//
// This is the special we want to drop. Take it out the the linked list.
//
*prev = p_special->Genus.Special->NextSpecial;
p_special->Genus.Special->NextSpecial = NULL;
p_special->Genus.Special->OwnerThing = NULL;
{
SLONG gx;
SLONG gy;
SLONG gz;
extern void find_nice_place_near_person( // In person.cpp
Thing *p_person,
SLONG *nice_x, // 8-bits per mapsquare
SLONG *nice_y,
SLONG *nice_z);
find_nice_place_near_person(
p_person,
&gx,
&gy,
&gz);
p_special->WorldPos.X = gx << 8;
p_special->WorldPos.Y = gy << 8;
p_special->WorldPos.Z = gz << 8;
}
//
// Put it on the map.
//
add_thing_to_map(p_special);
if (p_person->Genus.Person->PlayerID == 0)
{
//
// Don't drop a gun with MAX ammo.
//
switch(p_special->Genus.Special->SpecialType)
{
case SPECIAL_SHOTGUN:
p_special->Genus.Special->ammo = (Random() & 0x1) + 2;
break;
case SPECIAL_AK47:
p_special->Genus.Special->ammo = (Random() & 0x7) + 6;
break;
}
}
p_special->Velocity = 5; // can't pick it up for 5 gameturns!
p_special->Genus.Special->counter = 0; // Can't pick it up for one second.
p_special->SubState = SPECIAL_SUBSTATE_NONE;
if (next == p_person->Genus.Person->SpecialUse)
{
p_person->Genus.Person->SpecialUse = NULL;
}
if (next == p_person->Genus.Person->SpecialDraw)
{
p_person->Genus.Person->SpecialDraw = NULL;
}
return;
}
prev = &p_next->Genus.Special->NextSpecial;
next = p_next->Genus.Special->NextSpecial;
}
}
//
// Returns TRUE if the person is carrying a two-handed weapon.
//
SLONG person_has_twohanded_weapon(Thing *p_person)
{
return (person_has_special(p_person, SPECIAL_SHOTGUN) ||
person_has_special(p_person, SPECIAL_AK47 ) ||
person_has_special(p_person, SPECIAL_BASEBALLBAT));
}
//
// Should this person pick up the item?
//
SLONG should_person_get_item(Thing *p_person, Thing *p_special)
{
Thing *p_grenade;
Thing *p_explosives;
Thing *p_has;
/*
if(p_special->Velocity)
return(0);
*/
if (p_person->State == STATE_MOVEING &&
p_person->SubState == SUB_STATE_RUNNING_SKID_STOP)
{
return FALSE;
}
switch(p_special->Genus.Special->SpecialType)
{
case SPECIAL_GUN:
if (p_person->Flags & FLAGS_HAS_GUN)
{
//return p_person->Genus.Person->Ammo < SPECIAL_AMMO_IN_A_PISTOL; // If less than 15 rounds of ammo
return (p_person->Genus.Person->ammo_packs_pistol<255-SPECIAL_AMMO_IN_A_PISTOL);
}
else
{
//
// Always pick up a gun if you haven't got one.
//
return TRUE;
}
case SPECIAL_HEALTH:
return (p_person->Genus.Person->Health < health[p_person->Genus.Person->PersonType]); // If not at maximum health
case SPECIAL_BOMB:
return FALSE;
case SPECIAL_AK47:
p_has = person_has_special(p_person, SPECIAL_AK47);
return (!p_has || p_person->Genus.Person->ammo_packs_ak47 < 255-SPECIAL_AMMO_IN_A_AK47);
case SPECIAL_BASEBALLBAT:
//
// We can only carry one two-handed weapon at once.
//
return !person_has_special(p_person, SPECIAL_BASEBALLBAT);
case SPECIAL_SHOTGUN:
p_has = person_has_special(p_person, SPECIAL_SHOTGUN);
return (!p_has || p_person->Genus.Person->ammo_packs_shotgun < 255-SPECIAL_AMMO_IN_A_SHOTGUN);
case SPECIAL_KNIFE:
//
// We can only have one knife.
//
return !person_has_special(p_person, SPECIAL_KNIFE);
case SPECIAL_EXPLOSIVES:
p_explosives = person_has_special(p_person, SPECIAL_EXPLOSIVES);
//
// You can only carry 4 explosives.
//
return (p_explosives == NULL || p_explosives->Genus.Special->ammo < 4);
case SPECIAL_GRENADE:
p_grenade = person_has_special(p_person, SPECIAL_GRENADE);
//
// You can only carry 8 grenades.
//
return (p_grenade == NULL || p_grenade->Genus.Special->ammo < 8);
//
// Only pickup ammo when you have that weapon.
//
case SPECIAL_AMMO_SHOTGUN:
return(p_person->Genus.Person->ammo_packs_shotgun<255-SPECIAL_AMMO_IN_A_SHOTGUN);
return (SLONG) person_has_special(p_person, SPECIAL_SHOTGUN);
case SPECIAL_AMMO_AK47:
return(p_person->Genus.Person->ammo_packs_ak47<255-SPECIAL_AMMO_IN_A_AK47);
return (SLONG) person_has_special(p_person, SPECIAL_AK47);
case SPECIAL_AMMO_PISTOL:
return(p_person->Genus.Person->ammo_packs_pistol<255-SPECIAL_AMMO_IN_A_PISTOL);
return p_person->Flags & FLAGS_HAS_GUN;
case SPECIAL_MINE:
return(FALSE); //added my MD
default:
return TRUE;
}
}
//
// The player person has picked up the given item.
//
void person_get_item(Thing *p_person, Thing *p_special)
{
Thing *p_gun;
SLONG keep = FALSE;
SLONG x_message = 0;
SLONG overflow = 0; // ammo left over
// PANEL_new_text(0,4000," PICKUP special %d \n",p_special->Genus.Special->SpecialType);
switch(p_special->Genus.Special->SpecialType)
{
case SPECIAL_GUN:
if (p_person->Flags & FLAGS_HAS_GUN)
{
x_message = X_AMMO;
overflow=(SWORD)p_person->Genus.Person->Ammo + p_special->Genus.Special->ammo;
while (overflow>15)
{
p_person->Genus.Person->ammo_packs_pistol += 15;
overflow-=15;
}
p_person->Genus.Person->Ammo=overflow;
/* if ((SWORD)p_person->Genus.Person->Ammo + p_special->Genus.Special->ammo<256)
p_person->Genus.Person->Ammo += p_special->Genus.Special->ammo;
else
p_person->Genus.Person->Ammo = 255;*/
}
else
{
x_message = X_GUN;
p_person->Genus.Person->Ammo = p_special->Genus.Special->ammo;
p_person->Flags |= FLAGS_HAS_GUN;
}
break;
case SPECIAL_HEALTH:
x_message = X_HEALTH;
p_person->Genus.Person->Health += 100;
if (p_person->Genus.Person->Health > health[p_person->Genus.Person->PersonType])
{
p_person->Genus.Person->Health = health[p_person->Genus.Person->PersonType];
// p_person->Genus.Person->Health = 200;
}
break;
case SPECIAL_AMMO_SHOTGUN:
p_person->Genus.Person->ammo_packs_shotgun += SPECIAL_AMMO_IN_A_SHOTGUN;
x_message = X_AMMO;
break;
case SPECIAL_AMMO_AK47:
p_person->Genus.Person->ammo_packs_ak47 += SPECIAL_AMMO_IN_A_AK47;
x_message = X_AMMO;
break;
case SPECIAL_AMMO_PISTOL:
p_person->Genus.Person->ammo_packs_pistol += SPECIAL_AMMO_IN_A_PISTOL;
x_message = X_AMMO;
break;
case SPECIAL_MINE:
//
// You can't pick up mines any more.
//
ASSERT(0);
/*
ASSERT(p_special->SubState == SPECIAL_SUBSTATE_ACTIVATED);
//
// When the special comes to draw itself, it will draw itself at that
// person's hand. We don't remove it from the map or free up the special.
//
special_pickup(p_special, p_person);
keep = TRUE;
*/
break;
case SPECIAL_SHOTGUN:
{
Thing *p_gun = person_has_special(p_person, SPECIAL_SHOTGUN);
if (p_gun)
{
/* p_has->Genus.Special->ammo += p_special->Genus.Special->ammo;
if (p_has->Genus.Special->ammo > SPECIAL_AMMO_IN_A_SHOTGUN)
{
p_has->Genus.Special->ammo = SPECIAL_AMMO_IN_A_SHOTGUN;
}*/
overflow=(SWORD)p_gun->Genus.Special->ammo + p_special->Genus.Special->ammo;
while (overflow>SPECIAL_AMMO_IN_A_SHOTGUN)
{
p_person->Genus.Person->ammo_packs_shotgun += SPECIAL_AMMO_IN_A_SHOTGUN;
overflow-=SPECIAL_AMMO_IN_A_SHOTGUN;
}
p_gun->Genus.Special->ammo=overflow;
x_message = X_AMMO;
break;
}
else
{
special_pickup(p_special, p_person);
//
// Make sure it isn't drawn!
//
remove_thing_from_map(p_special);
//
// Dont free up the special.
//
keep = TRUE;
x_message = X_SHOTGUN;
break;
}
}
case SPECIAL_AK47:
{
Thing *p_gun = person_has_special(p_person, SPECIAL_AK47);
if (p_gun)
{
/* p_has->Genus.Special->ammo += p_special->Genus.Special->ammo;
if (p_has->Genus.Special->ammo > SPECIAL_AMMO_IN_A_AK47)
{
p_has->Genus.Special->ammo = SPECIAL_AMMO_IN_A_AK47;
}*/
overflow=(SWORD)p_gun->Genus.Special->ammo + p_special->Genus.Special->ammo;
while (overflow>SPECIAL_AMMO_IN_A_AK47)
{
p_person->Genus.Person->ammo_packs_ak47 += SPECIAL_AMMO_IN_A_AK47;
overflow-=SPECIAL_AMMO_IN_A_AK47;
}
p_gun->Genus.Special->ammo=overflow;
x_message = X_AMMO;
}
else
{
special_pickup(p_special, p_person);
//
// Make sure it isn't drawn!
//
remove_thing_from_map(p_special);
//
// Dont free up the special.
//
keep = TRUE;
x_message = X_AK;
}
break;
}
case SPECIAL_GRENADE:
{
Thing *p_has = person_has_special(p_person, SPECIAL_GRENADE);
if (p_has)
{
if(p_has->Genus.Special->ammo<100) //just to be on the safe side
p_has->Genus.Special->ammo += SPECIAL_AMMO_IN_A_GRENADE;
x_message = X_AMMO;
}
else
{
special_pickup(p_special, p_person);
//
// Make sure it isn't drawn!
//
remove_thing_from_map(p_special);
//
// Dont free up the special.
//
keep = TRUE;
x_message = X_GRENADE;
}
break;
}
case SPECIAL_EXPLOSIVES:
{
Thing *p_has = person_has_special(p_person, SPECIAL_EXPLOSIVES);
if (p_has)
{
p_has->Genus.Special->ammo += 1;
}
else
{
special_pickup(p_special, p_person);
//
// Make sure it isn't drawn!
//
remove_thing_from_map(p_special);
//
// Dont free up the special.
//
keep = TRUE;
}
if(p_special->SubState == SPECIAL_SUBSTATE_ACTIVATED)
{
//This is active lets make it inactive
p_special->SubState = SPECIAL_SUBSTATE_NONE;
}
x_message = X_EXPLOSIVES;
break;
}
case SPECIAL_TREASURE:
{
Thing *darci = NET_PERSON(0);
//
// Has a player picked us up?
//
if (!(darci->Genus.Person->Flags & FLAG_PERSON_DRIVING))
{
switch(p_special->Draw.Mesh->ObjectId)
{
case 81:
x_message = X_STA_INCREASED;
NET_PLAYER(0)->Genus.Player->Stamina++;
break;
case 94:
x_message = X_STR_INCREASED;
NET_PLAYER(0)->Genus.Player->Strength++;
break;
case 71:
x_message = X_REF_INCREASED;
NET_PLAYER(0)->Genus.Player->Skill++;
break;
case 39:
x_message = X_CON_INCREASED;
NET_PLAYER(0)->Genus.Player->Constitution++;
break;
default:
ASSERT(0);
break;
}
}
#ifdef PSX
PANEL_icon_time=30;
#endif
extern SLONG stat_count_bonus;
stat_count_bonus++;
}
keep = FALSE;
break;
default:
if (p_special->Genus.Special->SpecialType == SPECIAL_KNIFE) {x_message = X_KNIFE;}
if (p_special->Genus.Special->SpecialType == SPECIAL_BASEBALLBAT) {x_message = X_BASEBALL_BAT;}
if (p_special->Genus.Special->SpecialType == SPECIAL_KEY) {x_message = X_KEYCARD;}
if (p_special->Genus.Special->SpecialType == SPECIAL_VIDEO) {x_message = X_VIDEO;}
//
// Use it by default? Nope. Add it to the person's linked list of
// items carried.
//
special_pickup(p_special, p_person);
//
// Make sure it isn't drawn!
//
remove_thing_from_map(p_special);
//
// Dont free up the special.
//
keep = TRUE;
break;
}
if (x_message && p_person->Genus.Person->PlayerID)
{
/*
add_damage_text(
p_special->WorldPos.X >> 8,
p_special->WorldPos.Y + 0x2000 >> 8,
p_special->WorldPos.Z >> 8,
XLAT_str_ptr(x_message));
*/
PANEL_new_info_message(XLAT_str(x_message));
}
if (p_special->Genus.Special->waypoint)
{
//
// Tell the waypoint system.
//
EWAY_item_pickedup(p_special->Genus.Special->waypoint);
}
if (!keep)
{
//
// Don't need the special any more.
//
free_special(p_special);
}
}
void special_activate_mine(Thing *p_mine)
{
ASSERT(p_mine->Class == CLASS_SPECIAL);
ASSERT(p_mine->Genus.Special->SpecialType == SPECIAL_MINE);
if (NET_PERSON(0)->Genus.Person->Target == THING_NUMBER(p_mine))
{
//
// Make the player choose a new target.
//
NET_PERSON(0)->Genus.Person->Target = NULL;
}
/*
PYRO_construct(
p_mine->WorldPos,
-1,
0xa0);
*/
#ifdef PSX
POW_create(
POW_CREATE_LARGE_SEMI,
p_mine->WorldPos.X,
p_mine->WorldPos.Y,
p_mine->WorldPos.Z,
0,0,0);
PYRO_create(p_mine->WorldPos,PYRO_DUSTWAVE);
#else
PYRO_create(p_mine->WorldPos,PYRO_FIREBOMB);
PYRO_create(p_mine->WorldPos,PYRO_DUSTWAVE);
#endif
MFX_play_xyz(THING_NUMBER(p_mine),SOUND_Range(S_EXPLODE_START,S_EXPLODE_END),0,p_mine->WorldPos.X,p_mine->WorldPos.Y,p_mine->WorldPos.Z);
create_shockwave(
p_mine->WorldPos.X >> 8,
p_mine->WorldPos.Y >> 8,
p_mine->WorldPos.Z >> 8,
0x200,
250,
NULL);
free_special(p_mine);
}
DIRT_Info special_di;
void special_normal(Thing *s_thing)
{
SLONG i;
SLONG dx;
SLONG dy;
SLONG dz;
SLONG dist;
if (s_thing->Flags & FLAG_SPECIAL_HIDDEN)
{
//
// Counter is the ob this specail is inside!
//
}
else
{
s_thing->Genus.Special->counter += 16 * TICK_RATIO >> TICK_SHIFT;
}
if (s_thing->SubState == SPECIAL_SUBSTATE_PROJECTILE)
{
SpecialPtr ss;
SLONG velocity;
SLONG ground;
ss = s_thing->Genus.Special;
velocity = ss->timer;
velocity -= 0x8000;
velocity -= 256 * TICK_RATIO >> TICK_SHIFT;
s_thing->WorldPos.Y += velocity * TICK_RATIO >> TICK_SHIFT;
ground = PAP_calc_map_height_at(s_thing->WorldPos.X >> 8, s_thing->WorldPos.Z >> 8) + 0x30 << 8;
if (s_thing->WorldPos.Y < ground)
{
velocity = abs(velocity);
velocity >>= 1;
s_thing->WorldPos.Y = ground;
if (velocity < 0x100)
{
s_thing->SubState = SPECIAL_SUBSTATE_NONE;
s_thing->Genus.Special->timer = 0;
return;
}
}
velocity += 0x8000;
SATURATE(velocity, 0, 0xffff);
ss->timer= velocity;
return;
}
else
{
/*
ASSERT(s_thing->Velocity>=0 &&s_thing->Velocity<10);
if(s_thing->Velocity)
s_thing->Velocity--; // dropped things cant be picked up for a few gameturns.
*/
}
if (s_thing->Genus.Special->OwnerThing && s_thing->Genus.Special->SpecialType != SPECIAL_EXPLOSIVES)
{
Thing *p_owner = TO_THING(s_thing->Genus.Special->OwnerThing);
ASSERT(s_thing->Genus.Special->SpecialType != SPECIAL_MINE);
ASSERT(s_thing->Genus.Special->SpecialType != SPECIAL_NONE);
ASSERT((s_thing->Flags&FLAGS_ON_MAPWHO)==0);
//
// This special is being carried by someone- it can't be on the mapwho
//
s_thing->WorldPos = p_owner->WorldPos;
if (s_thing->Genus.Special->SpecialType == SPECIAL_GRENADE &&
s_thing->SubState == SPECIAL_SUBSTATE_ACTIVATED)
{
SLONG ticks = 16 * TICK_RATIO >> TICK_SHIFT;
if (s_thing->Genus.Special->timer < ticks)
{
//
// The grenade has gone off!
//
#ifndef PSX
CreateGrenadeExplosion(s_thing->WorldPos.X, s_thing->WorldPos.Y + 2256, s_thing->WorldPos.Z, p_owner);
#else
POW_create(
POW_CREATE_LARGE_SEMI,
s_thing->WorldPos.X,
s_thing->WorldPos.Y,
s_thing->WorldPos.Z,0,0,0);
create_shockwave(
s_thing->WorldPos.X >> 8,
s_thing->WorldPos.Y >> 8,
s_thing->WorldPos.Z >> 8,
0x300,
500,
p_owner);
#endif
p_owner->Genus.Person->SpecialUse = NULL;
if (s_thing->Genus.Special->ammo == 1)
{
special_drop(s_thing, p_owner);
free_special(s_thing);
}
else
{
s_thing->SubState = SPECIAL_SUBSTATE_NONE; // let's reset the grenade
s_thing->Genus.Special->ammo -= 1;
}
}
else
{
s_thing->Genus.Special->timer -= ticks;
}
}
}
else
{
//
// This special is lying on the ground. Mostly they rotate.
//
if (s_thing->Genus.Special->SpecialType == SPECIAL_BOMB &&
s_thing->SubState == SPECIAL_SUBSTATE_NONE)
{
//
// Deactivated bombs don't rotate.
//
}
else
{
if (s_thing->Genus.Special->SpecialType!=SPECIAL_MINE) // mines no longer rotate
if (s_thing->Genus.Special->SpecialType!=SPECIAL_EXPLOSIVES || s_thing->SubState != SPECIAL_SUBSTATE_ACTIVATED) // explosives waiting to go off no longer rotate
s_thing->Draw.Mesh->Angle = (s_thing->Draw.Mesh->Angle+32)&2047;
}
switch(s_thing->Genus.Special->SpecialType)
{
case SPECIAL_BOMB:
//
// Has the waypoint that created us gone active?
//
if (s_thing->Genus.Special->waypoint)
{
if (s_thing->SubState == SPECIAL_SUBSTATE_ACTIVATED)
{
if (EWAY_is_active(s_thing->Genus.Special->waypoint))
{
//
// Explode this bomb.
//
#ifndef PSX
PYRO_construct(
s_thing->WorldPos,
-1,
256);
#else
POW_create(
POW_CREATE_LARGE_SEMI,
s_thing->WorldPos.X,
s_thing->WorldPos.Y,
s_thing->WorldPos.Z,0,0,0);
#endif
//
// Don't need the special any more.
//
free_special(s_thing);
}
}
}
break;
case SPECIAL_EXPLOSIVES:
if (s_thing->SubState == SPECIAL_SUBSTATE_ACTIVATED)
{
SLONG tickdown = 0x10 * TICK_RATIO >> TICK_SHIFT;
//
// Time to explode?
//
if (s_thing->Genus.Special->timer <= tickdown)
{
//
// Bang!
//
#ifndef PSX
PYRO_construct(
s_thing->WorldPos,
1|4|8|64,
0xa0);
#else
POW_create(
POW_CREATE_LARGE_SEMI,
s_thing->WorldPos.X,
s_thing->WorldPos.Y,
s_thing->WorldPos.Z,0,0,0);
PYRO_construct(
s_thing->WorldPos,PYRO_DUSTWAVE,0xa0);
#endif
MFX_play_xyz(THING_NUMBER(s_thing),SOUND_Range(S_EXPLODE_MEDIUM,S_EXPLODE_BIG),0,s_thing->WorldPos.X,s_thing->WorldPos.Y,s_thing->WorldPos.Z);
{
SLONG cx,cz;
cx=s_thing->WorldPos.X>>8;
cz=s_thing->WorldPos.Z>>8;
DIRT_gust(s_thing,cx,cz,cx+0xa0,cz);
DIRT_gust(s_thing,cx+0xa0,cz,cx,cz);
}
create_shockwave(
s_thing->WorldPos.X >> 8,
s_thing->WorldPos.Y >> 8,
s_thing->WorldPos.Z >> 8,
0x500,
500,
TO_THING(s_thing->Genus.Special->OwnerThing));
//
// This is the end of the explosives.
//
free_special(s_thing);
}
else
{
s_thing->Genus.Special->timer -= tickdown;
}
}
else
{
if(!s_thing->Genus.Special->OwnerThing )
{
//
// not being carried round may as well see if anyone wants to pick me up
//
goto try_pickup; //I love goto
}
}
break;
case SPECIAL_MINE:
if (s_thing->Genus.Special->ammo > 0)
{
//
// This special has a counter ticking down to explode.
//
if (s_thing->Genus.Special->ammo == 1)
{
special_activate_mine(s_thing);
}
else
{
s_thing->Genus.Special->ammo -= 1;
}
}
else
if ((GAME_TURN&1) == (THING_NUMBER(s_thing)&1))
{
SLONG i;
SLONG j;
SLONG wx;
SLONG wy;
SLONG wz;
SLONG num_found = THING_find_sphere(
s_thing->WorldPos.X >> 8,
s_thing->WorldPos.Y >> 8,
s_thing->WorldPos.Z >> 8,
0x300,
THING_array,
THING_ARRAY_SIZE,
(1 << CLASS_PERSON) | (1 << CLASS_VEHICLE) | (1 << CLASS_BAT));
Thing *p_found;
for (i = 0; i < num_found; i++)
{
p_found = TO_THING(THING_array[i]);
switch(p_found->Class)
{
case CLASS_BAT:
if (p_found->Genus.Bat->type == BAT_TYPE_BALROG)
{
dx = abs(p_found->WorldPos.X - s_thing->WorldPos.X);
dz = abs(p_found->WorldPos.Z - s_thing->WorldPos.Z);
dist = QDIST2(dx,dz);
if (dist < 0x6000)
{
special_activate_mine(s_thing);
return;
}
}
break;
case CLASS_PERSON:
{
Thing *p_person = p_found;
dx = abs(p_person->WorldPos.X - s_thing->WorldPos.X);
dz = abs(p_person->WorldPos.Z - s_thing->WorldPos.Z);
dist = QDIST2(dx,dz);
if (dist < 0x3000)
{
SLONG fx;
SLONG fy;
SLONG fz;
calc_sub_objects_position(
p_person,
p_person->Draw.Tweened->AnimTween,
SUB_OBJECT_LEFT_FOOT,
&fx,
&fy,
&fz);
fx += p_person->WorldPos.X >> 8;
fy += p_person->WorldPos.Y >> 8;
fz += p_person->WorldPos.Z >> 8;
if (fy > (s_thing->WorldPos.Y + 0x2000 >> 8))
{
//
// This person has jumped over the mine!
//
}
else
{
//
// Activate the mine.
//
if (p_person->Genus.Person->pcom_ai== PCOM_AI_BODYGUARD && TO_THING(EWAY_get_person(p_person->Genus.Person->pcom_ai_other))->Genus.Person->PlayerID)
{
//
// players bodyguards dont trigger mines
//
}
else
{
special_activate_mine(s_thing);
return;
}
}
}
}
break;
case CLASS_VEHICLE:
{
SLONG wx;
SLONG wy;
SLONG wz;
Thing *p_vehicle = p_found;
//
// Find out where the wheels are.
//
vehicle_wheel_pos_init(p_vehicle);
for (j = 0; j < 4; j++)
{
vehicle_wheel_pos_get(
j,
&wx,
&wy,
&wz);
dx = abs(wx - (s_thing->WorldPos.X >> 8));
dy = abs(wy - (s_thing->WorldPos.Y >> 8));
dz = abs(wz - (s_thing->WorldPos.Z >> 8));
dist = QDIST3(dx,dy,dz);
if (dist < 0x50)
{
special_activate_mine(s_thing);
return;
}
}
}
break;
default:
ASSERT(0);
break;
}
}
}
break;
case SPECIAL_THERMODROID:
break;
case SPECIAL_TREASURE:
for (i = 0; i < NO_PLAYERS; i++)
{
Thing *darci = NET_PERSON(i);
//
// Has a player picked us up?
//
if (!(darci->Genus.Person->Flags & FLAG_PERSON_DRIVING))
{
dx = darci->WorldPos.X - s_thing->WorldPos.X >> 8;
dy = darci->WorldPos.Y - s_thing->WorldPos.Y >> 8;
dz = darci->WorldPos.Z - s_thing->WorldPos.Z >> 8;
dist = abs(dx) + abs(dy) + abs(dz);
if (dist < 0xa0)
{
SLONG x_message;
//
// Near enough to pick it up.
//
switch(s_thing->Draw.Mesh->ObjectId)
{
case 81:
x_message = X_STA_INCREASED;
add_damage_text(
s_thing->WorldPos.X >> 8,
s_thing->WorldPos.Y + 0x6000 >> 8,
s_thing->WorldPos.Z >> 8,
XLAT_str(X_STA_INCREASED));
NET_PLAYER(0)->Genus.Player->Stamina++;
break;
case 94:
x_message = X_STR_INCREASED;
add_damage_text(
s_thing->WorldPos.X >> 8,
s_thing->WorldPos.Y + 0x6000 >> 8,
s_thing->WorldPos.Z >> 8,
XLAT_str(X_STR_INCREASED));
NET_PLAYER(0)->Genus.Player->Strength++;
break;
case 71:
x_message = X_REF_INCREASED;
add_damage_text(
s_thing->WorldPos.X >> 8,
s_thing->WorldPos.Y + 0x6000 >> 8,
s_thing->WorldPos.Z >> 8,
XLAT_str(X_REF_INCREASED));
NET_PLAYER(0)->Genus.Player->Skill++;
break;
case 39:
x_message = X_CON_INCREASED;
add_damage_text(
s_thing->WorldPos.X >> 8,
s_thing->WorldPos.Y + 0x6000 >> 8,
s_thing->WorldPos.Z >> 8,
XLAT_str(X_CON_INCREASED));
NET_PLAYER(0)->Genus.Player->Constitution++;
break;
default:
ASSERT(0);
break;
}
PANEL_new_info_message(XLAT_str(x_message));
#ifdef PSX
PANEL_icon_time=30;
#endif
// CONSOLE_text(XLAT_str(X_FUSE_SET));
free_special(s_thing);
extern SLONG stat_count_bonus;
stat_count_bonus++;
// NET_PLAYER(i)->Genus.Player->Treasure += 1;
// darci->Genus.Person->Health = health[darci->Genus.Person->PersonType];
/*
{
CBYTE str[64];
sprintf(str, "Badge %d", NET_PLAYER(i)->Genus.Player->Treasure);
CONSOLE_text(str);
}
*/
//
// Reduce crime rate by 10%
//
// CRIME_RATE -= 10;
// SATURATE(CRIME_RATE, 0, 100);
}
}
}
break;
case SPECIAL_HEALTH:
extern SWORD health[];
if(NET_PERSON(0)->Genus.Person->Health>health[NET_PERSON(0)->Genus.Person->PersonType]-100)
{
break;
}
case SPECIAL_GRENADE:
if (s_thing->Genus.Special->SpecialType == SPECIAL_GRENADE &&
s_thing->SubState == SPECIAL_SUBSTATE_ACTIVATED)
{
//
// Don't pickup activated grenades.
//
break;
}
case SPECIAL_AK47:
case SPECIAL_SHOTGUN:
case SPECIAL_GUN:
case SPECIAL_KNIFE:
case SPECIAL_BASEBALLBAT:
case SPECIAL_AMMO_AK47:
case SPECIAL_AMMO_SHOTGUN:
case SPECIAL_AMMO_PISTOL:
default:
try_pickup:;
if (s_thing->Genus.Special->counter > 16 * 20)
{
if (s_thing->Flags & FLAGS_ON_MAPWHO)
{
Thing *darci = NET_PERSON(0);
//
// Has a player picked us up?
//
if (!(darci->Genus.Person->Flags & FLAG_PERSON_DRIVING))
{
dx = darci->WorldPos.X - s_thing->WorldPos.X >> 8;
dy = darci->WorldPos.Y - s_thing->WorldPos.Y >> 8;
dz = darci->WorldPos.Z - s_thing->WorldPos.Z >> 8;
dist = abs(dx) + abs(dy) + abs(dz);
if (dist < 0xa0)
{
if (should_person_get_item(darci, s_thing))
{
person_get_item(darci, s_thing);
}
}
}
}
}
break;
}
}
}
//---------------------------------------------------------------
#ifndef PSX
void init_specials(void)
{
//memset((UBYTE*)SPECIALS,0,sizeof(SPECIALS));
memset((UBYTE*)SPECIALS,0,sizeof(Special) * MAX_SPECIALS);
SPECIAL_COUNT = 0;
}
#endif
//---------------------------------------------------------------
SLONG find_empty_special(void)
{
SLONG c0;
for(c0=1;c0<MAX_SPECIALS;c0++)
{
if(SPECIALS[c0].SpecialType==SPECIAL_NONE)
{
return(c0);
}
}
return NULL;
}
Thing *alloc_special(
UBYTE type,
UBYTE substate,
SLONG world_x,
SLONG world_y,
SLONG world_z,
UWORD waypoint)
{
SLONG c0;
DrawMesh *dm;
Special *new_special;
Thing *special_thing = NULL;
SLONG special_index;
ASSERT(WITHIN(type, 1, SPECIAL_NUM_TYPES - 1));
// Run through the special array & find an unused one.
special_index = find_empty_special();
dm = alloc_draw_mesh();
special_thing = alloc_thing(CLASS_SPECIAL);
if (!special_index || !dm || !special_thing)
{
//
// Oh dear! Dealloc anythings we've got.
//
if (special_index)
{
TO_SPECIAL(special_index)->SpecialType = SPECIAL_NONE;
}
if (dm)
{
free_draw_mesh(dm);
}
if (special_thing)
{
free_thing(special_thing);
}
//
// Find another special and hijack it!
//
SLONG score;
SLONG best_score = -1;
Thing *best_thing = NULL;
SLONG list = thing_class_head[CLASS_SPECIAL];
while(list)
{
Thing *p_hijack = TO_THING(list);
ASSERT(p_hijack->Class == CLASS_SPECIAL);
list = p_hijack->NextLink;
//
// Good special to hijack?
//
score = -1;
if (!(p_hijack->Flags & FLAGS_ON_MAPWHO))
{
continue;
}
if (p_hijack->Genus.Special->OwnerThing)
{
continue;
}
switch(p_hijack->Genus.Special->SpecialType)
{
case SPECIAL_KNIFE:
case SPECIAL_BASEBALLBAT:
score += 4000;
break;
case SPECIAL_AMMO_PISTOL:
case SPECIAL_AMMO_SHOTGUN:
case SPECIAL_AMMO_AK47:
score += 3000;
break;
case SPECIAL_GUN:
case SPECIAL_GRENADE:
case SPECIAL_HEALTH:
case SPECIAL_SHOTGUN:
case SPECIAL_AK47:
score += 2000;
break;
default:
//
// Never hijack one of these...
//
continue;
}
SLONG dx = abs(p_hijack->WorldPos.X - NET_PERSON(0)->WorldPos.X) >> 16;
SLONG dz = abs(p_hijack->WorldPos.Z - NET_PERSON(0)->WorldPos.Z) >> 16;
if (dx + dz > 12)
{
score += dx;
score += dz;
if (score > best_score)
{
best_score = score;
best_thing = p_hijack;
}
}
}
if (best_thing)
{
remove_thing_from_map(best_thing);
special_index = SPECIAL_NUMBER(best_thing->Genus.Special);
special_thing = best_thing;
dm = special_thing->Draw.Mesh;
}
else
{
return NULL;
}
}
new_special = TO_SPECIAL(special_index);
new_special->SpecialType = type;
new_special->Thing = THING_NUMBER(special_thing);
new_special->waypoint = waypoint;
new_special->counter = 0;
new_special->OwnerThing = NULL;
special_thing->Genus.Special = new_special;
special_thing->State = STATE_NORMAL;
special_thing->SubState = substate;
special_thing->StateFn = special_normal;
// Create the visible object.
special_thing->Draw.Mesh = dm;
special_thing->DrawType = DT_MESH;
dm->Angle = 0;
dm->Tilt = 0;
dm->Roll = 0;
switch(type)
{
case SPECIAL_GUN: new_special->ammo = SPECIAL_AMMO_IN_A_PISTOL; break;
case SPECIAL_SHOTGUN: new_special->ammo = SPECIAL_AMMO_IN_A_SHOTGUN; break;
case SPECIAL_AK47: new_special->ammo = SPECIAL_AMMO_IN_A_AK47; break;
case SPECIAL_GRENADE: new_special->ammo = SPECIAL_AMMO_IN_A_GRENADE; break;
case SPECIAL_EXPLOSIVES: new_special->ammo = 1; break;
default:
new_special->ammo = 0;
break;
}
dm->ObjectId = SPECIAL_info[type].prim;
if(dm->ObjectId==PRIM_OBJ_ITEM_TREASURE)
{
switch(Random()&3)
{
case 0:
dm->ObjectId=71;
break;
case 1:
dm->ObjectId=94;
break;
case 2:
dm->ObjectId=81;
break;
case 3:
dm->ObjectId=39;
break;
}
}
special_thing->WorldPos.X = world_x << 8;
special_thing->WorldPos.Y = world_y << 8;
special_thing->WorldPos.Z = world_z << 8;
add_thing_to_map(special_thing);
if (world_y > PAP_calc_map_height_at(world_x, world_z) + 0x50)
{
//
// Make this item start dropping to the ground...
//
special_thing->SubState = SPECIAL_SUBSTATE_PROJECTILE;
special_thing->Genus.Special->timer = 0x8000; // 0x8000 => 0! (Its a UWORD)
}
return special_thing;
}
//---------------------------------------------------------------
void free_special(Thing *special_thing)
{
// Set the special type to none & free the thing.
special_thing->Genus.Special->SpecialType = SPECIAL_NONE;
free_draw_mesh(special_thing->Draw.Mesh);
remove_thing_from_map(special_thing);
free_thing(special_thing);
}
//---------------------------------------------------------------
Thing *person_has_special(Thing *p_person, SLONG special_type)
{
SLONG special;
Thing *p_special;
for (special = p_person->Genus.Person->SpecialList; special; special = p_special->Genus.Special->NextSpecial)
{
p_special = TO_THING(special);
if (p_special->Genus.Special->SpecialType == special_type)
{
return p_special;
}
}
return NULL;
}
void SPECIAL_throw_grenade(Thing *p_special)
{
Thing *p_person = TO_THING(p_special->Genus.Special->OwnerThing);
//
// Convert the grenade to some dirt.
//
if (!CreateGrenadeFromPerson(p_person, p_special->Genus.Special->timer))
{
// no room in grenade array
return;
}
if (p_special->Genus.Special->ammo == 1)
{
//
// Get rid of our special.
//
special_drop(p_special, p_person);
free_special(p_special);
p_person->Genus.Person->SpecialUse = NULL;
}
else
{
p_special->Genus.Special->ammo -= 1;
p_special->SubState = SPECIAL_SUBSTATE_NONE;
}
}
void SPECIAL_prime_grenade(Thing *p_special)
{
p_special->SubState = SPECIAL_SUBSTATE_ACTIVATED;
p_special->Genus.Special->timer = 16 * 20 * 6; // 6 second so self destruct.
}
/*
void SPECIAL_throw_mine(Thing *p_special)
{
UWORD dirt;
UWORD owner;
ASSERT(p_special->Genus.Special->SpecialType == SPECIAL_MINE);
ASSERT(p_special->SubState == SPECIAL_SUBSTATE_ACTIVATED);
ASSERT(p_special->Genus.Special->OwnerThing);
//
// Remember the owner...
//
owner = p_special->Genus.Special->OwnerThing;
//
// Create some dirt that is going to process the physics of the mine
// being thrown through the air.
//
dirt = DIRT_create_mine(TO_THING(p_special->Genus.Special->OwnerThing));
//
// Take it out of the person's special list.
//
special_drop(p_special, TO_THING(p_special->Genus.Special->OwnerThing));
//
// Link the special to the dirt that is going to process its physics.
//
p_special->SubState = SPECIAL_SUBSTATE_IS_DIRT;
p_special->Genus.Special->waypoint = dirt;
p_special->Genus.Special->OwnerThing = owner; // So we know who to blame for the explosion.
}
*/
void SPECIAL_set_explosives(Thing *p_person)
{
Thing *p_special;
p_special = person_has_special(p_person, SPECIAL_EXPLOSIVES);
ASSERT(p_special->Genus.Special->SpecialType == SPECIAL_EXPLOSIVES);
if (p_special)
{
if (p_special->Genus.Special->ammo == 1)
{
//
// Drop the special.
//
p_special->WorldPos = p_person->WorldPos;
special_drop(p_special, p_person);
if (p_person->Genus.Person->SpecialUse == THING_NUMBER(p_special))
{
p_person->Genus.Person->SpecialUse = NULL;
}
}
else
{
p_special->Genus.Special->ammo -= 1;
//
// Create a new explosives special...
//
p_special = alloc_special(
SPECIAL_EXPLOSIVES,
SPECIAL_SUBSTATE_NONE,
p_person->WorldPos.X >> 8,
p_person->WorldPos.Y >> 8,
p_person->WorldPos.Z >> 8,
NULL);
}
//
// Prime it!
//
p_special->SubState = SPECIAL_SUBSTATE_ACTIVATED;
p_special->Genus.Special->timer = 16 * 20 * 5; // 10 seconds so self destruct.
p_special->Genus.Special->OwnerThing = THING_NUMBER(p_person); // So we know who is responsible for the explosion.
//CONSOLE_text("Five second fuse set...");
/*
add_damage_text(
p_special->WorldPos.X >> 8,
p_special->WorldPos.Y + 0x2000 >> 8,
p_special->WorldPos.Z >> 8,
XLAT_str(X_FUSE_SET));
*/
PANEL_new_info_message(XLAT_str(X_FUSE_SET));
}
}
| 21.403471 | 164 | 0.615182 | [
"mesh",
"object"
] |
731742d5408b4b11b3eae5b509f359bf3035752a | 4,181 | cpp | C++ | evaluation/measurements/source/metrics/RelativeParentChange.cpp | varg-dev/treemap-hub | 75d4d2ced3fdf0a73ea1c6b079c70557882ac3b0 | [
"MIT"
] | 1 | 2021-04-15T09:27:23.000Z | 2021-04-15T09:27:23.000Z | evaluation/measurements/source/metrics/RelativeParentChange.cpp | varg-dev/treemap-hub | 75d4d2ced3fdf0a73ea1c6b079c70557882ac3b0 | [
"MIT"
] | 1 | 2021-07-28T14:54:39.000Z | 2021-07-28T14:54:39.000Z | evaluation/measurements/source/metrics/RelativeParentChange.cpp | varg-dev/treemap-hub | 75d4d2ced3fdf0a73ea1c6b079c70557882ac3b0 | [
"MIT"
] | null | null | null |
#include <measurements/metrics/RelativeParentChange.h>
#include <glm/geometric.hpp>
#include <glm/common.hpp>
#include <glm/gtc/constants.hpp>
#include <treemap/layout/Rect.h>
RelativeParentChange::RelativeParentChange()
{
}
float RelativeParentChange::compute(const std::vector<LinearizedTree *> & trees, const std::vector<LinearizedBuffer<Rect>> & layouts, std::uint32_t maxId,
const std::vector<LinearizedBuffer<std::uint32_t>> & index2ids, const std::vector<std::unordered_map<std::uint32_t, std::uint32_t>> & nodeIndexByIds)
{
return computeAverage(trees, layouts, maxId, index2ids, nodeIndexByIds);
}
float RelativeParentChange::computeAverage(const std::vector<LinearizedTree *> & trees, const std::vector<LinearizedBuffer<Rect>> & layouts, std::uint32_t maxId,
const std::vector<LinearizedBuffer<std::uint32_t>> & index2ids, const std::vector<std::unordered_map<std::uint32_t, std::uint32_t>> & nodeIndexByIds)
{
if (trees.size() < 2)
{
return 0.0f;
}
auto result = 0.0f;
for (auto i = 1ull; i < trees.size(); ++i)
{
std::vector<std::uint32_t> occuringInBothRevisions;
const auto currentTree = trees[i];
const auto & currentIDs = index2ids[i];
const auto prevTree = trees[i-1];
const auto & prevNodeIndicesById = nodeIndexByIds[i-1];
for (size_t j = 0; j < currentTree->size(); j++)
{
const auto node = currentTree->at(j);
const auto currentId = currentIDs.at(node);
const auto & layoutElement = layouts[i][node];
if (layoutElement.area() >= glm::epsilon<float>())
{
const auto it = prevNodeIndicesById.find(currentId);
if (it != prevNodeIndicesById.end())
{
const auto compNode = prevTree->at(it->second);
if (compNode != nullptr)
{
const auto & layoutElementComp = layouts[i-1][compNode];
if (layoutElementComp.area() >= glm::epsilon<float>())
{
occuringInBothRevisions.push_back(currentId);
}
}
}
}
}
result += relativeParentChange(prevTree, nodeIndexByIds[i-1], layouts[i-1], currentTree, nodeIndexByIds[i], layouts[i], occuringInBothRevisions);
}
return result / (trees.size() - 1);
}
float RelativeParentChange::relativeParentChange(const LinearizedTree * tree, const std::unordered_map<std::uint32_t, std::uint32_t> & nodeIndexById, const LinearizedBuffer<Rect> & layout, const LinearizedTree * treeComp, const std::unordered_map<std::uint32_t, std::uint32_t> & nodeIndexByIdComp, const LinearizedBuffer<Rect> & layoutComp, const std::vector<std::uint32_t> & occuringInBothRevisions)
{
auto numberOfNodes = occuringInBothRevisions.size();
if (numberOfNodes < 2) // At least one leaf + root required
{
return 0.0f;
}
auto summedRelativeParentChange = 0.0f;
for (const auto & id : occuringInBothRevisions)
{
if (id == 0)
{
--numberOfNodes;
continue;
}
const auto node = tree->at(nodeIndexById.at(id));
const auto parent = tree->at(node->parent());
const auto nodeComp = treeComp->at(nodeIndexByIdComp.at(id));
const auto parentComp = treeComp->at(nodeComp->parent());
const auto & rect = layout.at(node);
const auto & parentRect = layout.at(parent);
const auto & rectComp = layoutComp.at(nodeComp);
const auto & parentRectComp = layoutComp.at(parentComp);
// Compute relative parent distance (rpd)
const auto rpd = glm::distance(parentRect.center(), rect.center()) / (glm::length(glm::vec2(parentRect.extent)) / 2.0f);
const auto rpdComp = glm::distance(parentRectComp.center(), rectComp.center()) / (glm::length(glm::vec2(parentRectComp.extent)) / 2.0f);
summedRelativeParentChange += glm::abs(rpd - rpdComp);
}
return summedRelativeParentChange / numberOfNodes;
}
| 36.356522 | 400 | 0.621622 | [
"vector"
] |
731930b49a8b868f67838d1c6d9da0c86cb1b2f5 | 1,146 | cpp | C++ | grooking_patterns_cpp/dp_probs/word_break.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | 1 | 2021-09-19T16:41:58.000Z | 2021-09-19T16:41:58.000Z | grooking_patterns_cpp/dp_probs/word_break.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | grooking_patterns_cpp/dp_probs/word_break.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
unordered_set<string> uset = { "mobile", "samsung", "sam", "sung", "man",
"mango", "icecream", "and", "go", "i",
"like", "ice", "cream" };
inline bool dictionaryContains(string word){
return uset.count(word);
}
bool wordBreak(string s){
int n = s.size();
if (n == 0)
return true;
vector<int> matched_index;
matched_index.push_back(-1);
for (int i = 0; i < n; i++) {
int msize = matched_index.size();
for (int j = msize - 1; j >= 0; j--) {
string sb = s.substr(matched_index[j] + 1, i - matched_index[j]);
if (dictionaryContains(sb)) {
matched_index.push_back(i);
break;
}
}
}
return matched_index.back()==(n-1);
}
int main(){
wordBreak("ilikesamsung") ? cout << "Yes\n"
: cout << "No\n";
wordBreak("iiiiiiii") ? cout << "Yes\n"
: cout << "No\n";
wordBreak("") ? cout << "Yes\n" : cout << "No\n";
wordBreak("ilikelikeimangoiii") ? cout << "Yes\n"
: cout << "No\n";
wordBreak("samsungandmango") ? cout << "Yes\n"
: cout << "No\n";
wordBreak("samsungandmangok") ? cout << "Yes\n"
: cout << "No\n";
return 0;
} | 23.875 | 73 | 0.570681 | [
"vector"
] |
731d74c3d30a38b63a281d2aa8ea7e01792af9f4 | 51,276 | cpp | C++ | src/Etterna/Singletons/GameManager.cpp | kangalioo/etterna | 11630aa1c23bad46b2da993602b06f8b659a4961 | [
"MIT"
] | 1 | 2020-11-09T21:58:28.000Z | 2020-11-09T21:58:28.000Z | src/Etterna/Singletons/GameManager.cpp | kangalioo/etterna | 11630aa1c23bad46b2da993602b06f8b659a4961 | [
"MIT"
] | null | null | null | src/Etterna/Singletons/GameManager.cpp | kangalioo/etterna | 11630aa1c23bad46b2da993602b06f8b659a4961 | [
"MIT"
] | null | null | null | #include "Etterna/Globals/global.h"
#include "Etterna/Models/Misc/Foreach.h"
#include "Etterna/Models/Misc/Game.h"
#include "Etterna/Models/Misc/GameConstantsAndTypes.h"
#include "Etterna/Models/Misc/GameInput.h" // for GameButton constants
#include "Etterna/Globals/GameLoop.h" // for ChangeGame
#include "GameManager.h"
#include "NoteSkinManager.h"
#include "RageUtil/Misc/RageInputDevice.h"
#include "RageUtil/Utils/RageUtil.h"
#include "Etterna/Models/StepsAndStyles/Style.h"
#include "ThemeManager.h"
GameManager* GAMEMAN =
NULL; // global and accessible from anywhere in our program
enum
{
TRACK_1 = 0,
TRACK_2,
TRACK_3,
TRACK_4,
TRACK_5,
TRACK_6,
TRACK_7,
TRACK_8,
TRACK_9,
TRACK_10,
TRACK_11,
TRACK_12,
TRACK_13,
TRACK_14,
TRACK_15,
TRACK_16,
// 16 tracks needed for beat-double7 and techno-double8
};
RString
StepsTypeInfo::GetLocalizedString() const
{
if (THEME->HasString("StepsType", szName))
return THEME->GetString("StepsType", szName);
return szName;
}
static const StepsTypeInfo g_StepsTypeInfos[] = {
// dance
{ "dance-single", 4, true, StepsTypeCategory_Single },
{ "dance-double", 8, true, StepsTypeCategory_Double },
{ "dance-solo", 6, true, StepsTypeCategory_Single },
{ "dance-threepanel",
3,
true,
StepsTypeCategory_Single }, // thanks to kurisu
// pump
{ "pump-single", 5, true, StepsTypeCategory_Single },
{ "pump-halfdouble", 6, true, StepsTypeCategory_Double },
{ "pump-double", 10, true, StepsTypeCategory_Double },
// kb7
{ "kb7-single", 7, true, StepsTypeCategory_Single },
// { "kb7-small", 7, true, StepsTypeCategory_Single },
// ez2dancer
{ "ez2-single",
5,
true,
StepsTypeCategory_Single }, // Single: TL,LHH,D,RHH,TR
{ "ez2-double", 10, true, StepsTypeCategory_Double }, // Double: Single x2
{ "ez2-real",
7,
true,
StepsTypeCategory_Single }, // Real: TL,LHH,LHL,D,RHL,RHH,TR
// ds3ddx
{ "ds3ddx-single", 8, true, StepsTypeCategory_Single },
// beatmania
{ "bm-single5",
6,
true,
StepsTypeCategory_Single }, // called "bm" for backward compat
{ "bm-double5",
12,
true,
StepsTypeCategory_Double }, // called "bm" for backward compat
{ "bm-single7",
8,
true,
StepsTypeCategory_Single }, // called "bm" for backward compat
{ "bm-double7",
16,
true,
StepsTypeCategory_Double }, // called "bm" for backward compat
// dance maniax
{ "maniax-single", 4, true, StepsTypeCategory_Single },
{ "maniax-double", 8, true, StepsTypeCategory_Double },
// pop'n music
{ "pnm-five",
5,
true,
StepsTypeCategory_Single }, // called "pnm" for backward compat
{ "pnm-nine",
9,
true,
StepsTypeCategory_Single }, // called "pnm" for backward compat
};
// Important: Every game must define the buttons: "Start", "Back", "MenuLeft",
// "Operator" and "MenuRight"
static const AutoMappings g_AutoKeyMappings_Dance = AutoMappings(
"",
"",
"",
AutoMappingEntry(0, KEY_LEFT, GAME_BUTTON_MENULEFT, false),
AutoMappingEntry(0, KEY_RIGHT, GAME_BUTTON_MENURIGHT, false),
AutoMappingEntry(0, KEY_UP, GAME_BUTTON_MENUUP, false),
AutoMappingEntry(0, KEY_DOWN, GAME_BUTTON_MENUDOWN, false),
AutoMappingEntry(0, KEY_Cz, DANCE_BUTTON_LEFT, false),
AutoMappingEntry(0, KEY_PERIOD, DANCE_BUTTON_RIGHT, false),
AutoMappingEntry(0, KEY_COMMA, DANCE_BUTTON_UP, false),
AutoMappingEntry(0, KEY_Cx, DANCE_BUTTON_DOWN, false),
AutoMappingEntry(0, KEY_EQUAL, GAME_BUTTON_EFFECT_UP, false),
AutoMappingEntry(0, KEY_HYPHEN, GAME_BUTTON_EFFECT_DOWN, false),
AutoMappingEntry(0, KEY_ACCENT, GAME_BUTTON_RESTART, false),
AutoMappingEntry(0, KEY_KP_SLASH, GAME_BUTTON_MENULEFT, true),
AutoMappingEntry(0, KEY_KP_ASTERISK, GAME_BUTTON_MENURIGHT, true),
AutoMappingEntry(0, KEY_KP_HYPHEN, GAME_BUTTON_MENUUP, true),
AutoMappingEntry(0, KEY_KP_PLUS, GAME_BUTTON_MENUDOWN, true),
AutoMappingEntry(0, KEY_KP_C4, DANCE_BUTTON_LEFT, true),
AutoMappingEntry(0, KEY_KP_C6, DANCE_BUTTON_RIGHT, true),
AutoMappingEntry(0, KEY_KP_C8, DANCE_BUTTON_UP, true),
AutoMappingEntry(0, KEY_KP_C2, DANCE_BUTTON_DOWN, true),
AutoMappingEntry(0, KEY_KP_C7, DANCE_BUTTON_UPLEFT, true),
AutoMappingEntry(0, KEY_KP_C9, DANCE_BUTTON_UPRIGHT, true));
// xxx: get this from the theme? (see others)
// the problem with getting it from the noteskin is that this is meant to be
// static const; if we switch to anything we likely won't get const anymore
// but i may be talking out of my ass -aj
static const int DANCE_COL_SPACING = 64;
// static ThemeMetric<int> DANCE_COL_SPACING("ColumnSpacing","Dance");
// named after a similar metric in Aldo_MX's build for
// compatibility/familiarity:
// float DANCE_COL_SPACING
// NOTESKIN->GetMetricF("NoteDisplay","ArrowColSpacing");
/* looking for ARROW_SIZE should be enough (ArrowSize)
* just arroweffects.cpp for rowspacing (ArrowRowSpacing)
*/
static const Style g_Style_Dance_Single = {
// STYLE_DANCE_SINGLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
true, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single", // m_szName
StepsType_dance_single, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
4, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -DANCE_COL_SPACING * 1.5f, NULL },
{ TRACK_2, -DANCE_COL_SPACING * 0.5f, NULL },
{ TRACK_3, +DANCE_COL_SPACING * 0.5f, NULL },
{ TRACK_4, +DANCE_COL_SPACING * 1.5f, NULL },
},
{ // m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 3, 2, 1, Style::END_MAPPING },
{ 0, 3, 2, 1, Style::END_MAPPING } },
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3 },
false, // m_bLockDifficulties
};
static const Style g_Style_Dance_Double = {
// STYLE_DANCE_DOUBLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
true, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"double", // m_szName
StepsType_dance_double, // m_StepsType
StyleType_OnePlayerTwoSides, // m_StyleType
8, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -DANCE_COL_SPACING * 3.5f, NULL },
{ TRACK_2, -DANCE_COL_SPACING * 2.5f, NULL },
{ TRACK_3, -DANCE_COL_SPACING * 1.5f, NULL },
{ TRACK_4, -DANCE_COL_SPACING * 0.5f, NULL },
{ TRACK_5, +DANCE_COL_SPACING * 0.5f, NULL },
{ TRACK_6, +DANCE_COL_SPACING * 1.5f, NULL },
{ TRACK_7, +DANCE_COL_SPACING * 2.5f, NULL },
{ TRACK_8, +DANCE_COL_SPACING * 3.5f, NULL },
},
{ // m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 3, 2, 1, Style::END_MAPPING },
{ 4, 7, 6, 5, Style::END_MAPPING } },
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6,
7 },
false, // m_bLockDifficulties
};
static const Style g_Style_Dance_Solo = {
// STYLE_DANCE_SOLO
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"solo", // m_szName
StepsType_dance_solo, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
6, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -DANCE_COL_SPACING * 2.5f, NULL },
{ TRACK_2, -DANCE_COL_SPACING * 1.5f, NULL },
{ TRACK_3, -DANCE_COL_SPACING * 0.5f, NULL },
{ TRACK_4, +DANCE_COL_SPACING * 0.5f, NULL },
{ TRACK_5, +DANCE_COL_SPACING * 1.5f, NULL },
{ TRACK_6, +DANCE_COL_SPACING * 2.5f, NULL },
},
{ // m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 5, 3, 2, 1, 4, Style::END_MAPPING },
{ 0, 5, 3, 2, 1, 4, Style::END_MAPPING } },
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5 },
false, // m_bLockDifficulties
};
static const Style g_Style_Dance_ThreePanel = {
// STYLE_DANCE_THREEPANEL
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"threepanel", // m_szName
StepsType_dance_threepanel, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
3, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -DANCE_COL_SPACING * 1.0f, NULL },
{ TRACK_2, +DANCE_COL_SPACING * 0.0f, NULL },
{ TRACK_3, +DANCE_COL_SPACING * 1.0f, NULL },
},
{ // m_iInputColumn[NUM_GameController][NUM_GameButton]
// 4 3 5
{ 0, 2, Style::NO_MAPPING, 1, 0, 2, Style::END_MAPPING },
{ 0, 2, Style::NO_MAPPING, 1, 0, 2, Style::END_MAPPING } },
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2 },
false, // m_bLockDifficulties
};
static const Style* g_apGame_Dance_Styles[] = { &g_Style_Dance_Single,
&g_Style_Dance_Double,
&g_Style_Dance_Solo,
&g_Style_Dance_ThreePanel,
NULL };
static const Game g_Game_Dance = {
"dance", // m_szName
g_apGame_Dance_Styles, // m_apStyles
false, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"dance", // m_szName
NUM_DANCE_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "Left", GAME_BUTTON_LEFT },
{ "Right", GAME_BUTTON_RIGHT },
{ "Up", GAME_BUTTON_UP },
{ "Down", GAME_BUTTON_DOWN },
{ "UpLeft", GameButton_Invalid },
{ "UpRight", GameButton_Invalid },
},
&g_AutoKeyMappings_Dance },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W1, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W3, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_W5, // m_mapW5To
};
static const AutoMappings g_AutoKeyMappings_Pump = AutoMappings(
"",
"",
"",
AutoMappingEntry(0, KEY_Cq, PUMP_BUTTON_UPLEFT, false),
AutoMappingEntry(0, KEY_Ce, PUMP_BUTTON_UPRIGHT, false),
AutoMappingEntry(0, KEY_Cs, PUMP_BUTTON_CENTER, false),
AutoMappingEntry(0, KEY_Cz, PUMP_BUTTON_DOWNLEFT, false),
AutoMappingEntry(0, KEY_Cc, PUMP_BUTTON_DOWNRIGHT, false),
/*AutoMappingEntry( 0, KEY_KP_C7, PUMP_BUTTON_UPLEFT, true ),
AutoMappingEntry( 0, KEY_KP_C9, PUMP_BUTTON_UPRIGHT, true ),
AutoMappingEntry( 0, KEY_KP_C5, PUMP_BUTTON_CENTER, true ),
AutoMappingEntry( 0, KEY_KP_C1, PUMP_BUTTON_DOWNLEFT, true ),
AutoMappingEntry( 0, KEY_KP_C3, PUMP_BUTTON_DOWNRIGHT, true ),*/
// unmap confusing default MenuButtons
AutoMappingEntry(0, KEY_KP_C8, GameButton_Invalid, false),
AutoMappingEntry(0, KEY_KP_C2, GameButton_Invalid, false),
AutoMappingEntry(0, KEY_KP_C4, GameButton_Invalid, false),
AutoMappingEntry(0, KEY_KP_C6, GameButton_Invalid, false));
// PIU Defaults: RowSpacing = 60; ColSpacing = 52; ArrowSize = 54;
// apparently column spacing is 48px
// static ThemeMetric<int> PUMP_COL_SPACING ("ColumnSpacing","Pump");
static const int PUMP_COL_SPACING = 48;
static const Style g_Style_Pump_Single = {
// STYLE_PUMP_SINGLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single", // m_szName
StepsType_pump_single, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
5, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -PUMP_COL_SPACING * 2.0f, NULL },
{ TRACK_2, -PUMP_COL_SPACING * 1.0f, NULL },
{ TRACK_3, +PUMP_COL_SPACING * 0.0f, NULL },
{ TRACK_4, +PUMP_COL_SPACING * 1.0f, NULL },
{ TRACK_5, +PUMP_COL_SPACING * 2.0f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 1, 3, 2, 0, 4, Style::END_MAPPING },
{ 1, 3, 2, 0, 4, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
2,
1,
3,
0,
4 },
false, // m_bLockDifficulties
};
static const Style g_Style_Pump_HalfDouble = {
// STYLE_PUMP_HALFDOUBLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"halfdouble", // m_szName
StepsType_pump_halfdouble, // m_StepsType
StyleType_OnePlayerTwoSides, // m_StyleType
6, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -PUMP_COL_SPACING * 2.5f - 4, NULL },
{ TRACK_2, -PUMP_COL_SPACING * 1.5f - 4, NULL },
{ TRACK_3, -PUMP_COL_SPACING * 0.5f - 4, NULL },
{ TRACK_4, +PUMP_COL_SPACING * 0.5f + 4, NULL },
{ TRACK_5, +PUMP_COL_SPACING * 1.5f + 4, NULL },
{ TRACK_6, +PUMP_COL_SPACING * 2.5f + 4, NULL },
},
{ // m_iInputColumn[NUM_GameController][NUM_GameButton]
{ Style::NO_MAPPING, 1, 0, Style::NO_MAPPING, 2, Style::END_MAPPING },
{ 4, Style::NO_MAPPING, 5, 3, Style::NO_MAPPING, Style::END_MAPPING } },
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
2,
3,
1,
4,
0,
5 },
false, // m_bLockDifficulties
};
static const Style g_Style_Pump_Double = {
// STYLE_PUMP_DOUBLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"double", // m_szName
StepsType_pump_double, // m_StepsType
StyleType_OnePlayerTwoSides, // m_StyleType
10, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -PUMP_COL_SPACING * 4.5f - 4, NULL },
{ TRACK_2, -PUMP_COL_SPACING * 3.5f - 4, NULL },
{ TRACK_3, -PUMP_COL_SPACING * 2.5f - 4, NULL },
{ TRACK_4, -PUMP_COL_SPACING * 1.5f - 4, NULL },
{ TRACK_5, -PUMP_COL_SPACING * 0.5f - 4, NULL },
{ TRACK_6, +PUMP_COL_SPACING * 0.5f + 4, NULL },
{ TRACK_7, +PUMP_COL_SPACING * 1.5f + 4, NULL },
{ TRACK_8, +PUMP_COL_SPACING * 2.5f + 4, NULL },
{ TRACK_9, +PUMP_COL_SPACING * 3.5f + 4, NULL },
{ TRACK_10, +PUMP_COL_SPACING * 4.5f + 4, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 1, 3, 2, 0, 4, Style::END_MAPPING },
{ 6, 8, 7, 5, 9, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
2,
1,
3,
0,
4,
2 + 5,
1 + 5,
3 + 5,
0 + 5,
4 + 5 },
false, // m_bLockDifficulties
};
static const Style* g_apGame_Pump_Styles[] = { &g_Style_Pump_Single,
&g_Style_Pump_HalfDouble,
&g_Style_Pump_Double,
NULL };
static const Game g_Game_Pump = {
"pump", // m_szName
g_apGame_Pump_Styles, // m_apStyles
false, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"pump", // m_szName
NUM_PUMP_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "UpLeft", GAME_BUTTON_UP },
{ "UpRight", GAME_BUTTON_DOWN },
{ "Center", GAME_BUTTON_START },
{ "DownLeft", GAME_BUTTON_LEFT },
{ "DownRight", GAME_BUTTON_RIGHT },
},
&g_AutoKeyMappings_Pump },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W1, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W3, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_W5, // m_mapW5To
};
static const AutoMappings g_AutoKeyMappings_KB7 =
AutoMappings("",
"",
"",
AutoMappingEntry(0, KEY_Cs, KB7_BUTTON_KEY1, false),
AutoMappingEntry(0, KEY_Cd, KB7_BUTTON_KEY2, false),
AutoMappingEntry(0, KEY_Cf, KB7_BUTTON_KEY3, false),
AutoMappingEntry(0, KEY_SPACE, KB7_BUTTON_KEY4, false),
AutoMappingEntry(0, KEY_Cj, KB7_BUTTON_KEY5, false),
AutoMappingEntry(0, KEY_Ck, KB7_BUTTON_KEY6, false),
AutoMappingEntry(0, KEY_Cl, KB7_BUTTON_KEY7, false));
// ThemeMetric<int> KB7_COL_SPACING ("ColumnSpacing","KB7");
static const int KB7_COL_SPACING = 64;
static const Style g_Style_KB7_Single = {
// STYLE_KB7_SINGLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single", // m_szName
StepsType_kb7_single, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
7, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -KB7_COL_SPACING * 3.0f, NULL },
{ TRACK_2, -KB7_COL_SPACING * 2.0f, NULL },
{ TRACK_3, -KB7_COL_SPACING * 1.0f, NULL },
{ TRACK_4, +KB7_COL_SPACING * 0.0f, NULL },
{ TRACK_5, +KB7_COL_SPACING * 1.0f, NULL },
{ TRACK_6, +KB7_COL_SPACING * 2.0f, NULL },
{ TRACK_7, +KB7_COL_SPACING * 3.0f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 1, 2, 3, 4, 5, 6, Style::END_MAPPING },
{ 0, 1, 2, 3, 4, 5, 6, Style::END_MAPPING },
},
{
// m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6 // doesn't work?
},
false, // m_bLockDifficulties
};
static const Style* g_apGame_KB7_Styles[] = { &g_Style_KB7_Single, NULL };
static const Game g_Game_KB7 = {
"kb7", // m_szName
g_apGame_KB7_Styles, // m_apStyles
true, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"kb7", // m_szName
NUM_KB7_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "Key1", GameButton_Invalid },
{ "Key2", GAME_BUTTON_LEFT },
{ "Key3", GAME_BUTTON_DOWN },
{ "Key4", GameButton_Invalid },
{ "Key5", GAME_BUTTON_UP },
{ "Key6", GAME_BUTTON_RIGHT },
{ "Key7", GameButton_Invalid },
},
&g_AutoKeyMappings_KB7 },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W1, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W3, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_W5, // m_mapW5To
};
// ThemeMetric<int> EZ2_COL_SPACING ("ColumnSpacing","EZ2");
static const int EZ2_COL_SPACING = 46;
// do you even need this if they're the same now -aj
// ThemeMetric<int> EZ2__REAL_COL_SPACING ("ColumnSpacing","EZ2Real");
static const int EZ2_REAL_COL_SPACING = 46;
static const Style g_Style_Ez2_Single = {
// STYLE_EZ2_SINGLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single", // m_szName
StepsType_ez2_single, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
5, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -EZ2_COL_SPACING * 2.0f, NULL },
{ TRACK_2, -EZ2_COL_SPACING * 1.0f, NULL },
{ TRACK_3, +EZ2_COL_SPACING * 0.0f, NULL },
{ TRACK_4, +EZ2_COL_SPACING * 1.0f, NULL },
{ TRACK_5, +EZ2_COL_SPACING * 2.0f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 4, 2, 1, 3, Style::END_MAPPING },
{ 0, 4, 2, 1, 3, Style::END_MAPPING },
},
{
// m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
2,
0,
4,
1,
3 // This should be from back to front: Down, UpLeft, UpRight, Upper Left
// Hand, Upper Right Hand
},
false, // m_bLockDifficulties
};
static const Style g_Style_Ez2_Real = {
// STYLE_EZ2_REAL
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"real", // m_szName
StepsType_ez2_real, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
7, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -EZ2_REAL_COL_SPACING * 2.3f, NULL },
{ TRACK_2, -EZ2_REAL_COL_SPACING * 1.6f, NULL },
{ TRACK_3, -EZ2_REAL_COL_SPACING * 0.9f, NULL },
{ TRACK_4, +EZ2_REAL_COL_SPACING * 0.0f, NULL },
{ TRACK_5, +EZ2_REAL_COL_SPACING * 0.9f, NULL },
{ TRACK_6, +EZ2_REAL_COL_SPACING * 1.6f, NULL },
{ TRACK_7, +EZ2_REAL_COL_SPACING * 2.3f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 6, 3, 2, 4, 1, 5, Style::END_MAPPING },
{ 0, 6, 3, 2, 4, 1, 5, Style::END_MAPPING },
},
{
// m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
3,
0,
6,
1,
5,
2,
4 // This should be from back to front: Down, UpLeft, UpRight, Lower Left
// Hand, Lower Right Hand, Upper Left Hand, Upper Right Hand
},
false, // m_bLockDifficulties
};
static const Style g_Style_Ez2_Double = {
// STYLE_EZ2_DOUBLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"double", // m_szName
StepsType_ez2_double, // m_StepsType
StyleType_OnePlayerTwoSides, // m_StyleType
10, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -EZ2_COL_SPACING * 4.5f, NULL },
{ TRACK_2, -EZ2_COL_SPACING * 3.5f, NULL },
{ TRACK_3, -EZ2_COL_SPACING * 2.5f, NULL },
{ TRACK_4, -EZ2_COL_SPACING * 1.5f, NULL },
{ TRACK_5, -EZ2_COL_SPACING * 0.5f, NULL },
{ TRACK_6, +EZ2_COL_SPACING * 0.5f, NULL },
{ TRACK_7, +EZ2_COL_SPACING * 1.5f, NULL },
{ TRACK_8, +EZ2_COL_SPACING * 2.5f, NULL },
{ TRACK_9, +EZ2_COL_SPACING * 3.5f, NULL },
{ TRACK_10, +EZ2_COL_SPACING * 4.5f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 4, 2, 1, 3, Style::END_MAPPING },
{ 5, 9, 7, 6, 8, Style::END_MAPPING },
},
{
// m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
2,
0,
4,
1,
3,
7,
5,
9,
6,
8 // This should be from back to front: Down, UpLeft, UpRight, Upper Left
// Hand, Upper Right Hand
},
false, // m_bLockDifficulties
};
static const Style* g_apGame_Ez2_Styles[] = { &g_Style_Ez2_Single,
&g_Style_Ez2_Real,
&g_Style_Ez2_Double,
NULL };
static const AutoMappings g_AutoKeyMappings_Ez2 =
AutoMappings("",
"",
"",
AutoMappingEntry(0, KEY_Cz, EZ2_BUTTON_FOOTUPLEFT, false),
AutoMappingEntry(0, KEY_Cb, EZ2_BUTTON_FOOTUPRIGHT, false),
AutoMappingEntry(0, KEY_Cc, EZ2_BUTTON_FOOTDOWN, false),
AutoMappingEntry(0, KEY_Cx, EZ2_BUTTON_HANDUPLEFT, false),
AutoMappingEntry(0, KEY_Cv, EZ2_BUTTON_HANDUPRIGHT, false),
AutoMappingEntry(0, KEY_Cs, EZ2_BUTTON_HANDLRLEFT, false),
AutoMappingEntry(0, KEY_Cf, EZ2_BUTTON_HANDLRRIGHT, false));
static const Game g_Game_Ez2 = {
"ez2", // m_szName
g_apGame_Ez2_Styles, // m_apStyles
true, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"ez2", // m_szName
NUM_EZ2_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "FootUpLeft", GAME_BUTTON_UP },
{ "FootUpRight", GAME_BUTTON_DOWN },
{ "FootDown", GAME_BUTTON_START },
{ "HandUpLeft", GAME_BUTTON_LEFT },
{ "HandUpRight", GAME_BUTTON_RIGHT },
{ "HandLrLeft", GameButton_Invalid },
{ "HandLrRight", GameButton_Invalid },
},
&g_AutoKeyMappings_Ez2 },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W2, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W2, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_Miss, // m_mapW5To
};
// ThemeMetric<int> DS3DDX_COL_SPACING ("ColumnSpacing","DS3DDX");
static const int DS3DDX_COL_SPACING = 46;
static const Style g_Style_DS3DDX_Single = {
// STYLE_DS3DDX_SINGLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
true, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single", // m_szName
StepsType_ds3ddx_single, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
8, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -DS3DDX_COL_SPACING * 3.0f, NULL },
{ TRACK_2, -DS3DDX_COL_SPACING * 2.0f, NULL },
{ TRACK_3, -DS3DDX_COL_SPACING * 1.0f, NULL },
{ TRACK_4, -DS3DDX_COL_SPACING * 0.0f, NULL },
{ TRACK_5, +DS3DDX_COL_SPACING * 0.0f, NULL },
{ TRACK_6, +DS3DDX_COL_SPACING * 1.0f, NULL },
{ TRACK_7, +DS3DDX_COL_SPACING * 2.0f, NULL },
{ TRACK_8, +DS3DDX_COL_SPACING * 3.0f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 1, 2, 3, 4, 5, 6, 7, Style::END_MAPPING },
{ 0, 1, 2, 3, 4, 5, 6, 7, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6,
7 },
false, // m_bLockDifficulties
};
static const Style* g_apGame_DS3DDX_Styles[] = { &g_Style_DS3DDX_Single, NULL };
static const AutoMappings g_AutoKeyMappings_DS3DDX =
AutoMappings("",
"",
"",
AutoMappingEntry(0, KEY_Ca, DS3DDX_BUTTON_HANDLEFT, false),
AutoMappingEntry(0, KEY_Cz, DS3DDX_BUTTON_FOOTDOWNLEFT, false),
AutoMappingEntry(0, KEY_Cq, DS3DDX_BUTTON_FOOTUPLEFT, false),
AutoMappingEntry(0, KEY_Cw, DS3DDX_BUTTON_HANDUP, false),
AutoMappingEntry(0, KEY_Cx, DS3DDX_BUTTON_HANDDOWN, false),
AutoMappingEntry(0, KEY_Ce, DS3DDX_BUTTON_FOOTUPRIGHT, false),
AutoMappingEntry(0, KEY_Cc, DS3DDX_BUTTON_FOOTDOWNRIGHT, false),
AutoMappingEntry(0, KEY_Cd, DS3DDX_BUTTON_HANDRIGHT, false));
static const Game g_Game_DS3DDX = {
"ds3ddx", // m_szName
g_apGame_DS3DDX_Styles, // m_apStyles
false, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"ds3ddx", // m_szName
NUM_DS3DDX_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "HandLeft", GAME_BUTTON_LEFT },
{ "FootDownLeft", GameButton_Invalid },
{ "FootUpLeft", GameButton_Invalid },
{ "HandUp", GAME_BUTTON_UP },
{ "HandDown", GAME_BUTTON_DOWN },
{ "FootUpRight", GameButton_Invalid },
{ "FootDownRight", GameButton_Invalid },
{ "HandRight", GAME_BUTTON_RIGHT },
},
&g_AutoKeyMappings_DS3DDX },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W1, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W3, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_W5, // m_mapW5To
};
// ThemeMetric<int> BEAT_COL_SPACING ("ColumnSpacing","Beat");
static const int BEAT_COL_SPACING = 34;
static const Style g_Style_Beat_Single5 = {
// STYLE_BEAT_SINGLE5
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
true, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single5", // m_szName
StepsType_beat_single5, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
6, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -BEAT_COL_SPACING * 2.5f, NULL },
{ TRACK_2, -BEAT_COL_SPACING * 1.5f, NULL },
{ TRACK_3, -BEAT_COL_SPACING * 0.5f, NULL },
{ TRACK_4, +BEAT_COL_SPACING * 0.5f, NULL },
{ TRACK_5, +BEAT_COL_SPACING * 1.5f, NULL },
{ TRACK_6, +BEAT_COL_SPACING * 3.0f, "scratch" },
},
{ // m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0,
1,
2,
3,
4,
Style::NO_MAPPING,
Style::NO_MAPPING,
5,
5,
Style::END_MAPPING },
{ 0,
1,
2,
3,
4,
Style::NO_MAPPING,
Style::NO_MAPPING,
5,
5,
Style::END_MAPPING } },
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5 },
false, // m_bLockDifficulties
};
static const Style g_Style_Beat_Double5 = {
// STYLE_BEAT_DOUBLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"double5", // m_szName
StepsType_beat_double5, // m_StepsType
StyleType_OnePlayerTwoSides, // m_StyleType
12, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -BEAT_COL_SPACING * 6.0f, NULL },
{ TRACK_2, -BEAT_COL_SPACING * 5.0f, NULL },
{ TRACK_3, -BEAT_COL_SPACING * 4.0f, NULL },
{ TRACK_4, -BEAT_COL_SPACING * 3.0f, NULL },
{ TRACK_5, -BEAT_COL_SPACING * 2.0f, NULL },
{ TRACK_6, -BEAT_COL_SPACING * 1.5f, "scratch" },
{ TRACK_7, +BEAT_COL_SPACING * 0.5f, NULL },
{ TRACK_8, +BEAT_COL_SPACING * 1.5f, NULL },
{ TRACK_9, +BEAT_COL_SPACING * 2.5f, NULL },
{ TRACK_10, +BEAT_COL_SPACING * 3.5f, NULL },
{ TRACK_11, +BEAT_COL_SPACING * 4.5f, NULL },
{ TRACK_12, +BEAT_COL_SPACING * 6.0f, "scratch" },
},
{ // m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0,
1,
2,
3,
4,
Style::NO_MAPPING,
Style::NO_MAPPING,
5,
5,
Style::END_MAPPING },
{ 6,
7,
8,
9,
10,
Style::NO_MAPPING,
Style::NO_MAPPING,
11,
11,
Style::END_MAPPING } },
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11 },
false, // m_bLockDifficulties
};
static const Style g_Style_Beat_Single7 = {
// STYLE_BEAT_SINGLE7
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
true, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single7", // m_szName
StepsType_beat_single7, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
8, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_8, -BEAT_COL_SPACING * 3.5f, "scratch" },
{ TRACK_1, -BEAT_COL_SPACING * 2.0f, NULL },
{ TRACK_2, -BEAT_COL_SPACING * 1.0f, NULL },
{ TRACK_3, -BEAT_COL_SPACING * 0.0f, NULL },
{ TRACK_4, +BEAT_COL_SPACING * 1.0f, NULL },
{ TRACK_5, +BEAT_COL_SPACING * 2.0f, NULL },
{ TRACK_6, +BEAT_COL_SPACING * 3.0f, NULL },
{ TRACK_7, +BEAT_COL_SPACING * 4.0f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 1, 2, 3, 4, 5, 6, 7, 0, 0, Style::END_MAPPING },
{ 1, 2, 3, 4, 5, 6, 7, 0, 0, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6,
7 },
false, // m_bLockDifficulties
};
static const Style g_Style_Beat_Double7 = {
// STYLE_BEAT_DOUBLE7
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"double7", // m_szName
StepsType_beat_double7, // m_StepsType
StyleType_OnePlayerTwoSides, // m_StyleType
16, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_8, -BEAT_COL_SPACING * 8.0f, "scratch" },
{ TRACK_1, -BEAT_COL_SPACING * 6.5f, NULL },
{ TRACK_2, -BEAT_COL_SPACING * 5.5f, NULL },
{ TRACK_3, -BEAT_COL_SPACING * 4.5f, NULL },
{ TRACK_4, -BEAT_COL_SPACING * 3.5f, NULL },
{ TRACK_5, -BEAT_COL_SPACING * 2.5f, NULL },
{ TRACK_6, -BEAT_COL_SPACING * 1.5f, NULL },
{ TRACK_7, -BEAT_COL_SPACING * 0.5f, NULL },
{ TRACK_9, +BEAT_COL_SPACING * 0.5f, NULL },
{ TRACK_10, +BEAT_COL_SPACING * 1.5f, NULL },
{ TRACK_11, +BEAT_COL_SPACING * 2.5f, NULL },
{ TRACK_12, +BEAT_COL_SPACING * 3.5f, NULL },
{ TRACK_13, +BEAT_COL_SPACING * 4.5f, NULL },
{ TRACK_14, +BEAT_COL_SPACING * 5.5f, NULL },
{ TRACK_15, +BEAT_COL_SPACING * 6.5f, NULL },
{ TRACK_16, +BEAT_COL_SPACING * 8.0f, "scratch" },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 1, 2, 3, 4, 5, 6, 7, 0, 0, Style::END_MAPPING },
{ 8, 9, 10, 11, 12, 13, 14, 15, 15, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15 },
false, // m_bLockDifficulties
};
static const Style* g_apGame_Beat_Styles[] = { &g_Style_Beat_Single5,
&g_Style_Beat_Double5,
&g_Style_Beat_Single7,
&g_Style_Beat_Double7,
NULL };
static const AutoMappings g_AutoKeyMappings_Beat =
AutoMappings("",
"",
"",
AutoMappingEntry(0, KEY_Cm, BEAT_BUTTON_KEY1, false),
AutoMappingEntry(0, KEY_Ck, BEAT_BUTTON_KEY2, false),
AutoMappingEntry(0, KEY_COMMA, BEAT_BUTTON_KEY3, false),
AutoMappingEntry(0, KEY_Cl, BEAT_BUTTON_KEY4, false),
AutoMappingEntry(0, KEY_PERIOD, BEAT_BUTTON_KEY5, false),
AutoMappingEntry(0, KEY_SEMICOLON, BEAT_BUTTON_KEY6, false),
AutoMappingEntry(0, KEY_SLASH, BEAT_BUTTON_KEY7, false),
AutoMappingEntry(0, KEY_SPACE, BEAT_BUTTON_SCRATCHUP, false));
static const Game g_Game_Beat = {
"beat", // m_szName
g_apGame_Beat_Styles, // m_apStyles
true, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"beat", // m_szName
NUM_BEAT_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "Key1", GAME_BUTTON_LEFT },
{ "Key2", GameButton_Invalid },
{ "Key3", GameButton_Invalid },
{ "Key4", GameButton_Invalid },
{ "Key5", GameButton_Invalid },
{ "Key6", GameButton_Invalid },
{ "Key7", GAME_BUTTON_RIGHT },
{ "Scratch up", GAME_BUTTON_UP },
{ "Scratch down", GAME_BUTTON_DOWN },
},
&g_AutoKeyMappings_Beat },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W1, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W3, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_W5, // m_mapW5To
};
// ThemeMetric<int> MANIAX_COL_SPACING ("ColumnSpacing","Maniax");
static const int MANIAX_COL_SPACING = 36;
static const Style g_Style_Maniax_Single = {
// STYLE_MANIAX_SINGLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
true, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"single", // m_szName
StepsType_maniax_single, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
4, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -MANIAX_COL_SPACING * 1.5f, NULL },
{ TRACK_2, -MANIAX_COL_SPACING * 0.5f, NULL },
{ TRACK_3, +MANIAX_COL_SPACING * 0.5f, NULL },
{ TRACK_4, +MANIAX_COL_SPACING * 1.5f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 1, 2, 0, 3, Style::END_MAPPING },
{ 1, 2, 0, 3, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3 },
false, // m_bLockDifficulties
};
static const Style g_Style_Maniax_Double = {
// STYLE_MANIAX_DOUBLE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"double", // m_szName
StepsType_maniax_double, // m_StepsType
StyleType_OnePlayerTwoSides, // m_StyleType
8, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -MANIAX_COL_SPACING * 3.5f, NULL },
{ TRACK_2, -MANIAX_COL_SPACING * 2.5f, NULL },
{ TRACK_3, -MANIAX_COL_SPACING * 1.5f, NULL },
{ TRACK_4, -MANIAX_COL_SPACING * 0.5f, NULL },
{ TRACK_5, +MANIAX_COL_SPACING * 0.5f, NULL },
{ TRACK_6, +MANIAX_COL_SPACING * 1.5f, NULL },
{ TRACK_7, +MANIAX_COL_SPACING * 2.5f, NULL },
{ TRACK_8, +MANIAX_COL_SPACING * 3.5f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 1, 2, 0, 3, Style::END_MAPPING },
{ 5, 6, 4, 7, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6,
7 },
false, // m_bLockDifficulties
};
static const Style* g_apGame_Maniax_Styles[] = { &g_Style_Maniax_Single,
&g_Style_Maniax_Double,
NULL };
static const AutoMappings g_AutoKeyMappings_Maniax = AutoMappings(
"",
"",
"",
AutoMappingEntry(0, KEY_Ca, MANIAX_BUTTON_HANDUPLEFT, false),
AutoMappingEntry(0, KEY_Cs, MANIAX_BUTTON_HANDUPRIGHT, false),
AutoMappingEntry(0, KEY_Cz, MANIAX_BUTTON_HANDLRLEFT, false),
AutoMappingEntry(0, KEY_Cx, MANIAX_BUTTON_HANDLRRIGHT, false)
/*AutoMappingEntry( 0, KEY_KP_C4, MANIAX_BUTTON_HANDUPLEFT, true ),
AutoMappingEntry( 0, KEY_KP_C5, MANIAX_BUTTON_HANDUPRIGHT, true ),
AutoMappingEntry( 0, KEY_KP_C1, MANIAX_BUTTON_HANDLRLEFT, true ),
AutoMappingEntry( 0, KEY_KP_C2, MANIAX_BUTTON_HANDLRRIGHT, true )*/
);
static const Game g_Game_Maniax = {
"maniax", // m_szName
g_apGame_Maniax_Styles, // m_apStyles
false, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"maniax", // m_szName
NUM_MANIAX_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "HandUpLeft", GAME_BUTTON_LEFT },
{ "HandUpRight", GAME_BUTTON_RIGHT },
{ "HandLrLeft", GAME_BUTTON_DOWN },
{ "HandLrRight", GAME_BUTTON_UP },
},
&g_AutoKeyMappings_Maniax },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W1, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W3, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_W5, // m_mapW5To
};
/** popn *********************************************************************/
// ThemeMetric<int> POPN5_COL_SPACING ("ColumnSpacing","Popn5");
static const int POPN5_COL_SPACING = 32;
// ThemeMetric<int> POPN9_COL_SPACING ("ColumnSpacing","Popn9");
static const int POPN9_COL_SPACING = 32;
static const Style g_Style_Popn_Five = {
// STYLE_POPN_FIVE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
false, // m_bUsedForDemonstration
false, // m_bUsedForHowToPlay
"popn-five", // m_szName
StepsType_popn_five, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
5, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -POPN5_COL_SPACING * 2.0f, NULL },
{ TRACK_2, -POPN5_COL_SPACING * 1.0f, NULL },
{ TRACK_3, +POPN5_COL_SPACING * 0.0f, NULL },
{ TRACK_4, +POPN5_COL_SPACING * 1.0f, NULL },
{ TRACK_5, +POPN5_COL_SPACING * 2.0f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ Style::NO_MAPPING,
Style::NO_MAPPING,
0,
1,
2,
3,
4,
Style::END_MAPPING },
{ Style::NO_MAPPING,
Style::NO_MAPPING,
0,
1,
2,
3,
4,
Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4 },
false, // m_bLockDifficulties
};
static const Style g_Style_Popn_Nine = {
// STYLE_POPN_NINE
true, // m_bUsedForGameplay
true, // m_bUsedForEdit
true, // m_bUsedForDemonstration
true, // m_bUsedForHowToPlay
"popn-nine", // m_szName
StepsType_popn_nine, // m_StepsType
StyleType_OnePlayerOneSide, // m_StyleType
9, // m_iColsPerPlayer
{
// m_ColumnInfo[MAX_COLS_PER_PLAYER];
// PLAYER_1
{ TRACK_1, -POPN9_COL_SPACING * 4.0f, NULL },
{ TRACK_2, -POPN9_COL_SPACING * 3.0f, NULL },
{ TRACK_3, -POPN9_COL_SPACING * 2.0f, NULL },
{ TRACK_4, -POPN9_COL_SPACING * 1.0f, NULL },
{ TRACK_5, +POPN9_COL_SPACING * 0.0f, NULL },
{ TRACK_6, +POPN9_COL_SPACING * 1.0f, NULL },
{ TRACK_7, +POPN9_COL_SPACING * 2.0f, NULL },
{ TRACK_8, +POPN9_COL_SPACING * 3.0f, NULL },
{ TRACK_9, +POPN9_COL_SPACING * 4.0f, NULL },
},
{
// m_iInputColumn[NUM_GameController][NUM_GameButton]
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Style::END_MAPPING },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Style::END_MAPPING },
},
{ // m_iColumnDrawOrder[MAX_COLS_PER_PLAYER];
0,
1,
2,
3,
4,
5,
6,
7,
8 },
false, // m_bLockDifficulties
};
static const Style* g_apGame_Popn_Styles[] = { &g_Style_Popn_Five,
&g_Style_Popn_Nine,
NULL };
static const AutoMappings g_AutoKeyMappings_Popn =
AutoMappings("",
"",
"",
AutoMappingEntry(0, KEY_Cz, POPN_BUTTON_LEFT_WHITE, false),
AutoMappingEntry(0, KEY_Cs, POPN_BUTTON_LEFT_YELLOW, false),
AutoMappingEntry(0, KEY_Cx, POPN_BUTTON_LEFT_GREEN, false),
AutoMappingEntry(0, KEY_Cd, POPN_BUTTON_LEFT_BLUE, false),
AutoMappingEntry(0, KEY_Cc, POPN_BUTTON_RED, false),
AutoMappingEntry(0, KEY_Cf, POPN_BUTTON_RIGHT_BLUE, false),
AutoMappingEntry(0, KEY_Cv, POPN_BUTTON_RIGHT_GREEN, false),
AutoMappingEntry(0, KEY_Cg, POPN_BUTTON_RIGHT_YELLOW, false),
AutoMappingEntry(0, KEY_Cb, POPN_BUTTON_RIGHT_WHITE, false));
static const Game g_Game_Popn = {
"popn", // m_szName
g_apGame_Popn_Styles, // m_apStyles
true, // m_bCountNotesSeparately
false, // m_bTickHolds
false, // m_PlayersHaveSeparateStyles
{ // m_InputScheme
"popn", // m_szName
NUM_POPN_BUTTONS, // m_iButtonsPerController
{
// m_szButtonNames
{ "Left White", GameButton_Invalid },
{ "Left Yellow", GAME_BUTTON_UP },
{ "Left Green", GameButton_Invalid },
{ "Left Blue", GAME_BUTTON_LEFT },
{ "Red", GAME_BUTTON_START },
{ "Right Blue", GAME_BUTTON_RIGHT },
{ "Right Green", GameButton_Invalid },
{ "Right Yellow", GAME_BUTTON_DOWN },
{ "Right White", GameButton_Invalid },
},
&g_AutoKeyMappings_Popn },
{
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
{ GameButtonType_Step },
},
TNS_W1, // m_mapW1To
TNS_W2, // m_mapW2To
TNS_W3, // m_mapW3To
TNS_W4, // m_mapW4To
TNS_W5, // m_mapW5To
};
static const Game* g_Games[] = {
&g_Game_Dance, &g_Game_Pump, &g_Game_KB7, &g_Game_Ez2,
&g_Game_DS3DDX, &g_Game_Beat, &g_Game_Maniax, &g_Game_Popn,
};
GameManager::GameManager()
{
m_bResetModifiers = false;
m_bResetTurns = false;
m_fPreviousRate = 1.f;
m_sModsToReset;
m_vTurnsToReset;
m_iPreviousFail = FailType_Immediate; // this should never get called without being set with the player's existing
// option but default to avoid crashing due to a malformed enum just in case
m_bRestartedGameplay;
// Register with Lua.
{
Lua* L = LUA->Get();
lua_pushstring(L, "GAMEMAN");
this->PushSelf(L);
lua_settable(L, LUA_GLOBALSINDEX);
LUA->Release(L);
}
}
GameManager::~GameManager()
{
// Unregister with Lua.
LUA->UnsetGlobal("GAMEMAN");
}
void
GameManager::GetStylesForGame(const Game* pGame,
vector<const Style*>& aStylesAddTo,
bool editor)
{
for (int s = 0; pGame->m_apStyles[s] != nullptr; ++s) {
const Style* style = pGame->m_apStyles[s];
if (!editor && !style->m_bUsedForGameplay)
continue;
if (editor && !style->m_bUsedForEdit)
continue;
aStylesAddTo.push_back(style);
}
}
const Game*
GameManager::GetGameForStyle(const Style* pStyle)
{
for (auto pGame : g_Games) {
for (int s = 0; pGame->m_apStyles[s] != nullptr; ++s) {
if (pGame->m_apStyles[s] == pStyle)
return pGame;
}
}
FAIL_M(pStyle->m_szName);
}
const Style*
GameManager::GetEditorStyleForStepsType(StepsType st)
{
for (auto pGame : g_Games) {
for (int s = 0; pGame->m_apStyles[s] != nullptr; ++s) {
const Style* style = pGame->m_apStyles[s];
if (style->m_StepsType == st && style->m_bUsedForEdit)
return style;
}
}
ASSERT_M(
0, ssprintf("The current game cannot use this Style with the editor!"));
return NULL;
}
void
GameManager::GetStepsTypesForGame(const Game* pGame,
vector<StepsType>& aStepsTypeAddTo)
{
for (int i = 0; pGame->m_apStyles[i] != nullptr; ++i) {
StepsType st = pGame->m_apStyles[i]->m_StepsType;
ASSERT(st < NUM_StepsType);
// Some Styles use the same StepsType (e.g. single and versus) so check
// that we aren't doubling up.
bool found = false;
for (unsigned j = 0; j < aStepsTypeAddTo.size(); j++)
if (st == aStepsTypeAddTo[j]) {
found = true;
break;
}
if (found)
continue;
aStepsTypeAddTo.push_back(st);
}
}
void
GameManager::GetDemonstrationStylesForGame(const Game* pGame,
vector<const Style*>& vpStylesOut)
{
vpStylesOut.clear();
for (int s = 0; pGame->m_apStyles[s] != nullptr; ++s) {
const Style* style = pGame->m_apStyles[s];
if (style->m_bUsedForDemonstration)
vpStylesOut.push_back(style);
}
ASSERT(vpStylesOut.size() > 0); // this Game is missing a Style that can be
// used with the demonstration
}
const Style*
GameManager::GetHowToPlayStyleForGame(const Game* pGame)
{
for (int s = 0; pGame->m_apStyles[s] != nullptr; ++s) {
const Style* style = pGame->m_apStyles[s];
if (style->m_bUsedForHowToPlay)
return style;
}
FAIL_M(ssprintf("Game has no Style that can be used with HowToPlay: %s",
pGame->m_szName));
}
void
GameManager::GetCompatibleStyles(const Game* pGame,
int iNumPlayers,
vector<const Style*>& vpStylesOut)
{
FOREACH_ENUM(StyleType, styleType)
{
int iNumPlayersRequired;
switch (styleType) {
DEFAULT_FAIL(styleType);
case StyleType_OnePlayerOneSide:
case StyleType_OnePlayerTwoSides:
iNumPlayersRequired = 1;
break;
}
if (iNumPlayers != iNumPlayersRequired)
continue;
for (int s = 0; pGame->m_apStyles[s] != nullptr; ++s) {
const Style* style = pGame->m_apStyles[s];
if (style->m_StyleType != styleType)
continue;
if (!style->m_bUsedForGameplay)
continue;
vpStylesOut.push_back(style);
}
}
}
const Style*
GameManager::GetFirstCompatibleStyle(const Game* pGame,
int iNumPlayers,
StepsType st)
{
vector<const Style*> vpStyles;
GetCompatibleStyles(pGame, iNumPlayers, vpStyles);
FOREACH_CONST(const Style*, vpStyles, s)
{
if ((*s)->m_StepsType == st) {
return *s;
}
}
return NULL;
}
void
GameManager::GetEnabledGames(vector<const Game*>& aGamesOut)
{
for (size_t g = 0; g < ARRAYLEN(g_Games); ++g) {
const Game* pGame = g_Games[g];
if (IsGameEnabled(pGame))
aGamesOut.push_back(pGame);
}
}
const Game*
GameManager::GetDefaultGame()
{
const Game* pDefault = NULL;
if (pDefault == NULL) {
for (size_t i = 0; pDefault == NULL && i < ARRAYLEN(g_Games); ++i) {
if (IsGameEnabled(g_Games[i]))
pDefault = g_Games[i];
}
if (pDefault == NULL)
RageException::Throw("No NoteSkins found");
}
return pDefault;
}
int
GameManager::GetIndexFromGame(const Game* pGame)
{
for (size_t g = 0; g < ARRAYLEN(g_Games); ++g) {
if (g_Games[g] == pGame)
return g;
}
FAIL_M(ssprintf("Game not found: %s", pGame->m_szName));
}
const Game*
GameManager::GetGameFromIndex(int index)
{
ASSERT(index >= 0);
ASSERT(index < (int)ARRAYLEN(g_Games));
return g_Games[index];
}
bool
GameManager::IsGameEnabled(const Game* pGame)
{
return NOTESKIN->DoNoteSkinsExistForGame(pGame);
}
const StepsTypeInfo&
GameManager::GetStepsTypeInfo(StepsType st)
{
ASSERT(ARRAYLEN(g_StepsTypeInfos) == NUM_StepsType);
ASSERT_M(st < NUM_StepsType,
ssprintf("StepsType %d < NUM_StepsType (%d)", st, NUM_StepsType));
return g_StepsTypeInfos[st];
}
StepsType
GameManager::StringToStepsType(RString sStepsType)
{
sStepsType.MakeLower();
for (int i = 0; i < NUM_StepsType; i++)
if (g_StepsTypeInfos[i].szName == sStepsType)
return StepsType(i);
return StepsType_Invalid;
}
RString
GameManager::StyleToLocalizedString(const Style* style)
{
RString s = style->m_szName;
s = Capitalize(s);
if (THEME->HasString("Style", s))
return THEME->GetString("Style", s);
else
return s;
}
const Game*
GameManager::StringToGame(const RString& sGame)
{
for (size_t i = 0; i < ARRAYLEN(g_Games); ++i)
if (!sGame.CompareNoCase(g_Games[i]->m_szName))
return g_Games[i];
return NULL;
}
const Style*
GameManager::GameAndStringToStyle(const Game* game, const RString& sStyle)
{
for (int s = 0; game->m_apStyles[s]; ++s) {
const Style* style = game->m_apStyles[s];
if (sStyle.CompareNoCase(style->m_szName) == 0)
return style;
}
return NULL;
}
// lua start
#include "Etterna/Models/Lua/LuaBinding.h"
/** @brief Allow Lua to have access to the GameManager. */
class LunaGameManager : public Luna<GameManager>
{
public:
static int StepsTypeToLocalizedString(T* p, lua_State* L)
{
lua_pushstring(L,
p->GetStepsTypeInfo(Enum::Check<StepsType>(L, 1))
.GetLocalizedString());
return 1;
}
static int GetFirstStepsTypeForGame(T* p, lua_State* L)
{
Game* pGame = Luna<Game>::check(L, 1);
vector<StepsType> vstAddTo;
p->GetStepsTypesForGame(pGame, vstAddTo);
ASSERT(!vstAddTo.empty());
StepsType st = vstAddTo[0];
LuaHelpers::Push(L, st);
return 1;
}
static int IsGameEnabled(T* p, lua_State* L)
{
const Game* pGame = p->StringToGame(SArg(1));
if (pGame != nullptr)
lua_pushboolean(L, p->IsGameEnabled(pGame));
else
lua_pushnil(L);
return 1;
}
static int GetStylesForGame(T* p, lua_State* L)
{
RString game_name = SArg(1);
const Game* pGame = p->StringToGame(game_name);
if (pGame == nullptr) {
luaL_error(
L, "GetStylesForGame: Invalid Game: '%s'", game_name.c_str());
}
vector<Style*> aStyles;
lua_createtable(L, 0, 0);
for (int s = 0; pGame->m_apStyles[s] != nullptr; ++s) {
auto* pStyle = const_cast<Style*>(pGame->m_apStyles[s]);
pStyle->PushSelf(L);
lua_rawseti(L, -2, s + 1);
}
return 1;
}
static int GetEnabledGames(T* p, lua_State* L)
{
vector<const Game*> aGames;
p->GetEnabledGames(aGames);
lua_createtable(L, aGames.size(), 0);
for (size_t i = 0; i < aGames.size(); ++i) {
lua_pushstring(L, aGames[i]->m_szName);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
static int SetGame(T* p, lua_State* L)
{
RString game_name = SArg(1);
const Game* pGame = p->StringToGame(game_name);
if (pGame == nullptr) {
luaL_error(L, "SetGame: Invalid Game: '%s'", game_name.c_str());
}
RString theme;
if (lua_gettop(L) >= 2 && !lua_isnil(L, 2)) {
theme = SArg(2);
if (!THEME->IsThemeSelectable(theme)) {
luaL_error(L, "SetGame: Invalid Theme: '%s'", theme.c_str());
}
}
GameLoop::ChangeGame(game_name, theme);
return 0;
}
LunaGameManager()
{
ADD_METHOD(StepsTypeToLocalizedString);
ADD_METHOD(GetFirstStepsTypeForGame);
ADD_METHOD(IsGameEnabled);
ADD_METHOD(GetStylesForGame);
ADD_METHOD(GetEnabledGames);
ADD_METHOD(SetGame);
};
};
LUA_REGISTER_CLASS(GameManager)
// lua end
/*
* (c) 2001-2006 Chris Danford, Glenn Maynard
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 28.065681 | 115 | 0.669514 | [
"vector"
] |
731f78298c7e8ca739d1f2d38a328d9bee237417 | 8,173 | cpp | C++ | muxer_main.cpp | alexander-sholohov/rtlmuxer | cae7fb29f4daa7df0cd74279bf8168e9645a5306 | [
"MIT"
] | 13 | 2016-05-15T08:20:43.000Z | 2021-05-19T12:53:46.000Z | muxer_main.cpp | alexander-sholohov/rtlmuxer | cae7fb29f4daa7df0cd74279bf8168e9645a5306 | [
"MIT"
] | 1 | 2018-11-21T18:19:14.000Z | 2018-11-27T12:02:03.000Z | muxer_main.cpp | alexander-sholohov/rtlmuxer | cae7fb29f4daa7df0cd74279bf8168e9645a5306 | [
"MIT"
] | 5 | 2016-10-14T19:45:56.000Z | 2020-10-04T19:31:31.000Z | //
// Author: Alexander Sholohov <ra9yer@yahoo.com>
//
// License: MIT
//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <signal.h>
#include <string>
#include <vector>
#include <cstring>
#include <errno.h>
#include <getopt.h>
#include "buffer.h"
#include "tcp_sink.h"
#include "sink_list.h"
#include "tcp_source.h"
#define BASIC_BUFFER_SIZE (128*1024)
#define OUT_BUFFER_SIZE (BASIC_BUFFER_SIZE * 16)
#define BACK_BUFFER_SIZE (8192)
//-------------------------------------------------------------------
void close_and_exit(int status)
{
fprintf(stderr, "exit status = %d\n", status);
exit(status);
}
//-------------------------------------------------------------------
int prepareServerSocket(std::string const& addr, int port)
{
struct sockaddr_in local;
int optval, server;
/* Setup server addr & port */
memset(&local,0,sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(port);
local.sin_addr.s_addr = (addr == "0.0.0.0")? INADDR_ANY : inet_addr(addr.c_str());
server = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
if (server == -1) {
perror("socket");
close_and_exit(EXIT_FAILURE);
}
optval = 1;
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int));
setsockopt(server, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(int));
//struct linger ling = {1,0};
//setsockopt(server, SOL_SOCKET, SO_LINGER, (char *)&ling, sizeof(ling));
/* Bind and listen */
if (bind(server, (struct sockaddr *)&local, sizeof(local)))
{
perror("bind");
close_and_exit(EXIT_FAILURE);
}
if (listen(server, 0))
{
perror("listen");
close_and_exit(EXIT_FAILURE);
}
return server;
}
//-------------------------------------------------------------------
void prepareAcceptedSocket(int socket)
{
struct linger ling = {1,0};
setsockopt(socket, SOL_SOCKET, SO_LINGER, (char *)&ling, sizeof(ling));
}
//-------------------------------------------------------------------
void usage(void)
{
printf("rtlmuxer, simple rtl_tcp specific TCP stream splitter\n\n"
"Usage:\t[--src-address= address to connect to (default: 127.0.0.1)]\n"
"\t[--src-port= port to connect to (default: 1234)]\n"
"\t[--sink-bind-address= sink listen address (default: 127.0.0.1)]\n"
"\t[--sink-bind-port-a= sink listen port A (default: 7373)]\n"
"\t[--sink-bind-port-b= sink listen port B (default: 7374)]\n"
"\t[--help this text]\n");
exit(1);
}
//-------------------------------------------------------------------
int main(int argc, char** argv)
{
std::string srcAddress="127.0.0.1";
unsigned srcPort = 1234;
std::string sinkBindAddressA = "127.0.0.1";
unsigned skinkBindPortA = 7373;
std::string sinkBindAddressB = "127.0.0.1";
unsigned skinkBindPortB = 7374;
static struct option long_options[] = {
{"help", 0, 0, 0},
{"src-address", 1, 0, 0},
{"src-port", 1, 0, 0},
{"sink-bind-address", 1, 0, 0},
{"sink-bind-port-a", 1, 0, 0},
{"sink-bind-port-b", 1, 0, 0},
{0, 0, 0, 0}
};
while( true )
{
int option_index = 0;
int c = getopt_long (argc, argv, "", long_options, &option_index);
if( c == -1 )
break;
if( c == 0 )
{
switch( option_index )
{
case 0:
usage();
break;
case 1:
srcAddress = optarg;
break;
case 2:
srcPort = atoi(optarg);
break;
case 3:
sinkBindAddressA = optarg;
sinkBindAddressB = optarg;
break;
case 4:
skinkBindPortA = atoi(optarg);
break;
case 5:
skinkBindPortB = atoi(optarg);
break;
default:
usage();
}
}
}
printf("Using params:\n");
printf("Source connect address: %s:%d\n", srcAddress.c_str(), srcPort);
printf("Sink port A: %s:%d\n", sinkBindAddressA.c_str(), skinkBindPortA);
printf("Sink port B: %s:%d\n", sinkBindAddressB.c_str(), skinkBindPortB);
printf("\n");
fflush(stdout);
// ignore SIGPIPE, SIGHUP
struct sigaction sigign;
sigign.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sigign, NULL);
sigaction(SIGHUP, &sigign, NULL);
int serverSocketA = prepareServerSocket(sinkBindAddressA, skinkBindPortA);
int serverSocketB = prepareServerSocket(sinkBindAddressB, skinkBindPortB);
CSinkList sinkList;
CTcpSource src(BASIC_BUFFER_SIZE, srcAddress, srcPort);
CBuffer backBuffer(BACK_BUFFER_SIZE);
while( true )
{
unsigned numTriesConnect = 1;
while( !src.isConnected() )
{
printf("Try to connect to %s (%d)\n", src.printableAddress().c_str(), numTriesConnect );fflush(stdout);
src.connectSync();
if( src.isConnected() )
{
printf("Source port connected\n");fflush(stdout);
break;
}
numTriesConnect++;
sleep(5);
}
//-
fd_set rd_set;
FD_ZERO(&rd_set);
FD_SET(serverSocketA, &rd_set);
FD_SET(serverSocketB, &rd_set);
FD_SET(src.getSocket(), &rd_set);
sinkList.fillRdSet( rd_set );
//-
fd_set wr_set;
FD_ZERO(&wr_set);
src.fillWrSet( wr_set );
sinkList.fillWrSet( wr_set );
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
int maxFd = 0;
maxFd = src.calcMaxFd( serverSocketA );
maxFd = src.calcMaxFd( serverSocketB );
maxFd = sinkList.calcMaxFd( maxFd );
::select(maxFd+1, &rd_set, &wr_set, NULL, &timeout);
if( FD_ISSET(serverSocketA, &rd_set) )
{
struct sockaddr_in remote;
socklen_t rlen;
int client = ::accept4(serverSocketA, (struct sockaddr *)&remote, &rlen, SOCK_NONBLOCK );
printf("after acceptA %d\n", client);fflush(stdout);
prepareAcceptedSocket(client);
sinkList.addSink(client, OUT_BUFFER_SIZE, true);
if( src.isIdentifierPresent() )
{
printf("identifier sent\n");fflush(stdout);
std::vector<char> identifier;
src.fillIdentifier( identifier );
sinkList.getLastSink().putData( identifier );
}
}
if( FD_ISSET(serverSocketB, &rd_set) )
{
struct sockaddr_in remote;
socklen_t rlen;
int client = ::accept4(serverSocketB, (struct sockaddr *)&remote, &rlen, SOCK_NONBLOCK );
printf("after acceptB %d\n", client);fflush(stdout);
prepareAcceptedSocket(client);
sinkList.addSink(client, OUT_BUFFER_SIZE, false);
// we do not send identifier to port B
}
if( FD_ISSET(src.getSocket(), &wr_set) )
{
src.doWrite();
}
if( FD_ISSET(src.getSocket(), &rd_set) )
{
char buffer[BASIC_BUFFER_SIZE];
unsigned readed = src.doRead(buffer, sizeof(buffer));
if( readed > 0 )
{
sinkList.putData( buffer, readed );
}
}
backBuffer.reset();
sinkList.processRead( rd_set, backBuffer );
sinkList.processWrite( wr_set );
sinkList.cleanupTask();
// we do not expect big data here
if( backBuffer.bytesAvailable() > 0 )
{
size_t len = backBuffer.bytesAvailable();
std::vector<char> tmpBuf(len);
backBuffer.peek( tmpBuf, len );
src.putData( &tmpBuf[0], len );
}
}
return 0;
}
| 27.152824 | 115 | 0.524777 | [
"vector"
] |
7323377eb9782347f3a559177dd2355afeb036c1 | 74,626 | cpp | C++ | toonz/sources/toonz/flipbook.cpp | ongirii/tahoma2d | b6de3199a872c2bbcea37c3b3a728397e23dbaac | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonz/flipbook.cpp | ongirii/tahoma2d | b6de3199a872c2bbcea37c3b3a728397e23dbaac | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonz/flipbook.cpp | ongirii/tahoma2d | b6de3199a872c2bbcea37c3b3a728397e23dbaac | [
"BSD-3-Clause"
] | null | null | null |
// System includes
#include "tsystem.h"
#include "timagecache.h"
// Geometry
#include "tgeometry.h"
// Image
#include "tiio.h"
#include "timageinfo.h"
#include "trop.h"
#include "tropcm.h"
// Sound
#include "tsop.h"
#include "tsound.h"
// Strings
#include "tconvert.h"
// File-related includes
#include "tfilepath.h"
#include "tfiletype.h"
#include "filebrowsermodel.h"
#include "fileviewerpopup.h"
// OpenGL
#include "tgl.h"
#include "tvectorgl.h"
#include "tvectorrenderdata.h"
// Qt helpers
#include "toonzqt/gutil.h"
#include "toonzqt/imageutils.h"
// App-Stage includes
#include "tapp.h"
#include "toutputproperties.h"
#include "toonz/txsheethandle.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/levelproperties.h"
#include "toonz/tscenehandle.h"
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/tcamera.h"
#include "toonz/preferences.h"
#include "toonz/tproject.h"
// Image painting
#include "toonz/imagepainter.h"
// Preview
#include "previewfxmanager.h"
// Panels
#include "pane.h"
// recent files
#include "mainwindow.h"
// Other widgets
#include "toonzqt/flipconsole.h"
#include "toonzqt/dvdialog.h"
#include "filmstripselection.h"
#include "castselection.h"
#include "histogrampopup.h"
// Qt includes
#include <QApplication>
#include <QDesktopWidget>
#include <QSettings>
#include <QPainter>
#include <QDialogButtonBox>
#include <QAbstractButton>
#include <QLabel>
#include <QRadioButton>
#include <QSlider>
#include <QButtonGroup>
#include <QToolBar>
#include <QMainWindow>
#include <QUrl>
#include <QObject>
#include <QDesktopServices>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <stdint.h> // for uintptr_t
#ifdef _WIN32
#include "avicodecrestrictions.h"
#endif
#include "flipbook.h"
//-----------------------------------------------------------------------------
using namespace ImageUtils;
namespace {
QString getShortcut(const char *id) {
return QString::fromStdString(
CommandManager::instance()->getShortcutFromId(id));
}
} // namespace
//-----------------------------------------------------------------------------
namespace {
/* inline TRect getImageBounds(const TImageP& img)
{
if(TRasterImageP ri= img)
return ri->getRaster()->getBounds();
else if(TToonzImageP ti= img)
return ti->getRaster()->getBounds();
else
{
TVectorImageP vi= img;
return convert(vi->getBBox());
}
}*/
//-----------------------------------------------------------------------------
inline TRectD getImageBoundsD(const TImageP &img) {
if (TRasterImageP ri = img)
return TRectD(0, 0, ri->getRaster()->getLx(), ri->getRaster()->getLy());
else if (TToonzImageP ti = img)
return TRectD(0, 0, ti->getSize().lx, ti->getSize().ly);
else {
TVectorImageP vi = img;
return vi->getBBox();
}
}
} // namespace
//=============================================================================
/*! \class FlipBook
\brief The FlipBook class provides to view level images.
Inherits \b QWidget.
The object is composed of grid layout \b QGridLayout which
contains an image
viewer \b ImageViewer and a double button bar. It is possible
decide widget
title and which button bar show by setting QString and bool in
constructor.
You can set level to show in FlipBook using \b setLevel(); and
call
onDrawFrame() to show FlipBook current frame. The current frame
can be
set directly using setCurrentFrame(int index) or using slot
methods connected
to button bar.
\sa FlipBookPool class.
*/
FlipBook::FlipBook(QWidget *parent, QString viewerTitle,
std::vector<int> flipConsoleButtonMask, UCHAR flags,
bool isColorModel) //, bool showOnlyPlayBackgroundButton)
: QWidget(parent)
, m_viewerTitle(viewerTitle)
, m_levelNames()
, m_levels()
, m_playSound(false)
, m_snd(0)
, m_player(0)
//, m_doCompare(false)
, m_currentFrameToSave(0)
, m_lw()
, m_lr()
, m_loadPopup(0)
, m_savePopup(0)
, m_shrink(1)
, m_isPreviewFx(false)
, m_previewedFx(0)
, m_previewXsh(0)
, m_previewUpdateTimer(this)
, m_xl(0)
, m_title1()
, m_poolIndex(-1)
, m_freezed(false)
, m_loadbox()
, m_dim()
, m_loadboxes()
, m_freezeButton(0)
, m_flags(flags) {
setAcceptDrops(true);
setFocusPolicy(Qt::StrongFocus);
// flipConsoleButtonMask = flipConsoleButtonMask & ~FlipConsole::eSubCamera;
ImageUtils::FullScreenWidget *fsWidget =
new ImageUtils::FullScreenWidget(this);
m_imageViewer = new ImageViewer(
fsWidget, this,
std::find(flipConsoleButtonMask.begin(), flipConsoleButtonMask.end(),
FlipConsole::eHisto) == flipConsoleButtonMask.end());
fsWidget->setWidget(m_imageViewer);
setFocusProxy(m_imageViewer);
m_title = m_viewerTitle;
m_imageViewer->setIsColorModel(isColorModel);
// layout
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setMargin(0);
mainLayout->setSpacing(0);
{
mainLayout->addWidget(fsWidget, 1);
m_flipConsole = new FlipConsole(
mainLayout, flipConsoleButtonMask, true, 0,
(viewerTitle == "") ? "FlipConsole" : viewerTitle, this, !isColorModel);
mainLayout->addWidget(m_flipConsole);
}
setLayout(mainLayout);
// signal-slot connection
bool ret = connect(m_flipConsole, SIGNAL(buttonPressed(FlipConsole::EGadget)),
this, SLOT(onButtonPressed(FlipConsole::EGadget)));
m_flipConsole->setFrameRate(TApp::instance()
->getCurrentScene()
->getScene()
->getProperties()
->getOutputProperties()
->getFrameRate());
mainLayout->addWidget(m_flipConsole);
m_previewUpdateTimer.setSingleShot(true);
ret = ret && connect(parentWidget(), SIGNAL(closeButtonPressed()), this,
SLOT(onCloseButtonPressed()));
ret = ret && connect(parentWidget(), SIGNAL(doubleClick(QMouseEvent *)), this,
SLOT(onDoubleClick(QMouseEvent *)));
ret = ret && connect(&m_previewUpdateTimer, SIGNAL(timeout()), this,
SLOT(performFxUpdate()));
assert(ret);
m_viewerTitle = (m_viewerTitle.isEmpty()) ? tr("Flipbook") : m_viewerTitle;
parentWidget()->setWindowTitle(m_viewerTitle);
}
//-----------------------------------------------------------------------------
/*! add freeze button to the flipbook. called from the function
PreviewFxManager::openFlipBook.
this button will hide for re-use, at onCloseButtonPressed
*/
void FlipBook::addFreezeButtonToTitleBar() {
// If there is the button already, then reuse it.
if (m_freezeButton) {
m_freezeButton->show();
return;
}
// If there is not, then newly make it
TPanel *panel = qobject_cast<TPanel *>(parentWidget());
if (panel) {
TPanelTitleBar *titleBar = panel->getTitleBar();
m_freezeButton = new TPanelTitleBarButton(
titleBar, getIconThemePath("actions/20/pane_freeze.svg"));
m_freezeButton->setToolTip("Freeze");
titleBar->add(QPoint(-64, 0), m_freezeButton);
connect(m_freezeButton, SIGNAL(toggled(bool)), this, SLOT(freeze(bool)));
QPoint p(titleBar->width() - 64, 0);
m_freezeButton->move(p);
m_freezeButton->show();
}
}
//-----------------------------------------------------------------------------
void FlipBook::freeze(bool on) {
if (on)
freezePreview();
else
unfreezePreview();
}
//-----------------------------------------------------------------------------
void FlipBook::focusInEvent(QFocusEvent *e) {
m_flipConsole->makeCurrent();
QWidget::focusInEvent(e);
}
//-----------------------------------------------------------------------------
namespace {
enum { eBegin, eIncrement, eEnd };
static DVGui::ProgressDialog *Pd = 0;
class ProgressBarMessager final : public TThread::Message {
public:
int m_choice;
int m_val;
QString m_str;
ProgressBarMessager(int choice, int val, const QString &str = "")
: m_choice(choice), m_val(val), m_str(str) {}
void onDeliver() override {
switch (m_choice) {
case eBegin:
if (!Pd)
Pd = new DVGui::ProgressDialog(
QObject::tr("Saving previewed frames...."), QObject::tr("Cancel"),
0, m_val);
else
Pd->setMaximum(m_val);
Pd->show();
break;
case eIncrement:
if (Pd->wasCanceled()) {
delete Pd;
Pd = 0;
} else {
// if (m_val==Pd->maximum()) Pd->hide();
Pd->setValue(m_val);
}
break;
case eEnd: {
DVGui::info(m_str);
delete Pd;
Pd = 0;
} break;
default:
assert(false);
}
}
TThread::Message *clone() const override {
return new ProgressBarMessager(*this);
}
};
} // namespace
//=============================================================================
LoadImagesPopup::LoadImagesPopup(FlipBook *flip)
: FileBrowserPopup(tr("Load Images"), Options(WITH_APPLY_BUTTON),
tr("Append"), new QFrame(0))
, m_flip(flip)
, m_minFrame(0)
, m_maxFrame(1000000)
, m_step(1)
, m_shrink(1) {
QFrame *frameRangeFrame = (QFrame *)m_customWidget;
frameRangeFrame->setObjectName("customFrame");
frameRangeFrame->setFrameStyle(QFrame::StyledPanel);
// frameRangeFrame->setFixedHeight(30);
m_fromField = new DVGui::LineEdit(this);
m_toField = new DVGui::LineEdit(this);
m_stepField = new DVGui::LineEdit("1", this);
m_shrinkField = new DVGui::LineEdit("1", this);
// Define the append/load filter types
m_appendFilterTypes << "jpg"
<< "png"
<< "tga"
<< "tif"
<< "tiff"
<< "bmp"
<< "sgi"
<< "rgb";
#ifdef _WIN32
m_appendFilterTypes << "avi";
#endif
m_loadFilterTypes << "tlv"
<< "pli" << m_appendFilterTypes;
m_appendFilterTypes << "psd";
// layout
QHBoxLayout *frameRangeLayout = new QHBoxLayout();
frameRangeLayout->setMargin(5);
frameRangeLayout->setSpacing(5);
{
frameRangeLayout->addStretch(1);
frameRangeLayout->addWidget(new QLabel(tr("From:")), 0);
frameRangeLayout->addWidget(m_fromField, 0);
frameRangeLayout->addSpacing(5);
frameRangeLayout->addWidget(new QLabel(tr("To:")), 0);
frameRangeLayout->addWidget(m_toField, 0);
frameRangeLayout->addSpacing(10);
frameRangeLayout->addWidget(new QLabel(tr("Step:")), 0);
frameRangeLayout->addWidget(m_stepField, 0);
frameRangeLayout->addSpacing(5);
frameRangeLayout->addWidget(new QLabel(tr("Shrink:")));
frameRangeLayout->addWidget(m_shrinkField, 0);
}
frameRangeFrame->setLayout(frameRangeLayout);
// Make signal-slot connections
bool ret = true;
ret = ret && connect(m_fromField, SIGNAL(editingFinished()), this,
SLOT(onEditingFinished()));
ret = ret && connect(m_toField, SIGNAL(editingFinished()), this,
SLOT(onEditingFinished()));
ret = ret && connect(m_stepField, SIGNAL(editingFinished()), this,
SLOT(onEditingFinished()));
ret = ret && connect(m_shrinkField, SIGNAL(editingFinished()), this,
SLOT(onEditingFinished()));
ret = ret && connect(this, SIGNAL(filePathClicked(const TFilePath &)),
SLOT(onFilePathClicked(const TFilePath &)));
assert(ret);
setOkText(tr("Load"));
setWindowTitle(tr("Load / Append Images"));
}
//-----------------------------------------------------------------------------
void LoadImagesPopup::onEditingFinished() {
int val;
val = m_fromField->text().toInt();
m_from = (val < m_minFrame) ? m_minFrame : val;
val = m_toField->text().toInt();
m_to = (val > m_maxFrame) ? m_maxFrame : val;
if (m_to < m_from) m_to = m_from;
val = m_stepField->text().toInt();
m_step = (val < 1) ? 1 : val;
val = m_shrinkField->text().toInt();
m_shrink = (val < 1) ? 1 : val;
m_fromField->setText(QString::number(m_from));
m_toField->setText(QString::number(m_to));
m_stepField->setText(QString::number(m_step));
m_shrinkField->setText(QString::number(m_shrink));
}
//-----------------------------------------------------------------------------
bool LoadImagesPopup::execute() { return doLoad(false); }
//-----------------------------------------------------------------------------
/*! Append images with apply button
*/
bool LoadImagesPopup::executeApply() { return doLoad(true); }
//-----------------------------------------------------------------------------
bool LoadImagesPopup::doLoad(bool append) {
if (m_selectedPaths.empty()) return false;
::viewFile(*m_selectedPaths.begin(), m_from, m_to, m_step, m_shrink, 0,
m_flip, append);
// register recent files
std::set<TFilePath>::const_iterator pt;
for (pt = m_selectedPaths.begin(); pt != m_selectedPaths.end(); ++pt) {
RecentFiles::instance()->addFilePath(
toQString(
TApp::instance()->getCurrentScene()->getScene()->decodeFilePath(
(*pt))),
RecentFiles::Flip);
}
return true;
}
//-----------------------------------------------------------------------------
void LoadImagesPopup::onFilePathClicked(const TFilePath &fp) {
TLevel::Iterator it;
TLevelP level;
TLevelReaderP lr;
if (fp == TFilePath()) goto clear;
lr = TLevelReaderP(fp);
if (!lr) goto clear;
level = lr->loadInfo();
if (!level || level->getFrameCount() == 0) goto clear;
it = level->begin();
m_to = m_from = it->first.getNumber();
for (; it != level->end(); ++it) m_to = it->first.getNumber();
if (m_from == -2 && m_to == -2) m_from = m_to = 1;
m_minFrame = m_from;
m_maxFrame = m_to;
m_fromField->setText(QString::number(m_from));
m_toField->setText(QString::number(m_to));
return;
clear:
m_minFrame = 0;
m_maxFrame = 10000000;
m_fromField->setText("");
m_toField->setText("");
}
//=============================================================================
SaveImagesPopup::SaveImagesPopup(FlipBook *flip)
: FileBrowserPopup(tr("Save Flipbook Images")), m_flip(flip) {
setOkText(tr("Save"));
}
bool SaveImagesPopup::execute() {
if (m_selectedPaths.empty()) return false;
return m_flip->doSaveImages(*m_selectedPaths.begin());
}
//=============================================================================
void FlipBook::loadImages() {
if (!m_loadPopup) {
m_loadPopup = new LoadImagesPopup(this); //, frameRangeFrame);
// move the initial folder to the project root
m_loadPopup->setFolder(
TProjectManager::instance()->getCurrentProjectPath().getParentDir());
}
m_loadPopup->show();
m_loadPopup->raise();
m_loadPopup->activateWindow();
}
//=============================================================================
bool FlipBook::canAppend() {
// Images can be appended if:
// a) There is a name (in particular, an extension) representing currently
// held ones.
// b) This flipbook is not holding a preview (inappropriate and problematic).
// c) The level has no palette. Otherwise, appended images may have a
// different palette.
return !m_levels.empty() && !m_previewedFx && !m_palette;
}
//=============================================================================
void FlipBook::saveImages() {
if (!m_savePopup) m_savePopup = new SaveImagesPopup(this);
// initialize the default path every time
TOutputProperties *op = TApp::instance()
->getCurrentScene()
->getScene()
->getProperties()
->getOutputProperties();
m_savePopup->setFolder(TApp::instance()
->getCurrentScene()
->getScene()
->decodeFilePath(op->getPath())
.getParentDir());
m_savePopup->setFilename(op->getPath().withFrame().withoutParentDir());
m_savePopup->show();
m_savePopup->raise();
m_savePopup->activateWindow();
}
//=============================================================================
FlipBook::~FlipBook() {
if (m_loadPopup) delete m_loadPopup;
if (m_savePopup) delete m_savePopup;
}
//=============================================================================
bool FlipBook::doSaveImages(TFilePath fp) {
QStringList formats;
TLevelWriter::getSupportedFormats(formats, true);
Tiio::Writer::getSupportedFormats(formats, true);
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
TOutputProperties *outputSettings =
scene->getProperties()->getOutputProperties();
std::string ext = fp.getType();
// Open a notice that the previewFx is rendered in 8bpc regardless of the
// output settings.
if (m_isPreviewFx && outputSettings->getRenderSettings().m_bpp == 64) {
QString question =
"Save previewed images :\nImages will be saved in 8 bit per channel "
"with this command.\nDo you want to save images?";
int ret =
DVGui::MsgBox(question, QObject::tr("Save"), QObject::tr("Cancel"), 0);
if (ret == 2 || ret == 0) return false;
}
#ifdef _WIN32
if (ext == "avi") {
TPropertyGroup *props = outputSettings->getFileFormatProperties(ext);
std::string codecName = props->getProperty(0)->getValueAsString();
TDimension res = scene->getCurrentCamera()->getRes();
if (!AviCodecRestrictions::canWriteMovie(::to_wstring(codecName), res)) {
QString msg(
QObject::tr("The resolution of the output camera does not fit with "
"the options chosen for the output file format."));
DVGui::warning(msg);
return false;
}
}
#endif
if (ext == "") {
ext = outputSettings->getPath().getType();
fp = fp.withType(ext);
}
if (fp.getName() == "") {
DVGui::warning(
tr("The file name cannot be empty or contain any of the following "
"characters:(new line) \\ / : * ? \" |"));
return false;
}
if (!formats.contains(QString::fromStdString(ext))) {
DVGui::warning(
tr("It is not possible to save because the selected file format is not "
"supported."));
return false;
}
int from, to, step;
m_flipConsole->getFrameRange(from, to, step);
if (m_currentFrameToSave != 0) {
DVGui::info("Already saving!");
return true;
}
if (TFileType::getInfo(fp) == TFileType::RASTER_IMAGE)
fp = fp.withFrame(TFrameId::EMPTY_FRAME);
fp = scene->decodeFilePath(fp);
bool exists = TFileStatus(fp.getParentDir()).doesExist();
if (!exists) {
try {
TFilePath parent = fp.getParentDir();
TSystem::mkDir(parent);
DvDirModel::instance()->refreshFolder(parent.getParentDir());
} catch (TException &e) {
DVGui::error("Cannot create " + toQString(fp.getParentDir()) + " : " +
QString(::to_string(e.getMessage()).c_str()));
return false;
} catch (...) {
DVGui::error("Cannot create " + toQString(fp.getParentDir()));
return false;
}
}
if (TSystem::doesExistFileOrLevel(fp)) {
QString question(tr("File %1 already exists.\nDo you want to overwrite it?")
.arg(toQString(fp)));
int ret = DVGui::MsgBox(question, QObject::tr("Overwrite"),
QObject::tr("Cancel"));
if (ret == 2) return false;
}
try {
m_lw = TLevelWriterP(fp,
outputSettings->getFileFormatProperties(fp.getType()));
} catch (...) {
DVGui::error("It is not possible to save Flipbook content.");
return false;
}
m_lw->setFrameRate(outputSettings->getFrameRate());
m_currentFrameToSave = 1;
ProgressBarMessager(eBegin, m_framesCount).sendBlocking();
QTimer::singleShot(50, this, SLOT(saveImage()));
return true;
}
//-----------------------------------------------------------------------------
void FlipBook::saveImage() {
static int savedFrames = 0;
assert(Pd);
int from, to, step;
m_flipConsole->getFrameRange(from, to, step);
for (; m_currentFrameToSave <= m_framesCount; m_currentFrameToSave++) {
ProgressBarMessager(eIncrement, m_currentFrameToSave).sendBlocking();
if (!Pd) break;
int actualFrame = from + (m_currentFrameToSave - 1) * step;
TImageP img = getCurrentImage(actualFrame);
if (!img) continue;
TImageWriterP writer = m_lw->getFrameWriter(TFrameId(actualFrame));
bool failureOnSaving = false;
if (!writer) continue;
try {
writer->save(img);
} catch (...) {
QString str(tr("It is not possible to save Flipbook content."));
ProgressBarMessager(eEnd, 0, str).send();
m_currentFrameToSave = 0;
m_lw = TLevelWriterP();
savedFrames = 0;
return;
}
savedFrames++;
// if (!m_pb->changeFraction(m_currentFrameToSave,
// TApp::instance()->getCurrentXsheet()->getXsheet()->getFrameCount()))
// break;
m_currentFrameToSave++;
QTimer::singleShot(50, this, SLOT(saveImage()));
return;
}
QString str = tr("Saved %1 frames out of %2 in %3")
.arg(std::to_string(savedFrames).c_str())
.arg(std::to_string(m_framesCount).c_str())
.arg(::to_string(m_lw->getFilePath()).c_str());
if (!Pd) str = "Canceled! " + str;
ProgressBarMessager(eEnd, 0, str).send();
m_currentFrameToSave = 0;
m_lw = TLevelWriterP();
savedFrames = 0;
}
//=============================================================================
void FlipBook::onButtonPressed(FlipConsole::EGadget button) {
switch (button) {
case FlipConsole::eSound:
m_playSound = !m_playSound;
break;
case FlipConsole::eHisto:
m_imageViewer->showHistogram();
break;
case FlipConsole::eSaveImg: {
TRect loadbox = m_loadbox;
m_loadbox = TRect();
TImageP img = getCurrentImage(m_flipConsole->getCurrentFrame());
m_loadbox = loadbox;
if (!img) {
DVGui::warning(tr("There are no rendered images to save."));
return;
} else if ((TVectorImageP)img) {
DVGui::warning(
tr("It is not possible to take or compare snapshots for Toonz vector "
"levels."));
return;
}
TRasterImageP ri(img);
TToonzImageP ti(img);
TImageP clonedImg;
if (ri)
clonedImg = TRasterImageP(ri->getRaster()->clone());
else {
clonedImg = TToonzImageP(ti->getRaster()->clone(), ti->getSavebox());
clonedImg->setPalette(ti->getPalette());
}
TImageCache::instance()->add(QString("TnzCompareImg"), clonedImg);
// to update the histogram of compare snapshot image
m_imageViewer->invalidateCompHisto();
break;
}
case FlipConsole::eCompare:
if (m_flipConsole->isChecked(FlipConsole::eCompare) &&
(TVectorImageP)getCurrentImage(m_flipConsole->getCurrentFrame())) {
DVGui::warning(
tr("It is not possible to take or compare snapshots for Toonz vector "
"levels."));
// cancel the button pressing
m_flipConsole->pressButton(FlipConsole::eCompare);
return;
}
break;
case FlipConsole::eSave:
saveImages();
break;
default:
break;
}
}
//=============================================================================
// FlipBookPool
//-----------------------------------------------------------------------------
/*! \class FlipBookPool
\brief The FlipBookPool class is used to store used flipbook
viewers.
Flipbooks are generally intended as temporary but friendly floating widgets,
that gets displayed when a rendered scene or image needs to be shown.
Since a user may require that the geometry of a flipbook is to be remembered
between rendering tasks - perhaps even between different Toonz sessions -
flipbooks are always stored for later use in a \b FlipBookPool class.
This class implements the basical features to \b pop a flipbook from the
pool
or \b push a used one; plus, it provides the \b save and \b load functions
for persistent storage between Toonz sessions.
\sa FlipBook class.
*/
FlipBookPool::FlipBookPool() : m_overallFlipCount(0) {
qRegisterMetaType<ImagePainter::VisualSettings>(
"ImagePainter::VisualSettings");
}
//-----------------------------------------------------------------------------
FlipBookPool::~FlipBookPool() {}
//-----------------------------------------------------------------------------
FlipBookPool *FlipBookPool::instance() {
static FlipBookPool poolInstance;
return &poolInstance;
}
//-----------------------------------------------------------------------------
void FlipBookPool::push(FlipBook *flipbook) {
m_pool.insert(pair<int, FlipBook *>(flipbook->getPoolIndex(), flipbook));
}
//-----------------------------------------------------------------------------
//! Extracts the first unused flipbook from the flipbook pool.
//! If all known flipbooks are shown, allocates a new flipbook with the
//! first unused flipbook geometry in a geometry pool.
//! Again, if all recorded geometry are used by some existing flipbook, a
//! default geometry is used.
FlipBook *FlipBookPool::pop() {
FlipBook *flipbook;
TPanel *panel;
TMainWindow *currentRoom = TApp::instance()->getCurrentRoom();
if (m_pool.empty()) {
panel = TPanelFactory::createPanel(currentRoom, "FlipBook");
panel->setFloating(true);
flipbook = static_cast<FlipBook *>(panel->widget());
// Set geometry
static int x = 0, y = 0;
if (m_geometryPool.empty()) {
panel->setGeometry(x += 50, y += 50, 400, 300);
flipbook->setPoolIndex(m_overallFlipCount);
m_overallFlipCount++;
} else {
flipbook->setPoolIndex(m_geometryPool.begin()->first);
QRect geometry(m_geometryPool.begin()->second);
panel->setGeometry(geometry);
if ((geometry & QApplication::desktop()->availableGeometry(panel))
.isEmpty())
panel->move(x += 50, y += 50);
m_geometryPool.erase(m_geometryPool.begin());
}
} else {
flipbook = m_pool.begin()->second;
panel = (TPanel *)flipbook->parent();
m_pool.erase(m_pool.begin());
}
// The panel need to be added to currentRoom's layout control.
currentRoom->addDockWidget(panel);
panel->raise();
panel->show();
return flipbook;
}
//-----------------------------------------------------------------------------
//! Saves the content of this flipbook pool.
void FlipBookPool::save() const {
QSettings history(toQString(m_historyPath), QSettings::IniFormat);
history.clear();
history.setValue("count", m_overallFlipCount);
history.beginGroup("flipbooks");
std::map<int, FlipBook *>::const_iterator it;
for (it = m_pool.begin(); it != m_pool.end(); ++it) {
history.beginGroup(QString::number(it->first));
TPanel *panel = static_cast<TPanel *>(it->second->parent());
history.setValue("geometry", panel->geometry());
history.endGroup();
}
std::map<int, QRect>::const_iterator jt;
for (jt = m_geometryPool.begin(); jt != m_geometryPool.end(); ++jt) {
history.beginGroup(QString::number(jt->first));
history.setValue("geometry", jt->second);
history.endGroup();
}
history.endGroup();
}
//-----------------------------------------------------------------------------
//! Loads the pool from input history
void FlipBookPool::load(const TFilePath &historyPath) {
QSettings history(toQString(historyPath), QSettings::IniFormat);
m_historyPath = historyPath;
m_pool.clear();
m_geometryPool.clear();
m_overallFlipCount = history.value("count").toInt();
history.beginGroup("flipbooks");
QStringList flipBooks(history.childGroups());
QStringList::iterator it;
for (it = flipBooks.begin(); it != flipBooks.end(); ++it) {
history.beginGroup(*it);
// Retrieve flipbook geometry
QVariant geom = history.value("geometry");
// Insert geometry
m_geometryPool.insert(pair<int, QRect>(it->toInt(), geom.toRect()));
history.endGroup();
}
history.endGroup();
}
//=============================================================================
//! Returns the level frame number corresponding to passed flipbook index
TFrameId FlipBook::Level::flipbookIndexToLevelFrame(int index) {
TLevel::Iterator it;
int levelPos;
if (m_incrementalIndexing) {
levelPos = (index - 1) * m_step;
it = m_level->getTable()->find(m_fromIndex);
advance(it, levelPos);
} else {
levelPos = m_fromIndex + (index - 1) * m_step;
it = m_level->getTable()->find(levelPos);
}
if (it == m_level->end()) return TFrameId();
return it->first;
}
//-----------------------------------------------------------------------------
//! Returns the number of flipbook indexes available for this level
int FlipBook::Level::getIndexesCount() {
return m_incrementalIndexing ? (m_level->getFrameCount() - 1) / m_step + 1
: (m_toIndex - m_fromIndex) / m_step + 1;
}
//=============================================================================
bool FlipBook::isSavable() const {
if (m_levels.empty()) return false;
for (int i = 0; i < m_levels.size(); i++)
if (m_levels[i].m_fp != TFilePath() &&
(m_levels[i].m_fp.getType() == "tlv" ||
m_levels[i].m_fp.getType() == "pli"))
return false;
return true;
}
//=============================================================================
/*! Set the level contained in \b fp to FlipBook; if level exist show in image
viewer its first frame, set current frame to 1.
It's possible to change level palette, in fact if \b palette is
different
from 0 set level palette to \b palette.
*/
void FlipBook::setLevel(const TFilePath &fp, TPalette *palette, int from,
int to, int step, int shrink, TSoundTrack *snd,
bool append, bool isToonzOutput) {
try {
if (!append) {
clearCache();
m_levelNames.clear();
m_levels.clear();
}
m_snd = 0;
m_xl = 0;
m_flipConsole->enableProgressBar(false);
m_flipConsole->setProgressBarStatus(0);
m_flipConsole->enableButton(FlipConsole::eSound, snd != 0);
m_flipConsole->enableButton(FlipConsole::eDefineLoadBox, true);
m_flipConsole->enableButton(FlipConsole::eUseLoadBox, true);
if (fp == TFilePath()) return;
m_shrink = shrink;
if (fp.getDots() == ".." && fp.getType() != "noext")
m_levelNames.push_back(toQString(fp.withoutParentDir().withFrame()));
else
m_levelNames.push_back(toQString(fp.withoutParentDir()));
m_snd = snd;
if (TSystem::doesExistFileOrLevel(fp)) // is a viewfile
{
// m_flipConsole->enableButton(FlipConsole::eCheckBg,
// true);//fp.getType()!="pli");
m_lr = TLevelReaderP(fp);
bool supportsRandomAccess = doesSupportRandomAccess(fp, isToonzOutput);
if (supportsRandomAccess) m_lr->enableRandomAccessRead(isToonzOutput);
bool randomAccessRead = supportsRandomAccess && isToonzOutput;
bool incrementalIndexing = m_isPreviewFx ? true : false;
TLevelP level = m_lr->loadInfo();
if (!level || level->getFrameCount() == 0) {
if (m_flags & eDontKeepFilesOpened) m_lr = TLevelReaderP();
return;
}
// For the color model, get the reference fids from palette and delete
// unneeded from the table
if (m_imageViewer->isColorModel() && palette) {
std::vector<TFrameId> fids = palette->getRefLevelFids();
// when loading a single-frame, standard raster image into the
// ColorModel, skip here.
// If the fid == NO_FRAME(=-2), fids stores 0.
if (!fids.empty() && !(fids.size() == 1 && fids[0].getNumber() == 0)) {
// make the fid list to be deleted
std::vector<TFrameId> deleteList;
TLevel::Iterator it;
for (it = level->begin(); it != level->end(); it++) {
// If the fid is not included in the reference list, then delete it
int i;
for (i = 0; i < (int)fids.size(); i++) {
if (fids[i].getNumber() == it->first.getNumber()) break;
}
if (i == fids.size()) {
deleteList.push_back(it->first);
}
}
// delete list items here
if (!deleteList.empty())
for (int i = 0; i < (int)deleteList.size(); i++)
level->getTable()->erase(deleteList[i]);
}
}
int fromIndex, toIndex;
// in order to avoid that the current frame unexpectedly moves to 1 on the
// Color Model once editing the style
int current = -1;
if (from == -1 && to == -1) {
fromIndex = level->begin()->first.getNumber();
toIndex = (--level->end())->first.getNumber();
if (m_imageViewer->isColorModel())
current = m_flipConsole->getCurrentFrame();
incrementalIndexing = true;
} else {
TLevel::Iterator it = level->begin();
// Adjust the frame interval to read. There is one special case:
// If the level read did not support random access, *AND* the level to
// show was just rendered,
// we have to assume that no level update happened, and the
// from-to-step infos are lost.
// So, shift the requested interval from 1 and place step to 1.
fromIndex = from;
toIndex = to;
if (isToonzOutput && !supportsRandomAccess) {
fromIndex = 1;
toIndex = level->getFrameCount();
step = 1;
}
if (level->begin()->first.getNumber() != TFrameId::NO_FRAME) {
fromIndex = std::max(fromIndex, level->begin()->first.getNumber());
toIndex = std::min(toIndex, (--level->end())->first.getNumber());
} else {
fromIndex = level->begin()->first.getNumber();
toIndex = (--level->end())->first.getNumber();
incrementalIndexing = true;
}
// Workaround to display simple background images when loading from
// the right-click menu context
fromIndex = std::min(fromIndex, toIndex);
}
Level levelToPush(level, fp, fromIndex, toIndex, step);
levelToPush.m_randomAccessRead = randomAccessRead;
levelToPush.m_incrementalIndexing = incrementalIndexing;
int formatIdx = Preferences::instance()->matchLevelFormat(fp);
if (formatIdx >= 0 && Preferences::instance()
->levelFormat(formatIdx)
.m_options.m_premultiply) {
levelToPush.m_premultiply = true;
}
m_levels.push_back(levelToPush);
// Get the frames count to be shown in this flipbook level
m_framesCount = levelToPush.getIndexesCount();
assert(m_framesCount <= level->getFrameCount());
// this value will be used in loadAndCacheAllTlvImages later
int addingFrameAmount = m_framesCount;
if (append && !m_levels.empty()) {
int oldFrom, oldTo, oldStep;
m_flipConsole->getFrameRange(oldFrom, oldTo, oldStep);
assert(oldFrom == 1);
assert(oldStep == 1);
m_framesCount += oldTo;
}
m_flipConsole->setFrameRange(1, m_framesCount, 1, current);
if (palette && level->getPalette() != palette) level->setPalette(palette);
m_palette = level->getPalette();
const TImageInfo *ii = m_lr->getImageInfo();
if (ii) m_dim = TDimension(ii->m_lx / m_shrink, ii->m_ly / m_shrink);
int levelFrameCount = 0;
for (int lev = 0; lev < m_levels.size(); lev++)
levelFrameCount += m_levels[lev].m_level->getFrameCount();
if (levelFrameCount == 1)
m_title = " :: 1 Frame";
else
m_title = " :: " + QString::number(levelFrameCount) + " Frames";
// color model does not concern about the pixel size
if (ii && !m_imageViewer->isColorModel())
m_title = m_title + " :: " + QString::number(ii->m_lx) + "x" +
QString::number(ii->m_ly) + " Pixels";
if (shrink > 1)
m_title = m_title + " :: " + "Shrink: " + QString::number(shrink);
// when using the flip module, this signal is to show the loaded level
// names in application's title bar
QString arg = QString("Flip : %1").arg(m_levelNames[0]);
emit imageLoaded(arg);
// When viewing the tlv, try to cache all frames at the beginning.
if (!m_imageViewer->isColorModel() && fp.getType() == "tlv" &&
!(m_flags & eDontKeepFilesOpened) && !m_isPreviewFx) {
loadAndCacheAllTlvImages(levelToPush,
m_framesCount - addingFrameAmount + 1, // from
m_framesCount); // to
}
// An old archived bug says that simultaneous open for read of the same
// tlv are not allowed...
// if(m_lr && m_lr->getFilePath().getType()=="tlv")
// m_lr = TLevelReaderP();
} else // is a render
{
m_flipConsole->enableButton(FlipConsole::eCheckBg, true);
m_previewedFx = 0;
m_previewXsh = 0;
m_levels.clear();
m_flipConsole->setFrameRange(from, to, step);
m_framesCount = (to - from) / step + 1;
m_title = tr("Rendered Frames :: From %1 To %2 :: Step %3")
.arg(QString::number(from))
.arg(QString::number(to))
.arg(QString::number(step));
if (shrink > 1)
m_title = m_title + tr(" :: Shrink ") + QString::number(shrink);
}
// parentWidget()->setWindowTitle(m_title);
m_imageViewer->setHistogramEnable(true);
m_imageViewer->setHistogramTitle(m_levelNames[0]);
m_flipConsole->enableButton(FlipConsole::eSave, isSavable());
m_flipConsole->showCurrentFrame();
if (m_flags & eDontKeepFilesOpened) m_lr = TLevelReaderP();
} catch (...) {
return;
}
}
//-----------------------------------------------------------------------------
void FlipBook::setTitle(const QString &title) {
m_viewerTitle = title;
if (!m_previewedFx && !m_levelNames.empty())
m_title = m_viewerTitle + " :: " + m_levelNames[0];
else
m_title = m_viewerTitle;
}
//-----------------------------------------------------------------------------
void FlipBook::setLevel(TXshSimpleLevel *xl) {
try {
clearCache();
m_xl = xl;
m_levelNames.push_back(QString::fromStdWString(xl->getName()));
m_snd = 0;
m_previewedFx = 0;
m_previewXsh = 0;
m_levels.clear();
m_flipConsole->enableButton(FlipConsole::eSound, false);
m_shrink = 1;
int step = 1;
m_framesCount = (m_xl->getFrameCount() - 1) / step + 1;
m_flipConsole->setFrameRange(1, m_framesCount, step);
m_flipConsole->enableProgressBar(false);
m_flipConsole->setProgressBarStatus(0);
m_palette = m_xl->getPalette();
const LevelProperties *p = m_xl->getProperties();
m_title = m_viewerTitle + " :: " + m_levelNames[0];
if (m_framesCount == 1)
m_title = m_title + " :: 1 Frame";
else
m_title = m_title + " :: " + QString::number(m_framesCount) + " Frames";
if (p) m_dim = p->getImageRes();
if (p)
m_title = m_title + " :: " + QString::number(p->getImageRes().lx) +
"x" + QString::number(p->getImageRes().ly) + " Pixels";
if (m_shrink > 1)
m_title = m_title + " :: " + "Shrink: " + QString::number(m_shrink);
m_imageViewer->setHistogramEnable(true);
m_imageViewer->setHistogramTitle(m_levelNames[0]);
m_flipConsole->showCurrentFrame();
} catch (...) {
return;
}
}
//-----------------------------------------------------------------------------
void FlipBook::setLevel(TFx *previewedFx, TXsheet *xsh, TLevel *level,
TPalette *palette, int from, int to, int step,
int currentFrame, TSoundTrack *snd) {
m_xl = 0;
m_previewedFx = previewedFx;
m_previewXsh = xsh;
m_isPreviewFx = true;
m_levels.clear();
m_levels.push_back(Level(level, TFilePath(), from - 1, to - 1, step));
m_levelNames.clear();
m_levelNames.push_back(QString::fromStdString(level->getName()));
m_title = m_viewerTitle;
m_flipConsole->setFrameRange(from, to, step, currentFrame);
m_flipConsole->enableProgressBar(true);
m_flipConsole->enableButton(FlipConsole::eDefineLoadBox, false);
m_flipConsole->enableButton(FlipConsole::eUseLoadBox, false);
m_flipConsole->enableButton(FlipConsole::eSound, snd != 0);
m_snd = snd;
m_framesCount = (to - from) / step + 1;
m_imageViewer->setHistogramEnable(true);
m_imageViewer->setHistogramTitle(m_levelNames[0]);
m_flipConsole->showCurrentFrame();
}
//-----------------------------------------------------------------------------
TFx *FlipBook::getPreviewedFx() const {
return m_isPreviewFx ? m_previewedFx.getPointer() : 0;
}
//-----------------------------------------------------------------------------
TXsheet *FlipBook::getPreviewXsheet() const {
return m_isPreviewFx ? m_previewXsh.getPointer() : 0;
}
//-----------------------------------------------------------------------------
TRectD FlipBook::getPreviewedImageGeometry() const {
if (!m_isPreviewFx) return TRectD();
// Build viewer's geometry
QRect viewerGeom(m_imageViewer->geometry());
viewerGeom.adjust(-1, -1, 1, 1);
TRectD viewerGeomD(viewerGeom.left(), viewerGeom.top(),
viewerGeom.right() + 1, viewerGeom.bottom() + 1);
TPointD viewerCenter((viewerGeomD.x0 + viewerGeomD.x1) * 0.5,
(viewerGeomD.y0 + viewerGeomD.y1) * 0.5);
// NOTE: The above adjust() is imposed to counter the geometry removal
// specified in function
// FlipBook::onDoubleClick.
// Build viewer-to-camera affine
TAffine viewToCam(m_imageViewer->getViewAff().inv() *
TTranslation(-viewerCenter));
return viewToCam * viewerGeomD;
}
//-----------------------------------------------------------------------------
void FlipBook::schedulePreviewedFxUpdate() {
if (m_previewedFx)
m_previewUpdateTimer.start(
1000); // The effective fx update will happen in 1 msec.
}
//-----------------------------------------------------------------------------
void FlipBook::performFxUpdate() {
// refresh only when the subcamera is active
if (PreviewFxManager::instance()->isSubCameraActive(m_previewedFx))
PreviewFxManager::instance()->refreshView(m_previewedFx);
}
//-----------------------------------------------------------------------------
void FlipBook::regenerate() {
PreviewFxManager::instance()->reset(TFxP(m_previewedFx));
}
//-----------------------------------------------------------------------------
void FlipBook::regenerateFrame() {
PreviewFxManager::instance()->reset(m_previewedFx, getCurrentFrame() - 1);
}
//-----------------------------------------------------------------------------
void FlipBook::clonePreview() {
if (!m_previewedFx) return;
FlipBook *newFlip =
PreviewFxManager::instance()->showNewPreview(m_previewedFx, true);
newFlip->m_imageViewer->setViewAff(m_imageViewer->getViewAff());
PreviewFxManager::instance()->refreshView(m_previewedFx);
}
//-----------------------------------------------------------------------------
void FlipBook::freezePreview() {
if (!m_previewedFx) return;
PreviewFxManager::instance()->freeze(this);
m_freezed = true;
// sync the button state when triggered by shortcut
if (m_freezeButton) m_freezeButton->setPressed(true);
}
//-----------------------------------------------------------------------------
void FlipBook::unfreezePreview() {
if (!m_previewedFx) return;
PreviewFxManager::instance()->unfreeze(this);
m_freezed = false;
// sync the button state when triggered by shortcut
if (m_freezeButton) m_freezeButton->setPressed(false);
}
//-----------------------------------------------------------------------------
void FlipBook::setProgressBarStatus(const std::vector<UCHAR> *pbStatus) {
m_flipConsole->setProgressBarStatus(pbStatus);
}
//-----------------------------------------------------------------------------
const std::vector<UCHAR> *FlipBook::getProgressBarStatus() const {
return m_flipConsole->getProgressBarStatus();
}
//-----------------------------------------------------------------------------
void FlipBook::showFrame(int frame) {
if (frame < 0) return;
m_flipConsole->setCurrentFrame(frame);
m_flipConsole->showCurrentFrame();
}
//-----------------------------------------------------------------------------
void FlipBook::playAudioFrame(int frame) {
static bool first = true;
static bool audioCardInstalled;
if (!m_snd || !m_playSound) return;
if (first) {
audioCardInstalled = TSoundOutputDevice::installed();
first = false;
}
if (!audioCardInstalled) return;
if (!m_player) {
m_player = new TSoundOutputDevice();
m_player->attach(this);
}
if (m_player) {
// Flipbook does not currently support double fps - thus, casting to int in
// soundtrack playback, too
int fps = TApp::instance()
->getCurrentScene()
->getScene()
->getProperties()
->getOutputProperties()
->getFrameRate();
int samplePerFrame = int(m_snd->getSampleRate()) / fps;
TINT32 firstSample = (frame - 1) * samplePerFrame;
TINT32 lastSample = firstSample + samplePerFrame;
try {
m_player->play(m_snd, firstSample, lastSample, false, false);
} catch (TSoundDeviceException &e) {
std::string msg;
if (e.getType() == TSoundDeviceException::UnsupportedFormat) {
try {
TSoundTrackFormat fmt =
m_player->getPreferredFormat(m_snd->getFormat());
m_player->play(TSop::convert(m_snd, fmt), firstSample, lastSample,
false, false);
} catch (TSoundDeviceException &ex) {
throw TException(ex.getMessage());
return;
}
}
}
}
}
//-----------------------------------------------------------------------------
TImageP FlipBook::getCurrentImage(int frame) {
std::string id = "";
TFrameId fid;
TFilePath fp;
bool randomAccessRead = false;
bool incrementalIndexing = false;
bool premultiply = false;
if (m_xl) // is an xsheet level
{
if (m_xl->getFrameCount() <= 0) return 0;
return m_xl->getFrame(m_xl->index2fid(frame - 1), false);
} else if (!m_levels.empty()) // is a viewfile or a previewFx
{
TLevelP level;
QString levelName;
int from, to, step;
m_flipConsole->getFrameRange(from, to, step);
int frameIndex = m_previewedFx ? ((frame - from) / step) + 1 : frame;
int i = 0;
// Search all subsequent levels on the flipbook and retrieve the one
// containing the required frame
for (i = 0; i < m_levels.size(); i++) {
int frameIndexesCount = m_levels[i].getIndexesCount();
if (frameIndex > 0 && frameIndex <= frameIndexesCount) break;
frameIndex -= frameIndexesCount;
}
if (i == m_levels.size() || frame < 0) return 0;
frame--;
// Now, get the right frame from the level
level = m_levels[i].m_level;
fp = m_levels[i].m_fp; // fp=empty when previewing fx
randomAccessRead = m_levels[i].m_randomAccessRead;
incrementalIndexing = m_levels[i].m_incrementalIndexing;
levelName = m_levelNames[i];
fid = m_levels[i].flipbookIndexToLevelFrame(frameIndex);
premultiply = m_levels[i].m_premultiply;
if (fid == TFrameId()) return 0;
id = levelName.toStdString() + fid.expand(TFrameId::NO_PAD) +
((m_isPreviewFx) ? "" : ::to_string(this));
if (!m_isPreviewFx)
m_title1 = m_viewerTitle + " :: " + fp.withoutParentDir().withFrame(fid);
else
m_title1 = "";
} else if (m_levelNames.empty())
return 0;
else // is a render
id = m_levelNames[0].toStdString() + std::to_string(frame);
bool showSub = m_flipConsole->isChecked(FlipConsole::eUseLoadBox);
if (TImageCache::instance()->isCached(id)) {
TRect loadbox;
std::map<std::string, TRect>::const_iterator it = m_loadboxes.find(id);
if (it != m_loadboxes.end()) loadbox = it->second;
// Resubmit the image to the cache as the 'last one' seen by the flipbook.
// TImageCache::instance()->add(toString(m_poolIndex) + "lastFlipFrame",
// img);
// m_lastViewedFrame = frame+1;
if ((showSub && m_loadbox == loadbox) || (!showSub && loadbox == TRect()))
return TImageCache::instance()->get(id, false);
else
TImageCache::instance()->remove(id);
}
if (fp != TFilePath() && !m_isPreviewFx) {
int lx = 0, oriLx = 0;
// TLevelReaderP lr(fp);
if (!m_lr || (fp != m_lr->getFilePath())) {
m_lr = TLevelReaderP(fp);
m_lr->enableRandomAccessRead(randomAccessRead);
}
if (!m_lr) return 0;
// try to get image info only when loading tlv or pli as it is quite time
// consuming
if (fp.getType() == "tlv" || fp.getType() == "pli") {
if (m_lr->getImageInfo()) lx = oriLx = m_lr->getImageInfo()->m_lx;
}
TImageReaderP ir = m_lr->getFrameReader(fid);
ir->setShrink(m_shrink);
if (m_loadbox != TRect() && showSub) {
ir->setRegion(m_loadbox);
lx = m_loadbox.getLx();
}
if (Preferences::instance()->is30bitDisplayEnabled())
ir->enable16BitRead(true);
TImageP img = ir->load();
if (img) {
TRasterImageP ri = ((TRasterImageP)img);
TToonzImageP ti = ((TToonzImageP)img);
if (premultiply) {
if (ri)
TRop::premultiply(ri->getRaster());
else if (ti)
TRop::premultiply(ti->getRaster());
}
// se e' stata caricata una sottoimmagine alcuni formati in realta'
// caricano tutto il raster e fanno extract, non si ha quindi alcun
// risparmio di occupazione di memoria; alloco un raster grande
// giusto copio la region e butto quello originale.
if (ri && showSub && m_loadbox != TRect() &&
ri->getRaster()->getLx() == oriLx) // questo serve perche' per avi e
// mov la setRegion e'
// completamente ignorata...
ri->setRaster(ri->getRaster()->extract(m_loadbox)->clone());
else if (ri && ri->getRaster()->getWrap() > ri->getRaster()->getLx())
ri->setRaster(ri->getRaster()->clone());
else if (ti && ti->getCMapped()->getWrap() > ti->getCMapped()->getLx())
ti->setCMapped(ti->getCMapped()->clone());
if ((fp.getType() == "tlv" || fp.getType() == "pli") && m_shrink > 1 &&
(lx == 0 || (ri && ri->getRaster()->getLx() == lx) ||
(ti && ti->getRaster()->getLx() == lx))) {
if (ri)
ri->setRaster(TRop::shrink(ri->getRaster(), m_shrink));
else if (ti)
ti->setCMapped(TRop::shrink(ti->getRaster(), m_shrink));
}
TPalette *palette = img->getPalette();
if (m_palette && (!palette || palette != m_palette))
img->setPalette(m_palette);
TImageCache::instance()->add(id, img);
m_loadboxes[id] = showSub ? m_loadbox : TRect();
}
// An old archived bug says that simultaneous open for read of the same tlv
// are not allowed...
// if(fp.getType()=="tlv")
// m_lr = TLevelReaderP();
if (m_flags & eDontKeepFilesOpened) m_lr = TLevelReaderP();
return img;
} else if (fp == TFilePath() && m_isPreviewFx) {
if (!TImageCache::instance()->isCached(id)) {
/*string lastFrameCacheId(toString(m_poolIndex) + "lastFlipFrame");
if(TImageCache::instance()->isCached(lastFrameCacheId))
return TImageCache::instance()->get(lastFrameCacheId, false);
else*/
return 0;
// showFrame(m_lastViewedFrame);
}
}
return 0;
}
//-----------------------------------------------------------------------------
/*! Set current level frame to image viewer. Add the view image in cache.
*/
void FlipBook::onDrawFrame(int frame, const ImagePainter::VisualSettings &vs,
QElapsedTimer *timer, qint64 targetInstant) {
try {
m_imageViewer->setVisual(vs);
m_imageViewer->setTimerAndTargetInstant(timer, targetInstant);
TImageP img = getCurrentImage(frame);
if (!img) return;
m_imageViewer->setImage(img);
} catch (...) {
m_imageViewer->setImage(TImageP());
}
if (m_playSound && !vs.m_drawBlankFrame) playAudioFrame(frame);
}
//-----------------------------------------------------------------------------
void FlipBook::swapBuffers() { m_imageViewer->doSwapBuffers(); }
//-----------------------------------------------------------------------------
void FlipBook::changeSwapBehavior(bool enable) {
m_imageViewer->changeSwapBehavior(enable);
}
//-----------------------------------------------------------------------------
void FlipBook::setLoadbox(const TRect &box) {
m_loadbox =
(m_dim.lx > 0) ? box * TRect(0, 0, m_dim.lx - 1, m_dim.ly - 1) : box;
}
//----------------------------------------------------------------
void FlipBook::clearCache() {
TLevel::Iterator it;
if (m_levelNames.empty()) return;
int i;
if (!m_levels.empty()) // is a viewfile
for (i = 0; i < m_levels.size(); i++)
for (it = m_levels[i].m_level->begin(); it != m_levels[i].m_level->end();
++it)
TImageCache::instance()->remove(
m_levelNames[i].toStdString() +
std::to_string(it->first.getNumber()) +
((m_isPreviewFx) ? "" : ::to_string(this)));
else {
int from, to, step;
m_flipConsole->getFrameRange(from, to, step);
for (int i = from; i <= to; i += step) // is a render
// color model may loading a part of frames in the level
if (m_imageViewer->isColorModel() && m_palette) {
// get the actually-loaded frame list
std::vector<TFrameId> fids(m_palette->getRefLevelFids());
if (!fids.empty() && (int)fids.size() >= i) {
int frame = fids[i - 1].getNumber();
TImageCache::instance()->remove(m_levelNames[0].toStdString() +
std::to_string(frame));
} else {
TImageCache::instance()->remove(m_levelNames[0].toStdString() +
std::to_string(i));
}
} else
TImageCache::instance()->remove(m_levelNames[0].toStdString() +
std::to_string(i));
}
}
//-----------------------------------------------------------------------------
void FlipBook::onCloseButtonPressed() {
m_flipConsole->setActive(false);
closeFlipBook(this);
reset();
// hide freeze button in preview fx window
if (m_freezeButton) {
m_freezeButton->hide();
m_imageViewer->setIsRemakingPreviewFx(false);
}
// Return the flipbook to the pool in case it was popped from it.
if (m_poolIndex >= 0) FlipBookPool::instance()->push(this);
}
//-----------------------------------------------------------------------------
void ImageViewer::showHistogram() {
if (!m_isHistogramEnable) return;
if (m_histogramPopup->isVisible())
m_histogramPopup->raise();
else {
m_histogramPopup->setImage(getImage());
m_histogramPopup->show();
}
}
//-----------------------------------------------------------------------------
void FlipBook::dragEnterEvent(QDragEnterEvent *e) {
const QMimeData *mimeData = e->mimeData();
bool isResourceDrop = acceptResourceDrop(mimeData->urls());
if (!isResourceDrop &&
!mimeData->hasFormat("application/vnd.toonz.drawings") &&
!mimeData->hasFormat(CastItems::getMimeFormat()))
return;
for (const QUrl &url : mimeData->urls()) {
TFilePath fp(url.toLocalFile().toStdWString());
std::string type = fp.getType();
if (type == "tzp" || type == "tzu" || type == "tnz" || type == "scr" ||
type == "mesh")
return;
}
if (mimeData->hasFormat(CastItems::getMimeFormat())) {
const CastItems *items = dynamic_cast<const CastItems *>(mimeData);
if (!items) return;
int i;
for (i = 0; i < items->getItemCount(); i++) {
CastItem *item = items->getItem(i);
TXshSimpleLevel *sl = item->getSimpleLevel();
if (!sl) return;
}
}
if (isResourceDrop) {
// Force CopyAction
e->setDropAction(Qt::CopyAction);
// For files, don't accept original proposed action in case it's a move
e->accept();
} else
e->acceptProposedAction();
}
//-----------------------------------------------------------------------------
void FlipBook::dropEvent(QDropEvent *e) {
const QMimeData *mimeData = e->mimeData();
bool isResourceDrop = acceptResourceDrop(mimeData->urls());
if (mimeData->hasUrls()) {
for (const QUrl &url : mimeData->urls()) {
TFilePath fp(url.toLocalFile().toStdWString());
if (TFileType::getInfo(fp) != TFileType::UNKNOW_FILE) setLevel(fp);
if (isResourceDrop) {
// Force CopyAction
e->setDropAction(Qt::CopyAction);
// For files, don't accept original proposed action in case it's a move
e->accept();
} else
e->acceptProposedAction();
return;
}
} else if (mimeData->hasFormat(
"application/vnd.toonz.drawings")) // drag-drop from film
// strip
{
TFilmstripSelection *s =
dynamic_cast<TFilmstripSelection *>(TSelection::getCurrent());
TXshSimpleLevel *sl = TApp::instance()->getCurrentLevel()->getSimpleLevel();
if (!s || !sl) return;
TXshSimpleLevel *newSl = new TXshSimpleLevel();
newSl->setScene(sl->getScene());
newSl->setType(sl->getType());
newSl->setPalette(sl->getPalette());
newSl->clonePropertiesFrom(sl);
const std::set<TFrameId> &fids = s->getSelectedFids();
std::set<TFrameId>::const_iterator it;
for (it = fids.begin(); it != fids.end(); ++it)
newSl->setFrame(*it, sl->getFrame(*it, false)->cloneImage());
setLevel(newSl);
} else if (mimeData->hasFormat(
CastItems::getMimeFormat())) // Drag-Drop from castviewer
{
const CastItems *items = dynamic_cast<const CastItems *>(mimeData);
if (!items) return;
int i;
for (i = 0; i < items->getItemCount(); i++) {
CastItem *item = items->getItem(i);
if (TXshSimpleLevel *sl = item->getSimpleLevel()) setLevel(sl);
}
}
m_flipConsole->makeCurrent();
}
//-------------------------------------------------------------------
void FlipBook::reset() {
if (!m_isPreviewFx) // The cache is owned by the PreviewFxManager otherwise
clearCache();
else
PreviewFxManager::instance()->detach(this);
m_levelNames.clear();
m_levels.clear();
m_framesCount = 0;
m_palette = 0;
m_imageViewer->setImage(TImageP());
m_imageViewer->hideHistogram();
m_isPreviewFx = false;
m_previewedFx = 0;
m_previewXsh = 0;
m_freezed = false;
// sync the freeze button
if (m_freezeButton) m_freezeButton->setPressed(false);
m_flipConsole->pressButton(FlipConsole::ePause);
if (m_playSound) m_flipConsole->pressButton(FlipConsole::eSound);
if (m_player) m_player->stop();
if (m_flipConsole->isChecked(FlipConsole::eDefineLoadBox))
m_flipConsole->pressButton(FlipConsole::eDefineLoadBox);
if (m_flipConsole->isChecked(FlipConsole::eUseLoadBox))
m_flipConsole->pressButton(FlipConsole::eUseLoadBox);
m_flipConsole->enableButton(FlipConsole::eDefineLoadBox, true);
m_flipConsole->enableButton(FlipConsole::eUseLoadBox, true);
m_lr = TLevelReaderP();
m_dim = TDimension();
m_loadbox = TRect();
m_loadboxes.clear();
// m_lastViewedFrame = -1;
// TImageCache::instance()->remove(toString(m_poolIndex) + "lastFlipFrame");
m_flipConsole->enableProgressBar(false);
m_flipConsole->setProgressBarStatus(0);
m_flipConsole->setFrameRange(1, 1, 1);
setTitle(tr("Flipbook"));
parentWidget()->setWindowTitle(m_title);
update();
}
//-------------------------------------------------------------------
void FlipBook::showEvent(QShowEvent *e) {
TSceneHandle *sceneHandle = TApp::instance()->getCurrentScene();
connect(sceneHandle, SIGNAL(sceneChanged()), m_imageViewer, SLOT(update()));
// for updating the blank frame button
if (!m_imageViewer->isColorModel()) {
connect(sceneHandle, SIGNAL(preferenceChanged(const QString &)),
m_flipConsole, SLOT(onPreferenceChanged(const QString &)));
m_flipConsole->onPreferenceChanged("");
}
m_flipConsole->setActive(true);
m_imageViewer->update();
}
//-------------------------------------------------------------------
void FlipBook::hideEvent(QHideEvent *e) {
TSceneHandle *sceneHandle = TApp::instance()->getCurrentScene();
disconnect(sceneHandle, SIGNAL(sceneChanged()), m_imageViewer,
SLOT(update()));
if (!m_imageViewer->isColorModel()) {
disconnect(sceneHandle, SIGNAL(preferenceChanged(const QString &)),
m_flipConsole, SLOT(onPreferenceChanged(const QString &)));
}
m_flipConsole->setActive(false);
}
//-----------------------------------------------------------------------------
void FlipBook::resizeEvent(QResizeEvent *e) { schedulePreviewedFxUpdate(); }
//-----------------------------------------------------------------------------
void FlipBook::adaptGeometry(const TRect &interestingImgRect,
const TRect &imgRect) {
TRectD imgRectD(imgRect.x0, imgRect.y0, imgRect.x1 + 1, imgRect.y1 + 1);
TRectD interestingImgRectD(interestingImgRect.x0, interestingImgRect.y0,
interestingImgRect.x1 + 1,
interestingImgRect.y1 + 1);
TAffine toWidgetRef(m_imageViewer->getImgToWidgetAffine(imgRectD));
TRectD interestGeomD(toWidgetRef * interestingImgRectD);
TRectD imageGeomD(toWidgetRef * imgRectD);
adaptWidGeometry(
TRect(tceil(interestGeomD.x0), tceil(interestGeomD.y0),
tfloor(interestGeomD.x1) - 1, tfloor(interestGeomD.y1) - 1),
TRect(tceil(imageGeomD.x0), tceil(imageGeomD.y0),
tfloor(imageGeomD.x1) - 1, tfloor(imageGeomD.y1) - 1),
true);
}
//-----------------------------------------------------------------------------
/*! When Fx preview is called without the subcamera, render the full region
of camera by resize flipbook and zoom-out the rendered image.
*/
void FlipBook::adaptGeometryForFullPreview(const TRect &imgRect) {
TRectD imgRectD(imgRect.x0, imgRect.y0, imgRect.x1 + 1, imgRect.y1 + 1);
// Get screen geometry
TPanel *panel = static_cast<TPanel *>(parentWidget());
if (!panel->isFloating()) return;
QDesktopWidget *desk =
static_cast<QApplication *>(QApplication::instance())->desktop();
QRect screenGeom = desk->availableGeometry(panel);
while (1) {
TAffine toWidgetRef(m_imageViewer->getImgToWidgetAffine(imgRectD));
TRectD imageGeomD(toWidgetRef * imgRectD);
TRect imageGeom(tceil(imageGeomD.x0) - 1, tceil(imageGeomD.y0) - 1,
tfloor(imageGeomD.x1) + 1, tfloor(imageGeomD.y1) + 1);
if (imageGeom.getLx() <= screenGeom.width() &&
imageGeom.getLy() <= screenGeom.height()) {
adaptWidGeometry(imageGeom, imageGeom, false);
break;
} else
m_imageViewer->zoomQt(false, false);
}
}
//-----------------------------------------------------------------------------
//! Adapts panel geometry to that of passed rect.
void FlipBook::adaptWidGeometry(const TRect &interestWidGeom,
const TRect &imgWidGeom, bool keepPosition) {
TPanel *panel = static_cast<TPanel *>(parentWidget());
if (!panel->isFloating()) return;
// Extract image position in screen coordinates
QRect qgeom(interestWidGeom.x0, interestWidGeom.y0, interestWidGeom.getLx(),
interestWidGeom.getLy());
QRect interestGeom(m_imageViewer->mapToGlobal(qgeom.topLeft()),
m_imageViewer->mapToGlobal(qgeom.bottomRight()));
qgeom = QRect(imgWidGeom.x0, imgWidGeom.y0, imgWidGeom.getLx(),
imgWidGeom.getLy());
QRect imageGeom(m_imageViewer->mapToGlobal(qgeom.topLeft()),
m_imageViewer->mapToGlobal(qgeom.bottomRight()));
// qDebug("tgeom= [%d, %d] x [%d, %d]", tgeom.x0, tgeom.x1, tgeom.y0,
// tgeom.y1);
// qDebug("imagegeom= [%d, %d] x [%d, %d]", imageGeom.left(),
// imageGeom.right(),
// imageGeom.top(), imageGeom.bottom());
// Get screen geometry
QDesktopWidget *desk =
static_cast<QApplication *>(QApplication::instance())->desktop();
QRect screenGeom = desk->availableGeometry(panel);
// Get panel margin measures
QRect margins;
QRect currView(m_imageViewer->geometry());
currView.moveTo(m_imageViewer->mapToGlobal(currView.topLeft()));
QRect panelGeom(panel->geometry());
margins.setLeft(panelGeom.left() - currView.left());
margins.setRight(panelGeom.right() - currView.right());
margins.setTop(panelGeom.top() - currView.top());
margins.setBottom(panelGeom.bottom() - currView.bottom());
// Build the minimum flipbook geometry. Adjust the interesting geometry
// according to it.
QSize flipMinimumSize(panel->minimumSize());
flipMinimumSize -=
QSize(margins.right() - margins.left(), margins.bottom() - margins.top());
QSize minAddition(
tceil(std::max(0, flipMinimumSize.width() - interestGeom.width()) * 0.5),
tceil(std::max(0, flipMinimumSize.height() - interestGeom.height()) *
0.5));
interestGeom.adjust(-minAddition.width(), -minAddition.height(),
minAddition.width(), minAddition.height());
// Translate to keep the current view top-left corner, if required
if (keepPosition) {
QPoint shift(currView.topLeft() - interestGeom.topLeft());
interestGeom.translate(shift);
imageGeom.translate(shift);
}
// Intersect with the screen geometry
QRect newViewerGeom(screenGeom);
newViewerGeom.adjust(-margins.left(), -margins.top(), -margins.right(),
-margins.bottom());
// when fx previewing in full size (i.e. keepPosition is false ),
// try to translate geometry and keep the image inside the viewer as much as
// posiible
if (keepPosition)
newViewerGeom &= interestGeom;
else if (newViewerGeom.intersects(interestGeom)) {
int d_ns = 0;
int d_ew = 0;
if (interestGeom.top() < newViewerGeom.top())
d_ns = newViewerGeom.top() - interestGeom.top();
else if (interestGeom.bottom() > newViewerGeom.bottom())
d_ns = newViewerGeom.bottom() - interestGeom.bottom();
if (interestGeom.left() < newViewerGeom.left())
d_ew = newViewerGeom.left() - interestGeom.left();
else if (interestGeom.right() > newViewerGeom.right())
d_ew = newViewerGeom.right() - interestGeom.right();
if (d_ns || d_ew) {
interestGeom.translate(d_ew, d_ns);
imageGeom.translate(d_ew, d_ns);
}
newViewerGeom &= interestGeom;
}
// qDebug("new Viewer= [%d, %d] x [%d, %d]", newViewerGeom.left(),
// newViewerGeom.right(),
// newViewerGeom.top(), newViewerGeom.bottom());
// Calculate the pan of content image in order to compensate for our geometry
// change
QPointF imageGeomCenter((imageGeom.left() + imageGeom.right() + 1) * 0.5,
(imageGeom.top() + imageGeom.bottom() + 1) * 0.5);
QPointF newViewerGeomCenter(
(newViewerGeom.left() + newViewerGeom.right() + 1) * 0.5,
(newViewerGeom.top() + newViewerGeom.bottom() + 1) * 0.5);
/*QPointF imageGeomCenter(
(imageGeom.width()) * 0.5,
(imageGeom.height()) * 0.5
);
QPointF newViewerGeomCenter(
(newViewerGeom.width()) * 0.5,
(newViewerGeom.height()) * 0.5
);*/
// NOTE: If delta == (0,0) the image is at center. Typically happens when
// imageGeom doesn't intersect
// the screen geometry.
QPointF delta(imageGeomCenter - newViewerGeomCenter);
TAffine aff(m_imageViewer->getViewAff());
aff.a13 = delta.x();
aff.a23 = -delta.y();
// Calculate new panel geometry
newViewerGeom.adjust(margins.left(), margins.top(), margins.right(),
margins.bottom());
// Apply changes
m_imageViewer->setViewAff(aff);
panel->setGeometry(newViewerGeom);
}
//-----------------------------------------------------------------------------
void FlipBook::onDoubleClick(QMouseEvent *me) {
TImageP img(m_imageViewer->getImage());
if (!img) return;
TAffine toWidgetRef(m_imageViewer->getImgToWidgetAffine());
TRectD pixGeomD(TScale(1.0 / (double)getDevicePixelRatio(this)) *
toWidgetRef * getImageBoundsD(img));
// TRectD pixGeomD(toWidgetRef * getImageBoundsD(img));
TRect pixGeom(tceil(pixGeomD.x0), tceil(pixGeomD.y0), tfloor(pixGeomD.x1) - 1,
tfloor(pixGeomD.y1) - 1);
// NOTE: The previous line has ceils and floor inverted on purpose. The reason
// is the following:
// As the viewer's zoom level is arbitrary, the image is likely to have a not
// integer geometry
// with respect to the widget - the problem is, we cannot take the closest
// integer rect ENCLOSING ours,
// or the ImageViewer class adds blank lines on image rendering.
// So, we do the converse - take the closest ENCLOSED one - eventually to be
// compensated when
// performing the inverse.
adaptWidGeometry(pixGeom, pixGeom, false);
}
//-----------------------------------------------------------------------------
void FlipBook::minimize(bool doMinimize) {
m_imageViewer->setVisible(!doMinimize);
m_flipConsole->showHideAllParts(!doMinimize);
}
//-----------------------------------------------------------------------------
/*! When viewing the tlv, try to cache all frames at the beginning.
NOTE : fromFrame and toFrame are frame numbers displayed on the flipbook
*/
void FlipBook::loadAndCacheAllTlvImages(Level level, int fromFrame,
int toFrame) {
TFilePath fp = level.m_fp;
if (!m_lr || (fp != m_lr->getFilePath())) m_lr = TLevelReaderP(fp);
if (!m_lr) return;
// show the wait cursor when loading a level with more than 50 frames
if (toFrame - fromFrame > 50) QApplication::setOverrideCursor(Qt::WaitCursor);
int lx = 0, oriLx = 0;
if (m_lr->getImageInfo()) lx = oriLx = m_lr->getImageInfo()->m_lx;
std::string fileName = toQString(fp.withoutParentDir()).toStdString();
for (int f = fromFrame; f <= toFrame; f++) {
TFrameId fid = level.flipbookIndexToLevelFrame(f);
if (fid == TFrameId()) continue;
std::string id =
fileName + fid.expand(TFrameId::NO_PAD) + ::to_string(this);
TImageReaderP ir = m_lr->getFrameReader(fid);
ir->setShrink(m_shrink);
TImageP img = ir->load();
if (!img) continue;
TToonzImageP ti = ((TToonzImageP)img);
if (!ti) continue;
if (ti->getCMapped()->getWrap() > ti->getCMapped()->getLx())
ti->setCMapped(ti->getCMapped()->clone());
if (m_shrink > 1 && (lx == 0 || ti->getRaster()->getLx() == lx))
ti->setCMapped(TRop::shrink(ti->getRaster(), m_shrink));
TPalette *palette = img->getPalette();
if (m_palette && (!palette || palette != m_palette))
img->setPalette(m_palette);
TImageCache::instance()->add(id, img);
m_loadboxes[id] = TRect();
}
m_lr = TLevelReaderP();
// revert the cursor
if (toFrame - fromFrame > 50) QApplication::restoreOverrideCursor();
}
//=============================================================================
// Utility
//-----------------------------------------------------------------------------
//! Displays the passed file on a Flipbook, supporting a wide range of options.
//! Possible options include:
//! \li The range, step and shrink parameters for the loaded level
//! \li A soundtrack to accompany the level's images
//! \li The flipbook where the file is to be opened. If none, a new one is
//! created.
//! \li Whether the level must replace an existing one on the flipbook, or it
//! must
//! rather be appended at its end
//! \li In case the file has a movie format and it is known to be a toonz
//! output,
//! some additional random access information may be retrieved (i.e. images may
//! map
//! to specific frames).
// returns pointer to the opened flipbook to control modality.
FlipBook *viewFile(const TFilePath &path, int from, int to, int step,
int shrink, TSoundTrack *snd, FlipBook *flipbook,
bool append, bool isToonzOutput) {
// In case the step and shrink information are invalid, load them from
// preferences
if (step == -1 || shrink == -1) {
int _step = 1, _shrink = 1;
Preferences::instance()->getViewValues(_shrink, _step);
if (step == -1) step = _step;
if (shrink == -1) shrink = _shrink;
}
// Movie files must not have the ".." extension
if ((path.getType() == "avi") &&
path.isLevelName()) {
DVGui::warning(QObject::tr("%1 has an invalid extension format.")
.arg(QString::fromStdString(path.getLevelName())));
return NULL;
}
// Windows Screen Saver - avoid
if (path.getType() == "scr") return NULL;
// Avi and movs may be viewed by an external viewer, depending on preferences
if ((path.getType() == "avi") && !flipbook) {
QString str;
QSettings().value("generatedMovieViewEnabled", str);
if (str.toInt() != 0) {
TSystem::showDocument(path);
return NULL;
}
}
// Retrieve a blank flipbook
if (!flipbook)
flipbook = FlipBookPool::instance()->pop();
else if (!append)
flipbook->reset();
// Assign the passed level with associated infos
flipbook->setLevel(path, 0, from, to, step, shrink, snd, append,
isToonzOutput);
return flipbook;
}
//-----------------------------------------------------------------------------
| 32.918394 | 80 | 0.585908 | [
"mesh",
"geometry",
"render",
"object",
"vector",
"model"
] |
7324c594696eeda780a1727bb4543eb882c415bc | 1,541 | cpp | C++ | src/core/cons_object.cpp | trukanduk/lispp | 9fe4564b2197ae216214fa0408f1e5c4c5105237 | [
"MIT"
] | null | null | null | src/core/cons_object.cpp | trukanduk/lispp | 9fe4564b2197ae216214fa0408f1e5c4c5105237 | [
"MIT"
] | null | null | null | src/core/cons_object.cpp | trukanduk/lispp | 9fe4564b2197ae216214fa0408f1e5c4c5105237 | [
"MIT"
] | null | null | null | #include <lispp/cons_object.h>
#include <lispp/scope.h>
#include <lispp/callable_object.h>
namespace lispp {
bool ConsObject::operator==(const Object& other) const {
const auto* other_cons = other.as_cons();
return (other_cons != nullptr &&
left_value_.safe_equal(other_cons->left_value_) &&
right_value_.safe_equal(other_cons->right_value_));
}
std::string ConsObject::to_string() const {
if (!left_value_.valid() && !right_value_.valid()) {
return "()";
} else {
std::stringstream ss;
ss << "(";
print_as_tail(ss);
return ss.str();
}
}
ObjectPtr<> ConsObject::eval(const std::shared_ptr<Scope>& scope) {
if (!left_value_.valid()) {
throw ExecutionError("Cannot execute empty list");
}
ObjectPtr<> evaled_value(left_value_->eval(scope));
if (!evaled_value.valid()) {
throw ExecutionError(left_value_->to_string() + " is not callable");
}
ObjectPtr<CallableObject> callable(evaled_value->as_callable());
if (!callable.valid()) {
throw ExecutionError(evaled_value->to_string() + " is not callable");
}
return callable->execute(scope, right_value_);
}
void ConsObject::print_as_tail(std::ostream& out) const {
out << (left_value_.valid() ? left_value_->to_string() : "nil");
if (!right_value_.valid()) {
out << ")";
} else if (right_value_->as_cons()) {
out << " ";
right_value_->as_cons()->print_as_tail(out);
} else {
out << " . " << (right_value_.valid() ? right_value_->to_string() : "nil")
<< ")";
}
}
} // lispp
| 26.118644 | 78 | 0.646982 | [
"object"
] |
73295946b1e051050fa2564ea081b37c11355e49 | 12,151 | hpp | C++ | tlx/container/d_ary_addressable_int_heap.hpp | mullovc/tlx | e7c17b5981cbd7912b689fa0ad993e18424e26fe | [
"BSL-1.0"
] | 284 | 2017-02-26T08:49:15.000Z | 2022-03-30T21:55:37.000Z | tlx/container/d_ary_addressable_int_heap.hpp | xiao2mo/tlx | b311126e670753897c1defceeaa75c83d2d9531a | [
"BSL-1.0"
] | 24 | 2017-09-05T21:02:41.000Z | 2022-03-07T10:09:59.000Z | tlx/container/d_ary_addressable_int_heap.hpp | xiao2mo/tlx | b311126e670753897c1defceeaa75c83d2d9531a | [
"BSL-1.0"
] | 62 | 2017-02-23T12:29:27.000Z | 2022-03-31T07:45:59.000Z | /*******************************************************************************
* tlx/container/d_ary_addressable_int_heap.hpp
*
* Part of tlx - http://panthema.net/tlx
*
* Copyright (C) 2019 Eugenio Angriman <angrimae@hu-berlin.de>
* Copyright (C) 2019 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the Boost Software License, Version 1.0
******************************************************************************/
#ifndef TLX_CONTAINER_D_ARY_ADDRESSABLE_INT_HEAP_HEADER
#define TLX_CONTAINER_D_ARY_ADDRESSABLE_INT_HEAP_HEADER
#include <cassert>
#include <cstddef>
#include <functional>
#include <limits>
#include <queue>
#include <vector>
namespace tlx {
//! \addtogroup tlx_container
//! \{
/*!
* This class implements an addressable integer priority queue, precisely a
* d-ary heap.
*
* Keys must be unique unsigned integers. The addressable heap holds an array
* indexed by the keys, hence it requires a multiple of the highest integer key
* as space!
*
* \tparam KeyType Has to be an unsigned integer type.
* \tparam Arity A positive integer.
* \tparam Compare Function object.
*/
template <typename KeyType, unsigned Arity = 2,
class Compare = std::less<KeyType> >
class DAryAddressableIntHeap
{
static_assert(std::numeric_limits<KeyType>::is_integer &&
!std::numeric_limits<KeyType>::is_signed,
"KeyType must be an unsigned integer type.");
static_assert(Arity, "Arity must be greater than zero.");
public:
using key_type = KeyType;
using compare_type = Compare;
static constexpr size_t arity = Arity;
protected:
//! Cells in the heap.
std::vector<key_type> heap_;
//! Positions of the keys in the heap vector.
std::vector<key_type> handles_;
//! Compare function.
compare_type cmp_;
//! Marks a key that is not in the heap.
static constexpr key_type not_present() {
return static_cast<key_type>(-1);
}
public:
//! Allocates an empty heap.
explicit DAryAddressableIntHeap(compare_type cmp = compare_type())
: heap_(0), handles_(0), cmp_(cmp) { }
//! Allocates space for \c new_size items.
void reserve(size_t new_size) {
if (handles_.size() < new_size) {
handles_.resize(new_size, not_present());
heap_.reserve(new_size);
}
}
//! Copy.
DAryAddressableIntHeap(const DAryAddressableIntHeap&) = default;
DAryAddressableIntHeap& operator = (const DAryAddressableIntHeap&) = default;
//! Move.
DAryAddressableIntHeap(DAryAddressableIntHeap&&) = default;
DAryAddressableIntHeap& operator = (DAryAddressableIntHeap&&) = default;
//! Empties the heap.
void clear() {
std::fill(handles_.begin(), handles_.end(), not_present());
heap_.clear();
}
//! Returns the number of items in the heap.
size_t size() const noexcept { return heap_.size(); }
//! Returns the capacity of the heap.
size_t capacity() const noexcept { return heap_.capacity(); }
//! Returns true if the heap has no items, false otherwise.
bool empty() const noexcept { return heap_.empty(); }
//! Inserts a new item.
void push(const key_type& new_key) {
// Avoid to add the key that we use to mark non present keys.
assert(new_key != not_present());
if (new_key >= handles_.size()) {
handles_.resize(new_key + 1, not_present());
}
else {
assert(handles_[new_key] == not_present());
}
// Insert the new item at the end of the heap.
handles_[new_key] = static_cast<key_type>(heap_.size());
heap_.push_back(new_key);
sift_up(heap_.size() - 1);
}
//! Inserts a new item.
void push(key_type&& new_key) {
// Avoid to add the key that we use to mark non present keys.
assert(new_key != not_present());
if (new_key >= handles_.size()) {
handles_.resize(new_key + 1, not_present());
}
else {
assert(handles_[new_key] == not_present());
}
// Insert the new item at the end of the heap.
handles_[new_key] = static_cast<key_type>(heap_.size());
heap_.push_back(std::move(new_key));
sift_up(heap_.size() - 1);
}
//! Removes the item with key \c key.
void remove(key_type key) {
assert(contains(key));
key_type h = handles_[key];
std::swap(heap_[h], heap_.back());
handles_[heap_[h]] = h;
handles_[heap_.back()] = not_present();
heap_.pop_back();
// If we did not remove the last item in the heap vector.
if (h < size()) {
if (h && cmp_(heap_[h], heap_[parent(h)])) {
sift_up(h);
}
else {
sift_down(h);
}
}
}
//! Returns the top item.
const key_type& top() const noexcept {
assert(!empty());
return heap_[0];
}
//! Removes the top item.
void pop() { remove(heap_[0]); }
//! Removes and returns the top item.
key_type extract_top() {
key_type top_item = top();
pop();
return top_item;
}
//! Rebuilds the heap.
void update_all() {
heapify();
}
/*!
* Updates the priority queue after the priority associated to the item with
* key \c key has been changed; if the key \c key is not present in the
* priority queue, it will be added.
*
* Note: if not called after a priority is changed, the behavior of the data
* structure is undefined.
*/
void update(key_type key) {
if (key >= handles_.size() || handles_[key] == not_present()) {
push(key);
}
else if (handles_[key] &&
cmp_(heap_[handles_[key]], heap_[parent(handles_[key])])) {
sift_up(handles_[key]);
}
else {
sift_down(handles_[key]);
}
}
//! Returns true if the key \c key is in the heap, false otherwise.
bool contains(key_type key) const {
return key < handles_.size() ? handles_[key] != not_present() : false;
}
//! Builds a heap from a container.
template <class InputIterator>
void build_heap(InputIterator first, InputIterator last) {
heap_.assign(first, last);
heapify();
}
//! Builds a heap from the vector \c keys. Items of \c keys are copied.
void build_heap(const std::vector<key_type>& keys) {
heap_.resize(keys.size());
std::copy(keys.begin(), keys.end(), heap_.begin());
heapify();
}
//! Builds a heap from the vector \c keys. Items of \c keys are moved.
void build_heap(std::vector<key_type>&& keys) {
if (!empty())
heap_.clear();
heap_ = std::move(keys);
heapify();
}
//! For debugging: runs a BFS from the root node and verifies that the heap
//! property is respected.
bool sanity_check() {
if (empty()) {
return true;
}
std::vector<unsigned char> mark(handles_.size());
std::queue<size_t> q;
// Explore from the root.
q.push(0);
// mark first value as seen
mark.at(heap_[0]) = 1;
while (!q.empty()) {
size_t s = q.front();
q.pop();
size_t l = left(s);
for (size_t i = 0; i < arity && l < heap_.size(); ++i) {
// check that the priority of the children is not strictly less
// than their parent.
if (cmp_(heap_[l], heap_[s]))
return false;
// check handle
if (handles_[heap_[l]] != l)
return false;
// mark value as seen
mark.at(heap_[l]) = 1;
q.push(l++);
}
}
// check not_present handles
for (size_t i = 0; i < mark.size(); ++i) {
if (mark[i] != (handles_[i] != not_present()))
return false;
}
return true;
}
private:
//! Returns the position of the left child of the node at position \c k.
size_t left(size_t k) const { return arity * k + 1; }
//! Returns the position of the parent of the node at position \c k.
size_t parent(size_t k) const { return (k - 1) / arity; }
//! Pushes the node at position \c k up until either it becomes the root or
//! its parent has lower or equal priority.
void sift_up(size_t k) {
key_type value = std::move(heap_[k]);
size_t p = parent(k);
while (k > 0 && !cmp_(heap_[p], value)) {
heap_[k] = std::move(heap_[p]);
handles_[heap_[k]] = k;
k = p, p = parent(k);
}
handles_[value] = k;
heap_[k] = std::move(value);
}
//! Pushes the item at position \c k down until either it becomes a leaf or
//! all its children have higher priority
void sift_down(size_t k) {
key_type value = std::move(heap_[k]);
while (true) {
size_t l = left(k);
if (l >= heap_.size()) {
break;
}
// Get the min child.
size_t c = l;
size_t right = std::min(heap_.size(), c + arity);
while (++l < right) {
if (cmp_(heap_[l], heap_[c])) {
c = l;
}
}
// Current item has lower or equal priority than the child with
// minimum priority, stop.
if (!cmp_(heap_[c], value)) {
break;
}
// Swap current item with the child with minimum priority.
heap_[k] = std::move(heap_[c]);
handles_[heap_[k]] = k;
k = c;
}
handles_[value] = k;
heap_[k] = std::move(value);
}
//! Reorganize heap_ into a heap.
void heapify() {
key_type max_key = heap_.empty() ? 0 : heap_.front();
if (heap_.size() >= 2) {
// Iterate from the last internal node up to the root.
size_t last_internal = (heap_.size() - 2) / arity;
for (size_t i = last_internal + 1; i; --i) {
// Index of the current internal node.
size_t cur = i - 1;
key_type value = std::move(heap_[cur]);
max_key = std::max(max_key, value);
do {
size_t l = left(cur);
max_key = std::max(max_key, heap_[l]);
// Find the minimum child of cur.
size_t min_elem = l;
for (size_t j = l + 1;
j - l < arity && j < heap_.size(); ++j) {
if (cmp_(heap_[j], heap_[min_elem]))
min_elem = j;
max_key = std::max(max_key, heap_[j]);
}
// One of the children of cur is less then cur: swap and
// do another iteration.
if (cmp_(heap_[min_elem], value)) {
heap_[cur] = std::move(heap_[min_elem]);
cur = min_elem;
}
else
break;
} while (cur <= last_internal);
heap_[cur] = std::move(value);
}
}
// initialize handles_ vector
handles_.resize(std::max(handles_.size(), static_cast<size_t>(max_key) + 1), not_present());
for (size_t i = 0; i < heap_.size(); ++i)
handles_[heap_[i]] = i;
}
};
//! make template alias due to similarity with std::priority_queue
template <typename KeyType, unsigned Arity = 2,
typename Compare = std::less<KeyType> >
using d_ary_addressable_int_heap =
DAryAddressableIntHeap<KeyType, Arity, Compare>;
//! \}
} // namespace tlx
#endif // !TLX_CONTAINER_D_ARY_ADDRESSABLE_INT_HEAP_HEADER
/******************************************************************************/
| 32.489305 | 100 | 0.536581 | [
"object",
"vector"
] |
732a5855ede2b75d377d1a967f1872ed3affaebf | 3,947 | hpp | C++ | include/bvh/node_intersectors.hpp | chenjianxing1/bvh | bbe05161cec4fef7126ae490df49c05dec22a4fe | [
"MIT"
] | 1 | 2020-12-28T06:47:32.000Z | 2020-12-28T06:47:32.000Z | include/bvh/node_intersectors.hpp | chenjianxing1/bvh | bbe05161cec4fef7126ae490df49c05dec22a4fe | [
"MIT"
] | null | null | null | include/bvh/node_intersectors.hpp | chenjianxing1/bvh | bbe05161cec4fef7126ae490df49c05dec22a4fe | [
"MIT"
] | null | null | null | #ifndef BVH_NODE_INTERSECTORS_HPP
#define BVH_NODE_INTERSECTORS_HPP
#include <cmath>
#include "bvh/vector.hpp"
#include "bvh/ray.hpp"
#include "bvh/platform.hpp"
#include "bvh/utilities.hpp"
namespace bvh {
/// Base class for ray-node intersection algorithms. Does ray octant classification.
template <typename Bvh, typename Derived>
struct NodeIntersector {
using Scalar = typename Bvh::ScalarType;
std::array<int, 3> octant;
NodeIntersector(const Ray<Scalar>& ray)
: octant {
std::signbit(ray.direction[0]),
std::signbit(ray.direction[1]),
std::signbit(ray.direction[2])
}
{}
template <bool IsMin>
bvh__always_inline__
Scalar intersect_axis(int axis, const Vector3<Scalar>& p, const Ray<Scalar>& ray) const {
return static_cast<const Derived*>(this)->template intersect_axis<IsMin>(axis, p, ray);
}
bvh__always_inline__
std::pair<Scalar, Scalar> intersect(const typename Bvh::Node& node, const Ray<Scalar>& ray) const {
Vector3<Scalar> entry, exit;
entry[0] = intersect_axis<true >(0, node.bounds[0 * 2 + octant[0]], ray);
entry[1] = intersect_axis<true >(1, node.bounds[1 * 2 + octant[1]], ray);
entry[2] = intersect_axis<true >(2, node.bounds[2 * 2 + octant[2]], ray);
exit [0] = intersect_axis<false>(0, node.bounds[0 * 2 + 1 - octant[0]], ray);
exit [1] = intersect_axis<false>(1, node.bounds[1 * 2 + 1 - octant[1]], ray);
exit [2] = intersect_axis<false>(2, node.bounds[2 * 2 + 1 - octant[2]], ray);
// Note: This order for the min/max operations is guaranteed not to produce NaNs
return std::make_pair(
robust_max(entry[0], robust_max(entry[1], robust_max(entry[2], ray.tmin))),
robust_min(exit [0], robust_min(exit [1], robust_min(exit [2], ray.tmax))));
}
protected:
~NodeIntersector() {}
};
/// Fully robust ray-node intersection algorithm (see "Robust BVH Ray Traversal", by T. Ize).
template <typename Bvh>
struct RobustNodeIntersector : public NodeIntersector<Bvh, RobustNodeIntersector<Bvh>> {
using Scalar = typename Bvh::ScalarType;
// Padded inverse direction to avoid false-negatives in the ray-node test.
Vector3<Scalar> padded_inverse_direction;
Vector3<Scalar> inverse_direction;
RobustNodeIntersector(const Ray<Scalar>& ray)
: NodeIntersector<Bvh, RobustNodeIntersector<Bvh>>(ray)
{
inverse_direction = ray.direction.inverse();
padded_inverse_direction = Vector3<Scalar>(
add_ulp_magnitude(inverse_direction[0], 2),
add_ulp_magnitude(inverse_direction[1], 2),
add_ulp_magnitude(inverse_direction[2], 2));
}
template <bool IsMin>
bvh__always_inline__
Scalar intersect_axis(int axis, const Vector3<Scalar>& p, const Ray<Scalar>& ray) const {
return (p[axis] - ray.origin[axis]) * (IsMin ? inverse_direction[axis] : padded_inverse_direction[axis]);
}
using NodeIntersector<Bvh, RobustNodeIntersector<Bvh>>::intersect;
};
/// Semi-robust, fast ray-node intersection algorithm.
template <typename Bvh>
struct FastNodeIntersector : public NodeIntersector<Bvh, FastNodeIntersector<Bvh>> {
using Scalar = typename Bvh::ScalarType;
Vector3<Scalar> scaled_origin;
Vector3<Scalar> inverse_direction;
FastNodeIntersector(const Ray<Scalar>& ray)
: NodeIntersector<Bvh, FastNodeIntersector<Bvh>>(ray)
{
inverse_direction = ray.direction.safe_inverse();
scaled_origin = -ray.origin * inverse_direction;
}
template <bool>
bvh__always_inline__
Scalar intersect_axis(int axis, const Vector3<Scalar>& p, const Ray<Scalar>&) const {
return fast_multiply_add(p[axis], inverse_direction[axis], scaled_origin[axis]);
}
using NodeIntersector<Bvh, FastNodeIntersector<Bvh>>::intersect;
};
} // namespace bvh
#endif
| 36.546296 | 113 | 0.675703 | [
"vector"
] |
732b5b2215b5e56317d986b2f325a9c53315f319 | 954 | cpp | C++ | app/src/TableView.cpp | Hvvang/uTag | c2a1e0197acce94b93791e197c3bfbaf26bce980 | [
"MIT"
] | 1 | 2020-10-16T00:45:28.000Z | 2020-10-16T00:45:28.000Z | app/src/TableView.cpp | Hvvang/uTag | c2a1e0197acce94b93791e197c3bfbaf26bce980 | [
"MIT"
] | null | null | null | app/src/TableView.cpp | Hvvang/uTag | c2a1e0197acce94b93791e197c3bfbaf26bce980 | [
"MIT"
] | null | null | null | #include "TableView.h"
#include "FileTable.h"
TableView::TableView(QWidget *parent) :
QTableView(parent) {}
void TableView::commitData(QWidget *editor) {
QAbstractItemView::commitData(editor);
auto value = this->model()->data(this->currentIndex(), Qt::EditRole);
auto currCol = this->currentIndex().column();
auto currRow = this->currentIndex().row();
if (QFileInfo(model()->data(model()->index(this->currentIndex().row(), 4)).toString()).isWritable()) {
QModelIndexList selection = this->selectionModel()->selectedRows();
for(int i = 0; i < selection.count(); ++i) {
auto row = selection.at(i).row();
if (row != currRow) {
QModelIndex idx = model()->index(row, currCol);
if (QFileInfo(model()->data(model()->index(row, 4)).toString()).isWritable())
this->model()->setData(idx, value, Qt::EditRole);
}
}
}
}
| 34.071429 | 106 | 0.58805 | [
"model"
] |
73323acd68c2ee548bfa586d57b4b0d5b3e3bbf7 | 25,288 | cpp | C++ | planning/MotionPlanner.cpp | smeng9/KrisLibrary | 4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add | [
"BSD-3-Clause"
] | 57 | 2015-05-07T18:07:11.000Z | 2022-03-18T18:44:39.000Z | planning/MotionPlanner.cpp | smeng9/KrisLibrary | 4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add | [
"BSD-3-Clause"
] | 7 | 2018-12-10T21:46:52.000Z | 2022-01-20T19:49:11.000Z | planning/MotionPlanner.cpp | smeng9/KrisLibrary | 4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add | [
"BSD-3-Clause"
] | 36 | 2015-01-10T18:36:45.000Z | 2022-01-20T19:49:24.000Z | #include <KrisLibrary/Logger.h>
#include "MotionPlanner.h"
#include "PointLocation.h"
#include "Objective.h"
#include <graph/Path.h>
#include <graph/ShortestPaths.h>
#include <math/random.h>
#include <errors.h>
typedef TreeRoadmapPlanner::Node Node;
using namespace std;
//Graph search callbacks
class EdgeDistance
{
public:
Real operator () (const EdgePlannerPtr& e,int s,int t)
{
if(!e) return 1.0; //this must be a lazy planner
Real res = e->Length();
if(res <= 0) {
LOG4CXX_WARN(KrisLibrary::logger(),"RoadmapPlanner: Warning, edge has nonpositive length "<<res);
return Epsilon;
}
return res;
}
};
class EdgeObjectiveCost
{
public:
ObjectiveFunctionalBase* objective;
int terminalNode; //the indicator for the special terminal node
EdgeObjectiveCost(ObjectiveFunctionalBase* _objective,int _terminalNode=-1)
:objective(_objective),terminalNode(_terminalNode)
{}
Real operator () (const EdgePlannerPtr& e,int s,int t)
{
if(!e) return 1.0; //this must be a lazy planner
if(t==terminalNode)
return objective->TerminalCost(e->Start());
return objective->IncrementalCost(e.get());
}
};
// SetComponentCallback: sets all components to c
struct SetComponentCallback : public Node::Callback
{
SetComponentCallback(int c) { component = c; }
virtual void Visit(Node* n) { n->connectedComponent = component; }
int component;
};
// ClosestMilestoneCallback: finds the closest milestone to x
struct ClosestMilestoneCallback : public Node::Callback
{
ClosestMilestoneCallback(CSpace* s,const Config& _x)
:space(s),closestDistance(Inf),x(_x),closestMilestone(NULL)
{}
virtual void Visit(Node* n) {
Real d = space->Distance(n->x,x);
if(d < closestDistance) {
closestDistance = d;
closestMilestone = n;
}
}
CSpace* space;
Real closestDistance;
const Config& x;
Node* closestMilestone;
};
RoadmapPlanner::RoadmapPlanner(CSpace* s)
:space(s)
{
pointLocator = make_shared<NaivePointLocation>(roadmap.nodes,s);
}
RoadmapPlanner::~RoadmapPlanner()
{
}
void RoadmapPlanner::Cleanup()
{
roadmap.Cleanup();
ccs.Clear();
pointLocator->OnClear();
}
void RoadmapPlanner::GenerateConfig(Config& x)
{
space->Sample(x);
}
int RoadmapPlanner::AddMilestone(const Config& x)
{
ccs.AddNode();
int res=roadmap.AddNode(x);
pointLocator->OnAppend();
return res;
}
int RoadmapPlanner::TestAndAddMilestone(const Config& x)
{
if(!space->IsFeasible(x)) return -1;
return AddMilestone(x);
}
void RoadmapPlanner::ConnectEdge(int i,int j,const EdgePlannerPtr& e)
{
ccs.AddEdge(i,j);
roadmap.AddEdge(i,j,e);
}
EdgePlannerPtr RoadmapPlanner::TestAndConnectEdge(int i,int j)
{
EdgePlannerPtr e=space->LocalPlanner(roadmap.nodes[i],roadmap.nodes[j]);
if(e->IsVisible()) {
ConnectEdge(i,j,e);
return e;
}
else {
e=NULL;
return NULL;
}
}
void RoadmapPlanner::ConnectToNeighbors(int i,Real connectionThreshold,bool ccReject)
{
vector<int> nn;
vector<Real> distances;
if(pointLocator->Close(roadmap.nodes[i],connectionThreshold,nn,distances)) {
for(auto j:nn) {
if(ccReject) { if(ccs.SameComponent(i,j)) continue; }
else if(i==j || roadmap.HasEdge(i,j)) continue;
TestAndConnectEdge(i,j);
}
}
else {
//fall back on naive point location
for(size_t j=0;j<roadmap.nodes.size();j++) {
if(ccReject) { if(ccs.SameComponent(i,(int)j)) continue; }
else if(i==(int)j || roadmap.HasEdge(i,(int)j)) continue;
if(space->Distance(roadmap.nodes[i],roadmap.nodes[j]) < connectionThreshold) {
TestAndConnectEdge(i,j);
}
}
}
}
void RoadmapPlanner::ConnectToNearestNeighbors(int i,int k,bool ccReject)
{
if(k <= 0) return;
vector<int> nn;
vector<Real> distances;
if(pointLocator->KNN(roadmap.nodes[i],(ccReject?k*4:k),nn,distances)) {
//assume the k nearest neighbors are sorted by distance
int numTests=0;
for(auto j:nn) {
if(ccReject) { if(ccs.SameComponent(i,j)) continue; }
else if(i==(int)j) continue;
TestAndConnectEdge(i,j);
numTests++;
if(numTests == k) break;
}
}
else {
//fall back on naive
set<pair<Real,int> > knn;
pair<Real,int> node;
Real worst=Inf;
for(size_t j=0;j<roadmap.nodes.size();j++) {
if(ccReject) { if(ccs.SameComponent(i,(int)j)) continue; }
else if(i==(int)j) continue;
node.first = space->Distance(roadmap.nodes[i],roadmap.nodes[j]);
node.second = (int)j;
if(node.first < worst) {
knn.insert(node);
if(ccReject) { //oversample candidate nearest neighbors
if((int)knn.size() > k*4)
knn.erase(--knn.end());
}
else { //only keep k nearest neighbors
if((int)knn.size() > k)
knn.erase(--knn.end());
}
worst = (--knn.end())->first;
}
}
int numTests=0;
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
if(ccReject && ccs.SameComponent(i,j->second)) continue;
TestAndConnectEdge(i,j->second);
numTests++;
if(numTests == k) break;
}
}
}
void RoadmapPlanner::Generate(int numSamples,Real connectionThreshold)
{
Config x;
for(int i=0;i<numSamples;i++) {
GenerateConfig(x);
int node=TestAndAddMilestone(x);
if(node >= 0) ConnectToNeighbors(node,connectionThreshold);
}
}
void RoadmapPlanner::CreatePath(int i,int j,MilestonePath& path)
{
Assert(ccs.SameComponent(i,j));
//Graph::PathIntCallback callback(roadmap.nodes.size(),j);
//roadmap._BFS(i,callback);
EdgeDistance distanceWeightFunc;
Graph::ShortestPathProblem<Config,EdgePlannerPtr > spp(roadmap);
spp.InitializeSource(i);
spp.FindPath_Undirected(j,distanceWeightFunc);
if(IsInf(spp.d[j])) {
FatalError("RoadmapPlanner::CreatePath: SameComponent is true, but no shortest path?");
return;
}
list<int> nodes;
//Graph::GetAncestorPath(callback.parents,j,i,nodes);
bool res=Graph::GetAncestorPath(spp.p,j,i,nodes);
if(!res) {
FatalError("RoadmapPlanner::CreatePath: GetAncestorPath returned false");
return;
}
if(nodes.front() != i || nodes.back() != j) {
FatalError("RoadmapPlanner::CreatePath: GetAncestorPath didn't return correct path? %d to %d vs %d to %d",nodes.front(),nodes.back(),i,j);
}
Assert(nodes.front()==i);
Assert(nodes.back()==j);
path.edges.clear();
path.edges.reserve(nodes.size());
for(auto p=nodes.begin();p!=--nodes.end();++p) {
auto n=p; ++n;
EdgePlannerPtr* e=roadmap.FindEdge(*p,*n);
Assert(e);
if(*e == NULL) {
//edge data not stored
path.edges.push_back(space->LocalPlanner(roadmap.nodes[*p],roadmap.nodes[*n]));
}
else {
//edge data stored
if((*e)->Start() == roadmap.nodes[*p]) {
//path.edges.push_back((*e)->Copy());
path.edges.push_back(*e);
}
else {
Assert((*e)->End() == roadmap.nodes[*p]);
path.edges.push_back((*e)->ReverseCopy());
}
}
}
Assert(path.IsValid());
}
Real RoadmapPlanner::OptimizePath(int i,const vector<int>& goals,ObjectiveFunctionalBase* cost,MilestonePath& path)
{
path.edges.clear();
if(goals.empty())
return Inf;
Real optCost=0;
list<int> nodes;
if(goals.size()==1) {
//no need to add a special terminal node
EdgeObjectiveCost edgeCost(cost,-1);
int terminalNode = goals[0];
Graph::ShortestPathProblem<Config,EdgePlannerPtr > spp(roadmap);
spp.InitializeSource(i);
spp.FindPath_Undirected(terminalNode,edgeCost);
optCost = spp.d[terminalNode];
if(IsInf(spp.d[terminalNode])) {
return Inf;
}
bool res=Graph::GetAncestorPath(spp.p,terminalNode,i,nodes);
if(!res) {
FatalError("RoadmapPlanner::OptimizePath: GetAncestorPath returned false");
return Inf;
}
}
else {
//need to add a special terminal node, then delete it
int terminalNode = roadmap.AddNode(Vector());
for(auto g: goals) {
roadmap.AddEdge(g,terminalNode,space->PathChecker(roadmap.nodes[g],roadmap.nodes[g]));
}
EdgeObjectiveCost edgeCost(cost,terminalNode);
Graph::ShortestPathProblem<Config,EdgePlannerPtr > spp(roadmap);
spp.InitializeSource(i);
spp.FindPath_Undirected(terminalNode,edgeCost);
//delete the terminal node
roadmap.DeleteNode(terminalNode);
optCost = spp.d[terminalNode];
if(IsInf(spp.d[terminalNode])) {
return Inf;
}
bool res=Graph::GetAncestorPath(spp.p,terminalNode,i,nodes);
if(!res) {
FatalError("RoadmapPlanner::OptimizePath: GetAncestorPath returned false");
return Inf;
}
//remove terminalNode
nodes.pop_back();
}
path.edges.clear();
path.edges.reserve(nodes.size());
for(auto p=nodes.begin();p!=--nodes.end();++p) {
auto n=p; ++n;
EdgePlannerPtr* e=roadmap.FindEdge(*p,*n);
Assert(e);
if(*e == NULL) {
//edge data not stored
path.edges.push_back(space->LocalPlanner(roadmap.nodes[*p],roadmap.nodes[*n]));
}
else {
//edge data stored
if((*e)->Start() == roadmap.nodes[*p]) {
//path.edges.push_back((*e)->Copy());
path.edges.push_back(*e);
}
else {
Assert((*e)->End() == roadmap.nodes[*p]);
path.edges.push_back((*e)->ReverseCopy());
}
}
}
Assert(path.IsValid());
return optCost;
}
TreeRoadmapPlanner::TreeRoadmapPlanner(CSpace* s)
:space(s),connectionThreshold(Inf)
{
pointLocator = make_shared<NaivePointLocation>(milestoneConfigs,s);
}
TreeRoadmapPlanner::~TreeRoadmapPlanner()
{
for (size_t i = 0; i<connectedComponents.size(); i++)
SafeDelete(connectedComponents[i]);
}
void TreeRoadmapPlanner::Cleanup()
{
for(size_t i=0;i<connectedComponents.size();i++)
SafeDelete(connectedComponents[i]);
connectedComponents.clear();
milestones.clear();
milestoneConfigs.clear();
pointLocator->OnClear();
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::TestAndAddMilestone(const Config& x)
{
if(space->IsFeasible(x))
return AddMilestone(x);
else
return AddInfeasibleMilestone(x);
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::AddMilestone(const Config& x)
{
milestoneConfigs.push_back(x);
Milestone m;
m.x.setRef(milestoneConfigs.back());
m.id = (int)milestoneConfigs.size()-1;
int n=(int)connectedComponents.size();
m.connectedComponent=n;
connectedComponents.push_back(new Node(m));
milestones.push_back(connectedComponents[n]);
pointLocator->OnAppend();
return connectedComponents[n];
}
void TreeRoadmapPlanner::GenerateConfig(Config& x)
{
space->Sample(x);
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::Extend()
{
GenerateConfig(x);
Node* n=AddMilestone(x);
if(n) ConnectToNeighbors(n);
return n;
}
void TreeRoadmapPlanner::ConnectToNeighbors(Node* n)
{
if(n->connectedComponent == -1) return;
if(IsInf(connectionThreshold)==1) {
//for each other component, attempt a connection to the closest node
for(size_t i=0;i<connectedComponents.size();i++) {
if((int)i == n->connectedComponent) continue;
ClosestMilestoneCallback callback(space,n->x);
connectedComponents[i]->DFS(callback);
TryConnect(n,callback.closestMilestone);
}
}
else {
//attempt a connection between this node and all others within the
//connection threshold
vector<int> nodes;
vector<Real> distances;
pointLocator->Close(n->x,connectionThreshold,nodes,distances);
for(auto i:nodes) {
if(n->connectedComponent != milestones[i]->connectedComponent) {
TryConnect(n,milestones[i]);
}
}
}
}
EdgePlannerPtr TreeRoadmapPlanner::TryConnect(Node* a,Node* b)
{
Assert(a->connectedComponent != b->connectedComponent);
EdgePlannerPtr e=space->LocalPlanner(a->x,b->x);
if(e->IsVisible()) {
if(a->connectedComponent < b->connectedComponent) AttachChild(a,b,e);
else AttachChild(b,a,e);
return e;
}
return NULL;
}
void TreeRoadmapPlanner::AttachChild(Node* p, Node* c, const EdgePlannerPtr& e)
{
Assert(p->connectedComponent != c->connectedComponent);
if(e) Assert(e->Start() == p->x && e->End() == c->x);
connectedComponents[c->connectedComponent] = NULL;
c->reRoot();
SetComponentCallback callback(p->connectedComponent);
c->DFS(callback);
p->addChild(c);
c->edgeFromParent() = e;
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::SplitEdge(Node* p,Node* n,Real u)
{
Assert(p==n->getParent());
Vector x;
n->edgeFromParent()->Eval(u,x);
p->detachChild(n);
Node* s=Extend(p,x);
s->addChild(n);
n->edgeFromParent() = space->LocalPlanner(x,n->x);
return s;
}
void TreeRoadmapPlanner::DeleteSubtree(Node* n)
{
if(connectedComponents[n->connectedComponent] == n) {
connectedComponents[n->connectedComponent] = n->getParent();
}
Graph::TopologicalSortCallback<Node*> callback;
n->DFS(callback);
for(list<Node*>::iterator i=callback.list.begin();i!=callback.list.end();i++) {
int j=(*i)->id;
assert(milestones[j]==*i);
milestones[j]=milestones.back();
milestoneConfigs[j]=milestoneConfigs.back();
milestones.resize(milestones.size()-1);
milestoneConfigs.resize(milestoneConfigs.size()-1);
milestones[j]->id = (int)j;
milestones[j]->x.setRef(milestoneConfigs[j]);
}
//refresh the point locator
pointLocator->OnClear();
pointLocator->OnBuild();
//delete the items
n->getParent()->eraseChild(n);
}
void TreeRoadmapPlanner::CreatePath(Node* a, Node* b, MilestonePath& path)
{
Assert(a->connectedComponent == b->connectedComponent);
Assert(a->LCA(b) != NULL); //make sure they're on same tree?
a->reRoot();
connectedComponents[a->connectedComponent] = a;
Assert(b->hasAncestor(a) || b==a);
Assert(a->getParent()==NULL);
//get path from a to b
list<Node*> atob;
while(b != NULL) {
atob.push_front(b);
Assert(b->connectedComponent == a->connectedComponent);
if(b->getParent() != NULL) {
Assert(b->edgeFromParent()->End() == b->x);
Assert(b->edgeFromParent()->Start() == b->getParent()->x);
}
b = b->getParent();
}
assert(atob.front() == a);
path.edges.resize(atob.size()-1);
int index=0;
for(list<Node*>::iterator i=++atob.begin();i!=atob.end();i++) {
b=*i;
if(b->edgeFromParent()==NULL) {
//LOG4CXX_INFO(KrisLibrary::logger(),"Hmm... constructing new edge?\n");
//edge data not stored
list<Node*>::iterator p=i; --p;
Node* bp = *p;
path.edges[index]=space->LocalPlanner(bp->x,b->x);
}
else {
//contains edge data
if(b->x == b->edgeFromParent()->Start())
path.edges[index]=b->edgeFromParent()->ReverseCopy();
else {
Assert(b->x == b->edgeFromParent()->End());
//do we need a copy here?
//path.edges[index]=b->edgeFromParent()->Copy();
path.edges[index]=b->edgeFromParent();
}
}
index++;
}
}
Real TreeRoadmapPlanner::OptimizePath(Node* a, const vector<Node*>& goals, ObjectiveFunctionalBase* objective, MilestonePath& path)
{
//this is pretty inefficient if there are a lot of goals...
MilestonePath tempPath;
Real bestCost = Inf;
a->reRoot();
connectedComponents[a->connectedComponent] = a;
for(auto b : goals) {
if(a->connectedComponent != b->connectedComponent) continue;
Assert(b->hasAncestor(a) || b==a);
Assert(a->getParent()==NULL);
Real totalCost = objective->TerminalCost(b->x);
if(totalCost >= bestCost) continue;
//get path from a to b
list<Node*> atob;
while(b != NULL) {
atob.push_front(b);
b = b->getParent();
}
path.edges.resize(atob.size()-1);
int index=0;
for(auto i=++atob.begin();i!=atob.end();i++) {
b=*i;
if(b->edgeFromParent()==NULL) {
//LOG4CXX_INFO(KrisLibrary::logger(),"Hmm... constructing new edge?\n");
//edge data not stored
auto p=i; --p;
Node* bp = *p;
path.edges[index]=space->LocalPlanner(bp->x,b->x);
}
else {
//contains edge data
if(b->x == b->edgeFromParent()->Start())
path.edges[index]=b->edgeFromParent()->ReverseCopy();
else {
Assert(b->x == b->edgeFromParent()->End());
//do we need a copy here?
//path.edges[index]=b->edgeFromParent()->Copy();
path.edges[index]=b->edgeFromParent();
}
}
totalCost += objective->IncrementalCost(path.edges[index].get());
if(totalCost >= bestCost) break;
index++;
}
if(totalCost < bestCost) {
bestCost = totalCost;
tempPath = path;
}
}
swap(path.edges,tempPath.edges);
return bestCost;
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::ClosestMilestone(const Config& x)
{
int idx = ClosestMilestoneIndex(x);
if(idx < 0) return NULL;
Assert(idx < (int)milestoneConfigs.size());
return milestones[idx];
}
int TreeRoadmapPlanner::ClosestMilestoneIndex(const Config& x)
{
if(milestones.empty()) return -1;
int index;
Real distance;
bool successful = pointLocator->NN(x,index,distance);
assert(successful);
return index;
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::ClosestMilestoneInComponent(int component,const Config& x)
{
ClosestMilestoneCallback callback(space,x);
connectedComponents[component]->DFS(callback);
return callback.closestMilestone;
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::ClosestMilestoneInSubtree(Node* node,const Config& x)
{
ClosestMilestoneCallback callback(space,x);
node->DFS(callback);
return callback.closestMilestone;
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::Extend(Node* n,const Config& x)
{ //connect closest to n
EdgePlannerPtr e=space->LocalPlanner(n->x,x);
Assert(e->Start() == n->x);
Assert(e->End() == x);
Node* c=AddMilestone(x);
n->addChild(c);
c->edgeFromParent() = e;
c->connectedComponent = n->connectedComponent;
//AddMilestone adds a connected component
connectedComponents.resize(connectedComponents.size()-1);
return c;
}
TreeRoadmapPlanner::Node* TreeRoadmapPlanner::TryExtend(Node* n,const Config& x)
{
if(space->IsFeasible(x)) {
//connect closest to n
EdgePlannerPtr e=space->LocalPlanner(n->x,x);
if(e->IsVisible()) {
Node* c=AddMilestone(x);
n->addChild(c);
c->edgeFromParent() = e;
c->connectedComponent = n->connectedComponent;
//AddMilestone adds a connected component
connectedComponents.resize(connectedComponents.size()-1);
return c;
}
}
return NULL;
}
/*
bool LazyCollisionRP::CheckPath(Node* a, Node* b)
{
Assert(a->connectedComponent == b->connectedComponent);
a->reRoot();
connectedComponents[a->connectedComponent] = a;
Node* n=b;
while(n != a) {
Node* p = n->getParent();
Assert(p != NULL);
if(!space->IsVisible(n->x,p->x)) {
//split at n
p->detachChild(n);
SetComponentCallback callback(connectedComponents.size());
connectedComponents.push_back(n);
n->DFS(callback);
return false;
}
n = p;
}
return true;
}
RandomizedPlanner::Node* LazyCollisionRP::CanConnectComponent(int i,const Config& x)
{
ClosestMilestoneCallback callback(space,x);
connectedComponents[i]->DFS(callback);
if(callback.closestMilestone) {
if(callback.closestDistance < connectionThreshold) {
return callback.closestMilestone;
}
}
return NULL;
}
*/
PerturbationTreePlanner::PerturbationTreePlanner(CSpace*s)
:TreeRoadmapPlanner(s),delta(1)
{}
void PerturbationTreePlanner::Cleanup()
{
TreeRoadmapPlanner::Cleanup();
weights.clear();
}
TreeRoadmapPlanner::Node* PerturbationTreePlanner::AddMilestone(const Config& x)
{
Assert(milestones.size() == weights.size());
Node* n=TreeRoadmapPlanner::AddMilestone(x);
Assert(n == milestones.back());
weights.push_back(1);
Assert(milestones.size() == weights.size());
return n;
}
void PerturbationTreePlanner::GenerateConfig(Config& x)
{
if(milestones.empty()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PerturbationTreePlanner::GenerateConfig(): No nodes to choose from!");
space->Sample(x);
}
else {
Node* n = SelectMilestone(milestones);
space->SampleNeighborhood(n->x,delta,x);
}
}
TreeRoadmapPlanner::Node* PerturbationTreePlanner::SelectMilestone(const vector<Node*>& milestones)
{
Assert(milestones.size()==weights.size());
Real total=Zero;
for(unsigned int i=0;i<milestones.size();i++) {
total += weights[i];
}
//pick randomly from the total
Real val=Rand(Zero,total);
for(unsigned int i=0;i<milestones.size();i++) {
val -= weights[i];
if(val<=Zero) return milestones[i];
}
//shouldn't get here
Assert(false);
return NULL;
}
RRTPlanner::RRTPlanner(CSpace*s)
:TreeRoadmapPlanner(s),delta(1)
{}
TreeRoadmapPlanner::Node* RRTPlanner::Extend()
{
Config dest,x;
space->Sample(dest);
//pick closest milestone, step in that direction
Node* closest=ClosestMilestone(dest);
Real dist=space->Distance(closest->x,dest);
if(dist > delta)
space->Interpolate(closest->x,dest,delta/dist,x);
else
x=dest;
return TryExtend(closest,x);
}
BidirectionalRRTPlanner::BidirectionalRRTPlanner(CSpace*s)
:RRTPlanner(s)
{}
void BidirectionalRRTPlanner::Init(const Config& start, const Config& goal)
{
Cleanup();
Assert(space->IsFeasible(start));
Assert(space->IsFeasible(goal));
AddMilestone(start);
AddMilestone(goal);
Assert(milestones.size()==2);
Assert(milestoneConfigs[0] == start);
Assert(milestoneConfigs[1] == goal);
Assert(connectedComponents.size()==2);
Assert(connectedComponents[0] == milestones[0]);
Assert(connectedComponents[1] == milestones[1]);
}
bool BidirectionalRRTPlanner::Plan()
{
//If we've already found a path, return true
if(milestones[0]->connectedComponent == milestones[1]->connectedComponent)
return true;
Node* n=Extend();
if(!n) return false;
if(n->connectedComponent == milestones[0]->connectedComponent) {
//attempt to connect to goal, if the distance is < connectionThreshold
ClosestMilestoneCallback callback(space,n->x);
milestones[1]->DFS(callback);
if(callback.closestDistance < connectionThreshold) {
if(TryConnect(n,callback.closestMilestone)) //connection successful!
return true;
}
}
else {
Assert(n->connectedComponent == milestones[1]->connectedComponent);
//attempt to connect to start, if the distance is < connectionThreshold
ClosestMilestoneCallback callback(space,n->x);
milestones[0]->DFS(callback);
if(callback.closestDistance < connectionThreshold) {
if(TryConnect(callback.closestMilestone,n)) //connection successful!
return true;
}
}
return false;
}
void BidirectionalRRTPlanner::CreatePath(MilestonePath& p) const
{
Assert(milestones[0]->connectedComponent == milestones[1]->connectedComponent);
Assert(connectedComponents[0] == milestones[0]);
list<Node*> path;
Node* n = milestones[1];
while(n != milestones[0]) {
path.push_front(n);
n = n->getParent();
Assert(n != NULL);
}
p.edges.resize(0);
p.edges.reserve(path.size());
for(list<Node*>::const_iterator i=path.begin();i!=path.end();i++) {
Node* n = *i;
EdgePlannerPtr e=n->edgeFromParent();
if(e->Start() == n->x) {
p.edges.push_back(e->ReverseCopy());
}
else if(e->End() == n->x) {
p.edges.push_back(e);
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"Hmm... edge doesn't have node as its start or its goal!");
Abort();
}
}
}
/*
VisibilityPRM::VisibilityPRM(CSpace*s)
:RandomizedPlanner(s)
{}
VisibilityPRM::Node* VisibilityPRM::AddMilestone(const Config& x)
{
if(space->IsFeasible(x)) {
vector<Node*> visibleNodes;
//add it only if it can connect to 0, or >= 2 nodes
//pick two closest nodes of entire graph
vector<Node*> closestNodes;
vector<Real> closestDistances;
closestNodes.reserve(connectedComponents.size()/2);
closestDistances.reserve(connectedComponents.size()/2);
Real minDist=Inf;
for(size_t i=0;i<connectedComponents.size();i++) {
if(connectedComponents[i] == NULL) continue;
ClosestMilestoneCallback callback(space,x);
connectedComponents[i]->DFS(callback);
if(callback.closestMilestone) {
closestNodes.push_back(callback.closestMilestone);
closestDistances.push_back(callback.closestDistance);
minDist = Min(minDist,callback.closestDistance);
}
}
//check visibility of any node that's closer than 2x min dist
for(size_t i=0;i<closestDistances.size();i++) {
if(closestDistances[i] < minDist*Two) {
if(space->IsVisible(x,closestNodes[i]->x))
visibleNodes.push_back(closestNodes[i]);
}
}
//connect if 0 or >= 2 nodes can be seen
if(visibleNodes.size() != 1) {
Node* n = AddMilestone(x);
for(size_t i=0;i<visibleNodes.size();i++) {
ConnectComponents(visibleNodes[i],n);
}
return n;
}
}
return NULL;
}
RandomizedPlanner::Node* VisibilityPRM::Extend()
{
GenerateConfig(x);
Node* n=TestAndAddMilestone(x);
//if(n) ConnectToNeighbors(n); (don't connect to neighbors, AddMilestone does that for you)
return n;
}
RandomizedPlanner::Node* VisibilityPRM::CanConnectComponent(int i,const Config& x)
{
//return closest visible node
ClosestMilestoneCallback callback(space,x);
connectedComponents[i]->DFS(callback);
if(space->IsVisible(callback.closestMilestone->x,x))
return callback.closestMilestone;
return NULL;
}
*/
| 27.367965 | 142 | 0.670357 | [
"vector"
] |
73364d235f8192f594de4135ea071e852d3b9e8d | 20,083 | hxx | C++ | include/usagi/gl/model/mesh.hxx | usagi/usagi | 2d57d21eeb92eadfdf4154a3e470aebfc3e388e5 | [
"MIT"
] | 2 | 2016-11-20T04:59:17.000Z | 2017-02-13T01:44:37.000Z | include/usagi/gl/model/mesh.hxx | usagi/usagi | 2d57d21eeb92eadfdf4154a3e470aebfc3e388e5 | [
"MIT"
] | 3 | 2015-09-28T12:00:02.000Z | 2015-09-28T12:03:21.000Z | include/usagi/gl/model/mesh.hxx | usagi/usagi | 2d57d21eeb92eadfdf4154a3e470aebfc3e388e5 | [
"MIT"
] | 3 | 2017-07-02T06:09:47.000Z | 2018-07-09T01:00:57.000Z | #pragma once
#include "helper.hxx"
#include "material.hxx"
#include "animation.hxx"
#include "vertex_buffer.hxx"
#include "bone.hxx"
#include <boost/gil/gil_all.hpp>
#include <boost/optional.hpp>
// assimp::Importer
#include <assimp/Importer.hpp>
// aiPostProcessSteps for assimp::Importer::ReadFile
#include <assimp/postprocess.h>
// aiScene, aiNode
#include <assimp/scene.h>
#include <unordered_map>
namespace usagi
{
namespace gl
{
namespace model
{
class mesh_type
{
friend class node_type;
GLuint _triangle_vb_id;
GLuint _triangle_ib_id;
GLsizei _count_of_indices;
GLuint _triangle_vao_id;
/// @brief このメッシュのマテリアル
const shared_material_type _shared_material;
/// @brief このメッシュのボーン群
const shared_bone_offsets_type _shared_bone_offsets;
/// @brief このメッシュのボーンインデックスへボーンの名前から参照するためのマップ
const shared_bone_map_type _shared_bone_map;
/// @brief このメッシュが関わるアニメーションを含むアニメーション群
const shared_animation_map_type _shared_animation_map;
using vertices_buffer_type = std::vector< vertex_buffer_type >;
using indices_buffer_type = std::vector< GLuint >;
/// @brief 内部用: 頂点バッファーとインデックスバッファーを assimp のメッシュに基いて生成する
auto initialize_prepare_buffers
( const aiMesh* mesh
, vertices_buffer_type& vb
, indices_buffer_type& ib
)
->void
{
constexpr auto indices_of_triangle = 3;
for ( auto n_vertex = 0u; n_vertex < mesh->mNumVertices; ++n_vertex )
vb.emplace_back
( std::move( helper::to_glm_vec4( mesh->mVertices + n_vertex ) )
, std::move( mesh->mColors[ 0 ] ? helper::to_glm_vec4( mesh->mColors[ 0 ] + n_vertex ) : glm::vec4( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 0 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 0 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 1 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 1 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 2 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 2 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 3 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 3 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 4 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 4 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 5 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 5 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 6 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 6 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mTextureCoords[ 7 ] ? helper::to_glm_vec2( mesh->mTextureCoords[ 7 ] + n_vertex ) : glm::vec2( std::nanf("") ) )
, std::move( mesh->mNormals ? helper::to_glm_vec3( mesh->mNormals + n_vertex ) : glm::vec3( std::nanf("") ) )
, std::move( mesh->mTangents ? helper::to_glm_vec3( mesh->mTangents + n_vertex ) : glm::vec3( std::nanf("") ) )
, std::move( mesh->mBitangents ? helper::to_glm_vec3( mesh->mBitangents + n_vertex ) : glm::vec3( std::nanf("") ) )
, std::move( glm::vec4( 0.0f ) )
, std::move( glm::vec4( 0.0f ) )
);
for ( auto n_face = 0u; n_face < mesh->mNumFaces; ++ n_face )
{
const auto face = mesh->mFaces + n_face;
if ( face->mNumIndices not_eq indices_of_triangle )
throw std::runtime_error( "required must be indices of face is 3. try create_model with aiProcess_Triangulate." );
ib.emplace_back( std::move( face->mIndices[0] ) );
ib.emplace_back( std::move( face->mIndices[1] ) );
ib.emplace_back( std::move( face->mIndices[2] ) );
}
_count_of_indices = ib.size();
}
/// @brief 内部用: アニメーションのためのボーン情報を assimp のメッシュに基いて生成し頂点バッファーへ格納する
auto initialize_animation_bone
( const aiMesh* mesh
, vertices_buffer_type& vb
)
->void
{
// アニメーション・ボーンまわり
const auto bones = mesh->mBones;
for ( auto n_bone = 0u; n_bone < mesh->mNumBones; ++n_bone )
{
const auto bone = bones[ n_bone ];
const std::string bone_name( bone->mName.C_Str() );
unsigned bone_index = 0;
if ( _shared_bone_map->find( bone_name ) == _shared_bone_map->end() )
{
bone_index = _shared_bone_map->size();
_shared_bone_offsets->push_back( glm::mat4( 1.0f ) );
if ( _shared_bone_offsets->size() > max_bones )
throw std::runtime_error
( "bone offset size " + std::to_string( _shared_bone_offsets->size() )
+ " over shader::max_bones " + std::to_string( max_bones )
+ "."
);
}
else
bone_index = _shared_bone_map->at( bone_name );
(*_shared_bone_map)[ bone_name ] = bone_index;
// TODO: もしかしたら .x 形式以外では bone_offset に transpose していると怪奇現象化するかも。要確認
// pattern: .x is ok
_shared_bone_offsets->at( bone_index ) = glm::transpose( helper::to_glm_mat4( bone->mOffsetMatrix ) );
// transpose しない場合:
// _shared_bone_offsets->at( bone_index ) = helper::to_glm_mat4( bone->mOffsetMatrix );
for ( auto n_weight = 0u; n_weight < bone->mNumWeights; ++n_weight )
{
const auto& weight = bone->mWeights[ n_weight ];
auto& vertex = vb[ weight.mVertexId ];
bool overflow_check = true;
for ( auto n = 0; n < 4; ++n )
if ( vertex.bone_weights[ n ] == 0.0f )
{
vertex.bone_ids [ n ] = bone_index;
vertex.bone_weights[ n ] = weight.mWeight;
overflow_check = false;
break;
}
if ( overflow_check )
throw std::runtime_error( "bone buffer is not enought, need limit data bone/vertex <= 4, or fix engine." );
}
}
}
/// @brief 内部用: 頂点バッファー、インデックスバッファーを生成
auto initialize_generate_buffers
( const vertices_buffer_type& vb
, const indices_buffer_type& ib
)
->void
{
glGenVertexArrays( 1, &_triangle_vao_id );
glBindVertexArray( _triangle_vao_id );
glGenBuffers( 1, &_triangle_vb_id);
glGenBuffers( 1, &_triangle_ib_id);
glBindBuffer( GL_ARRAY_BUFFER, _triangle_vb_id );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _triangle_ib_id );
glBufferData
( GL_ARRAY_BUFFER
, vb.size() * vertex_buffer_type::size_of_memory
, vb.data()->to_ptr<void>()
, GLenum( GL_STATIC_DRAW )
);
glBufferData
( GL_ELEMENT_ARRAY_BUFFER
, ib.size() * sizeof( indices_buffer_type::value_type )
, reinterpret_cast< const void* >( ib.data() )
, GLenum( GL_STATIC_DRAW )
);
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ARRAY_BUFFER , 0 );
glBindVertexArray( 0 );
}
public:
/// @brief assimp のメッシュに基いて usagi::gl::model で取り扱い可能なメッシュオブジェクトを構築
mesh_type
( const aiMesh* mesh
, const shared_shared_materials_type& shared_shared_materials
, const shared_bone_offsets_type& shared_bone_offsets
, const shared_bone_map_type& shared_bone_map
, const shared_animation_map_type& shared_animation_map
)
: _shared_material ( shared_shared_materials->at( mesh->mMaterialIndex ) )
, _shared_bone_offsets ( shared_bone_offsets )
, _shared_bone_map ( shared_bone_map )
, _shared_animation_map( shared_animation_map )
{
// initialize_generate_buffers 後は不要となる一時オブジェクトのためメンバー化する必要は無い
vertices_buffer_type vb;
indices_buffer_type ib;
// vb, ib は参照渡しで変更される
initialize_prepare_buffers ( mesh, vb, ib );
initialize_animation_bone ( mesh, vb );
// vb, ib はここでメインメモリーからVRAMのオブジェクトへ転送されメインメモリー上では不要となる
initialize_generate_buffers( vb, ib );
}
~mesh_type()
{
glDeleteBuffers( 1, &_triangle_ib_id );
glDeleteBuffers( 1, &_triangle_vb_id );
glDeleteVertexArrays( 1, &_triangle_vao_id );
}
/// @brief 必要なマテリアルをバインドしメッシュを描画する
auto draw()
->void
{
// vertex transfar
constexpr GLenum attribute = GL_FLOAT;
const GLboolean normalize_on = static_cast< GLboolean >( true );
const GLboolean normalize_off = static_cast< GLboolean >( false );
const auto program_id = get_current_program();
{
glBindVertexArray( _triangle_vao_id );
glBindBuffer( GL_ARRAY_BUFFER, _triangle_vb_id );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _triangle_ib_id );
{
const auto location_of_vs_position = glGetAttribLocation( program_id, "position" );
const auto location_of_vs_color = glGetAttribLocation( program_id, "color" );
const auto location_of_vs_texcoord0 = glGetAttribLocation( program_id, "texcoord0" );
const auto location_of_vs_texcoord1 = glGetAttribLocation( program_id, "texcoord1" );
const auto location_of_vs_texcoord2 = glGetAttribLocation( program_id, "texcoord2" );
const auto location_of_vs_texcoord3 = glGetAttribLocation( program_id, "texcoord3" );
const auto location_of_vs_texcoord4 = glGetAttribLocation( program_id, "texcoord4" );
const auto location_of_vs_texcoord5 = glGetAttribLocation( program_id, "texcoord5" );
const auto location_of_vs_texcoord6 = glGetAttribLocation( program_id, "texcoord6" );
const auto location_of_vs_texcoord7 = glGetAttribLocation( program_id, "texcoord7" );
const auto location_of_vs_normal = glGetAttribLocation( program_id, "normal" );
const auto location_of_vs_tangent = glGetAttribLocation( program_id, "tangent" );
const auto location_of_vs_bitangent = glGetAttribLocation( program_id, "bitangent" );
const auto location_of_vs_bone_ids = glGetAttribLocation( program_id, "bone_ids" );
const auto location_of_vs_bone_weights = glGetAttribLocation( program_id, "bone_weights" );
if ( location_of_vs_position not_eq -1 )
{
glVertexAttribPointer
( location_of_vs_position
, vertex_buffer_type::count_of_position_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_position )
);
glEnableVertexAttribArray( location_of_vs_position );
}
if ( location_of_vs_color not_eq -1 )
{
glVertexAttribPointer( location_of_vs_color
, vertex_buffer_type::count_of_color_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_color )
);
glEnableVertexAttribArray( location_of_vs_color );
}
if ( location_of_vs_texcoord0 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord0
, vertex_buffer_type::count_of_texcoord0_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord0 )
);
glEnableVertexAttribArray( location_of_vs_texcoord0 );
}
if ( location_of_vs_texcoord1 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord1
, vertex_buffer_type::count_of_texcoord1_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord1 )
);
glEnableVertexAttribArray( location_of_vs_texcoord1 );
}
if ( location_of_vs_texcoord2 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord2
, vertex_buffer_type::count_of_texcoord2_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord2 )
);
glEnableVertexAttribArray( location_of_vs_texcoord2 );
}
if ( location_of_vs_texcoord3 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord3
, vertex_buffer_type::count_of_texcoord3_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord3 )
);
glEnableVertexAttribArray( location_of_vs_texcoord3 );
}
if ( location_of_vs_texcoord4 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord4
, vertex_buffer_type::count_of_texcoord4_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord4 )
);
glEnableVertexAttribArray( location_of_vs_texcoord4 );
}
if ( location_of_vs_texcoord5 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord5
, vertex_buffer_type::count_of_texcoord5_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord5 )
);
glEnableVertexAttribArray( location_of_vs_texcoord5 );
}
if ( location_of_vs_texcoord6 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord6
, vertex_buffer_type::count_of_texcoord6_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord6 )
);
glEnableVertexAttribArray( location_of_vs_texcoord6 );
}
if ( location_of_vs_texcoord7 not_eq -1 )
{
glVertexAttribPointer( location_of_vs_texcoord7
, vertex_buffer_type::count_of_texcoord7_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_texcoord7 )
);
glEnableVertexAttribArray( location_of_vs_texcoord7 );
}
if ( location_of_vs_normal not_eq -1 )
{
glVertexAttribPointer( location_of_vs_normal
, vertex_buffer_type::count_of_normal_elements
, attribute
, normalize_on
, vertex_buffer_type::size_of_memory
, reinterpret_cast<void*>( vertex_buffer_type::memory_offset_of_normal )
);
glEnableVertexAttribArray( location_of_vs_normal );
}
if ( location_of_vs_tangent not_eq -1 )
{
glVertexAttribPointer
( location_of_vs_tangent
, vertex_buffer_type::count_of_tangent_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast< void* >( vertex_buffer_type::memory_offset_of_tangent )
);
glEnableVertexAttribArray( location_of_vs_tangent );
}
if ( location_of_vs_bitangent not_eq -1 )
{
glVertexAttribPointer
( location_of_vs_bitangent
, vertex_buffer_type::count_of_bitangent_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast< void* >( vertex_buffer_type::memory_offset_of_bitangent )
);
glEnableVertexAttribArray( location_of_vs_bitangent );
}
if ( location_of_vs_bone_ids not_eq -1 )
{
glVertexAttribPointer
( location_of_vs_bone_ids
, vertex_buffer_type::count_of_bone_ids_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast< void* >( vertex_buffer_type::memory_offset_of_bone_ids )
);
glEnableVertexAttribArray( location_of_vs_bone_ids );
}
if ( location_of_vs_bone_weights not_eq -1 )
{
glVertexAttribPointer
( location_of_vs_bone_weights
, vertex_buffer_type::count_of_bone_weights_elements
, attribute
, normalize_off
, vertex_buffer_type::size_of_memory
, reinterpret_cast< void* >( vertex_buffer_type::memory_offset_of_bone_weights )
);
glEnableVertexAttribArray( location_of_vs_bone_weights );
}
}
_shared_material->bind();
glDrawElements( GL_TRIANGLES, _count_of_indices, GL_UNSIGNED_INT, nullptr );
_shared_material->unbind();
}
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
}
};
using meshes_type = std::vector< mesh_type >;
using shared_meshes_type = std::shared_ptr< meshes_type >;
static inline auto make_shared_meshes() { return std::make_shared< meshes_type >(); }
}
}
} | 42.912393 | 143 | 0.554598 | [
"mesh",
"vector",
"model"
] |
7336a5696d914767350202245366f498303d7908 | 8,694 | cpp | C++ | src/client/horde3ditem.cpp | SkewedAspect/precursors-client | 2c56d924829f2628cceb0eaef91ac49fd8482ee3 | [
"MIT"
] | 2 | 2016-05-10T05:05:18.000Z | 2017-10-10T07:29:13.000Z | src/client/horde3ditem.cpp | SkewedAspect/precursors-client | 2c56d924829f2628cceb0eaef91ac49fd8482ee3 | [
"MIT"
] | null | null | null | src/client/horde3ditem.cpp | SkewedAspect/precursors-client | 2c56d924829f2628cceb0eaef91ac49fd8482ee3 | [
"MIT"
] | null | null | null | #include "config.h"
#include "horde3ditem.h"
#include "cameranodeobject.h"
#include <Horde3DUtils.h>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>
#define USE_BEFORE_RENDER 1
Horde3DItem::Horde3DItem(QQuickItem* parent) :
QQuickItem(parent),
m_timerID(0),
m_cameraQObject(NULL),
m_node(NULL),
m_fbo(NULL),
m_texture(NULL),
m_qtContext(NULL),
m_h3dContext(NULL),
m_samples(0),
m_AAEnabled(false),
m_initialized(false),
m_dirtyFBO(false),
m_animTime(0.0f)
{
setFlag(ItemHasContents);
setSmooth(false);
connect(this, SIGNAL(initFinished()), this, SLOT(onInitFinished()), Qt::QueuedConnection);
} // end Horde3DItem
Horde3DItem::~Horde3DItem()
{
//TODO: Cleanup!
} // end ~Horde3DItem
QSGNode* Horde3DItem::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData* data)
{
Q_UNUSED(data);
if(!m_initialized)
{
init();
} // end if
if(m_dirtyFBO)
{
updateFBO();
} // end if
if(width() <= 0 || height() <= 0 || !m_texture)
{
delete oldNode;
return 0;
} // end if
m_node = static_cast<QSGSimpleTextureNode*>(oldNode);
if(!m_node)
{
m_node = new QSGSimpleTextureNode();
m_node->setFiltering(QSGTexture::Nearest);
} // end if
m_node->setRect(boundingRect());
m_node->setTexture(m_texture);
setAAEnabled(smooth());
# ifndef USE_BEFORE_RENDER
renderHorde();
# endif // USE_BEFORE_RENDER
return m_node;
} // end updatePaintNode
void Horde3DItem::renderHorde()
{
if(m_node)
{
m_animTime += 0.4f;
// Do animation blending
h3dSetModelAnimParams(m_knight, 0, m_animTime, 0.5f);
h3dSetModelAnimParams(m_knight, 1, m_animTime, 0.5f);
h3dUpdateModel(m_knight, H3DModelUpdateFlags::Animation | H3DModelUpdateFlags::Geometry);
if(m_qtContext && m_h3dContext && m_fbo && m_camera)
{
if(restoreH3DState())
{
h3dRender(m_camera);
h3dFinalizeFrame();
} // end if
saveH3DState();
} // end if
m_node->markDirty(QSGNode::DirtyMaterial);
} // end if
} // end renderHorde
void Horde3DItem::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry)
{
qDebug() << "Horde3DItem::geometryChanged(" << newGeometry << "," << oldGeometry << ")";
if(newGeometry.size() != oldGeometry.size())
{
m_size = QSize((int) newGeometry.width(), (int) newGeometry.height());
m_dirtyFBO = true;
if(m_node)
{
m_node->markDirty(QSGNode::DirtyGeometry);
} // end if
} // end if
} // end geometryChanged
void Horde3DItem::printHordeMessages()
{
int msgLevel;
float msgTime;
const char* message;
while((message = h3dGetMessage(&msgLevel, &msgTime)) && strlen(message) > 0)
{
qDebug() << msgLevel << "message from Horde3D at" << msgTime << ":" << message;
} // end while
} // end printHordeMessages
bool Horde3DItem::restoreH3DState()
{
m_qtContext->doneCurrent();
m_h3dContext->makeCurrent(window());
QOpenGLFunctions glFunctions(m_h3dContext);
glFunctions.glUseProgram(0);
if(!m_fbo->bind())
{
qCritical() << "Error binding FBO!";
return false;
}
else
{
return true;
} // end if
} // end restoreH3DState
void Horde3DItem::saveH3DState()
{
if(!m_fbo->release())
{
qCritical() << "Error releasing FBO!";
} // end if
m_h3dContext->doneCurrent();
m_qtContext->makeCurrent(window());
} // end saveH3DState
void Horde3DItem::updateFBO()
{
qDebug() << "Horde3DItem::updateFBO()";
if(m_fbo)
{
delete m_fbo;
} // end if
m_qtContext = QOpenGLContext::currentContext();
if(m_h3dContext && (m_h3dContext->format() != m_qtContext->format()))
{
m_h3dContext->deleteLater();
m_h3dContext = NULL;
} // end if
if(!m_h3dContext)
{
// Create a new shared OpenGL context to be used exclusively by Horde3D
m_h3dContext = new QOpenGLContext();
m_h3dContext->setFormat(window()->requestedFormat());
m_h3dContext->setShareContext(m_qtContext);
m_h3dContext->create();
} // end if
m_h3dContext->makeCurrent(window());
m_fbo = new QOpenGLFramebufferObject(m_size, QOpenGLFramebufferObject::CombinedDepthStencil);
m_h3dContext->doneCurrent();
int deviceWidth = m_size.width();
int deviceHeight = m_size.height();
// Resize viewport
h3dSetNodeParamI(m_camera, H3DCamera::ViewportXI, 0);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportYI, 0);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportWidthI, deviceWidth);
h3dSetNodeParamI(m_camera, H3DCamera::ViewportHeightI, deviceHeight);
// Set virtual camera parameters
float aspectRatio = static_cast<float>(deviceWidth) / deviceHeight;
h3dSetupCameraView(m_camera, 45.0f, aspectRatio, 0.1f, 1000.0f);
m_cameraObject->updateRotation();
H3DRes cameraPipeRes = h3dGetNodeParamI(m_camera, H3DCamera::PipeResI);
h3dResizePipelineBuffers(cameraPipeRes, deviceWidth, deviceHeight);
delete m_texture;
m_texture = window()->createTextureFromId(m_fbo->texture(), m_fbo->size());
m_texture->setFiltering(QSGTexture::Nearest);
m_texture->setHorizontalWrapMode(QSGTexture::ClampToEdge);
m_texture->setVerticalWrapMode(QSGTexture::ClampToEdge);
m_dirtyFBO = false;
// Appease the angry QML gods.
restoreH3DState();
saveH3DState();
} // end updateFBO
void Horde3DItem::setAAEnabled(bool enable)
{
if(m_AAEnabled != enable)
{
qDebug() << "Horde3DItem::setAAEnabled(" << enable << ")";
m_AAEnabled = enable;
m_dirtyFBO = true;
} // end if
} // end setAAEnabled
void Horde3DItem::timerEvent(QTimerEvent* event)
{
Q_UNUSED(event);
printHordeMessages();
update();
} // end timerEvent
void Horde3DItem::onBeforeRendering()
{
renderHorde();
printHordeMessages();
} // end onBeforeRendering
void Horde3DItem::onInitFinished()
{
startTimer(16);
# ifdef USE_BEFORE_RENDER
connect(window(), SIGNAL(beforeRendering()), this, SLOT(onBeforeRendering()), Qt::DirectConnection);
# endif // USE_BEFORE_RENDER
} // end onInitFinished
void Horde3DItem::init()
{
qDebug() << "Horde3DItem::init()";
const QOpenGLContext* ctx = window()->openglContext();
m_samples = ctx->format().samples();
if(!h3dInit())
{
qCritical() << "h3dInit failed";
} // end if
int textureAnisotropy = 8;
if(!h3dSetOption(H3DOptions::MaxAnisotropy, textureAnisotropy))
{
qDebug() << "Couldn't set texture anisotropy to" << textureAnisotropy << "!";
} // end if
int aaSamples = m_AAEnabled ? m_samples : 0;
if(!h3dSetOption(H3DOptions::SampleCount, aaSamples))
{
qDebug() << "Couldn't set antialiasing samples to" << aaSamples << "!";
} // end if
H3DRes pipeline = h3dAddResource(H3DResTypes::Pipeline, "pipelines/forward.pipeline.xml", 0);
H3DRes knight = h3dAddResource(H3DResTypes::SceneGraph, "models/knight/knight.scene.xml", 0);
H3DRes knightAnim1Res = h3dAddResource(H3DResTypes::Animation, "animations/knight_order.anim", 0);
H3DRes knightAnim2Res = h3dAddResource(H3DResTypes::Animation, "animations/knight_attack.anim", 0);
H3DRes ares = h3dAddResource(H3DResTypes::SceneGraph, "models/ares/ares.scene.xml", 0);
h3dutLoadResourcesFromDisk("Content");
m_knight = h3dAddNodes(H3DRootNode, knight);
h3dSetNodeTransform(m_knight,
0, 0, 0,
0, 0, 0,
1, 1, 1
);
h3dSetupModelAnimStage(m_knight, 0, knightAnim1Res, 0, "", false);
h3dSetupModelAnimStage(m_knight, 1, knightAnim2Res, 0, "", false);
m_ares = h3dAddNodes(H3DRootNode, ares);
h3dSetNodeTransform(m_ares,
0, 0, 0,
0, 0, 0,
1, 1, 1
);
m_camera = h3dAddCameraNode(H3DRootNode, "cam", pipeline);
h3dSetNodeParamF(m_camera, H3DCamera::FarPlaneF, 0, 100000);
m_cameraObject = new CameraNodeObject(m_camera);
m_cameraQObject = static_cast<QObject*>(m_cameraObject);
printHordeMessages();
qDebug() << "--------- Initialization Finished ---------";
m_dirtyFBO = true;
m_initialized = true;
emit initFinished();
} // end init
| 26.668712 | 108 | 0.644813 | [
"geometry"
] |
7339e1e9690ab4b51e1a9100a8ba3d37a58f0583 | 6,581 | hpp | C++ | libs/geometry/test/algorithms/test_simplify.hpp | lijgame/boost | ec2214a19cdddd1048058321a8105dd0231dac47 | [
"BSL-1.0"
] | 1 | 2018-12-15T19:57:24.000Z | 2018-12-15T19:57:24.000Z | thirdparty-cpp/boost_1_62_0/libs/geometry/test/algorithms/test_simplify.hpp | nxplatform/nx-mobile | 0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5 | [
"Apache-2.0"
] | null | null | null | thirdparty-cpp/boost_1_62_0/libs/geometry/test/algorithms/test_simplify.hpp | nxplatform/nx-mobile | 0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5 | [
"Apache-2.0"
] | 1 | 2019-03-08T11:06:22.000Z | 2019-03-08T11:06:22.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_TEST_SIMPLIFY_HPP
#define BOOST_GEOMETRY_TEST_SIMPLIFY_HPP
// Test-functionality, shared between single and multi tests
#include <iomanip>
#include <sstream>
#include <geometry_test_common.hpp>
#include <boost/geometry/algorithms/simplify.hpp>
#include <boost/geometry/algorithms/distance.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/io/wkt/wkt.hpp>
#include <boost/variant/variant.hpp>
template <typename Tag, typename Geometry>
struct test_inserter
{
static void apply(Geometry& , std::string const& , double )
{}
};
template <typename Geometry>
struct test_inserter<bg::linestring_tag, Geometry>
{
template <typename DistanceMeasure>
static void apply(Geometry& geometry,
std::string const& expected,
DistanceMeasure const& distance)
{
{
Geometry simplified;
bg::detail::simplify::simplify_insert(geometry,
std::back_inserter(simplified), distance);
std::ostringstream out;
// TODO: instead of comparing the full string (with more or less decimal digits),
// we should call something more robust to check the test for example geometry::equals
out << std::setprecision(12) << bg::wkt(simplified);
BOOST_CHECK_EQUAL(out.str(), expected);
}
#ifdef TEST_PULL89
{
typedef typename bg::point_type<Geometry>::type point_type;
typedef typename bg::strategy::distance::detail::projected_point_ax<>::template result_type<point_type, point_type>::type distance_type;
typedef bg::strategy::distance::detail::projected_point_ax_less<distance_type> less_comparator;
distance_type max_distance(distance);
less_comparator less(max_distance);
bg::strategy::simplify::detail::douglas_peucker
<
point_type,
bg::strategy::distance::detail::projected_point_ax<>,
less_comparator
> strategy(less);
Geometry simplified;
bg::detail::simplify::simplify_insert(geometry,
std::back_inserter(simplified), max_distance, strategy);
std::ostringstream out;
// TODO: instead of comparing the full string (with more or less decimal digits),
// we should call something more robust to check the test for example geometry::equals
out << std::setprecision(12) << bg::wkt(simplified);
BOOST_CHECK_EQUAL(out.str(), expected);
}
#endif
}
};
template <typename Geometry, typename DistanceMeasure>
void check_geometry(Geometry const& geometry,
std::string const& expected,
DistanceMeasure const& distance)
{
Geometry simplified;
bg::simplify(geometry, simplified, distance);
std::ostringstream out;
out << std::setprecision(12) << bg::wkt(simplified);
BOOST_CHECK_EQUAL(out.str(), expected);
}
template <typename Geometry, typename Strategy, typename DistanceMeasure>
void check_geometry(Geometry const& geometry,
std::string const& expected,
DistanceMeasure const& distance,
Strategy const& strategy)
{
Geometry simplified;
bg::simplify(geometry, simplified, distance, strategy);
std::ostringstream out;
out << std::setprecision(12) << bg::wkt(simplified);
BOOST_CHECK_EQUAL(out.str(), expected);
}
template <typename Geometry, typename DistanceMeasure>
void test_geometry(std::string const& wkt,
std::string const& expected,
DistanceMeasure distance)
{
typedef typename bg::point_type<Geometry>::type point_type;
Geometry geometry;
bg::read_wkt(wkt, geometry);
boost::variant<Geometry> v(geometry);
// Define default strategy for testing
typedef bg::strategy::simplify::douglas_peucker
<
typename bg::point_type<Geometry>::type,
bg::strategy::distance::projected_point<double>
> dp;
check_geometry(geometry, expected, distance);
check_geometry(v, expected, distance);
BOOST_CONCEPT_ASSERT( (bg::concepts::SimplifyStrategy<dp, point_type>) );
check_geometry(geometry, expected, distance, dp());
check_geometry(v, expected, distance, dp());
// Check inserter (if applicable)
test_inserter
<
typename bg::tag<Geometry>::type,
Geometry
>::apply(geometry, expected, distance);
#ifdef TEST_PULL89
// Check using non-default less comparator in douglass_peucker
typedef typename bg::strategy::distance::detail::projected_point_ax<>::template result_type<point_type, point_type>::type distance_type;
typedef bg::strategy::distance::detail::projected_point_ax_less<distance_type> less_comparator;
distance_type const max_distance(distance);
less_comparator const less(max_distance);
typedef bg::strategy::simplify::detail::douglas_peucker
<
point_type,
bg::strategy::distance::detail::projected_point_ax<>,
less_comparator
> douglass_peucker_with_less;
BOOST_CONCEPT_ASSERT( (bg::concepts::SimplifyStrategy<douglass_peucker_with_less, point_type>) );
check_geometry(geometry, expected, distance, douglass_peucker_with_less(less));
check_geometry(v, expected, distance, douglass_peucker_with_less(less));
#endif
}
template <typename Geometry, typename Strategy, typename DistanceMeasure>
void test_geometry(std::string const& wkt,
std::string const& expected,
DistanceMeasure const& distance,
Strategy const& strategy)
{
Geometry geometry;
bg::read_wkt(wkt, geometry);
boost::variant<Geometry> v(geometry);
BOOST_CONCEPT_ASSERT( (bg::concepts::SimplifyStrategy<Strategy,
typename bg::point_type<Geometry>::type>) );
check_geometry(geometry, expected, distance, strategy);
check_geometry(v, expected, distance, strategy);
}
#endif
| 35.961749 | 149 | 0.660234 | [
"geometry"
] |
733cd0148cbf53b2f32dda807a8ad074ce84c058 | 3,137 | hpp | C++ | lib/Util/VecOp.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | null | null | null | lib/Util/VecOp.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | null | null | null | lib/Util/VecOp.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | null | null | null | #ifndef VECOP_H
#define VECOP_H
#include <Template/Array.hpp>
#include <STD/Vector.hpp>
namespace EnjoLib
{
class VecD;
class VecOp
{
public:
template <class T> Array<T> AddArr(const Array<T> & one, const Array<T> & two) const;
template <class T> std::vector<T> Add(const std::vector<T> & one, const std::vector<T> & two) const;
template <class T> std::vector<T> AddConstMem(const std::vector<T> & one, const std::vector<T> & two) const;
template <class T> std::vector<std::vector<T> > Split(const std::vector<T> & one, std::size_t num) const;
template <class T> void AddRef(const std::vector<T> & one, std::vector<T> * two) const;
template <class T> int FindMaxIdx(const std::vector<T> & v) const;
template <class T> int FindMinIdx(const std::vector<T> & v) const;
protected:
private:
};
template <class T>
std::vector<T> VecOp::Add(const std::vector<T> & a, const std::vector<T> & b) const
{
std::vector<T> ret(a);
ret.insert(ret.end(), b.begin(), b.end());
return ret;
}
template <class T>
Array<T> VecOp::AddArr(const Array<T> & one, const Array<T> & two) const
{
std::vector<T> oneV;
std::vector<T> twoV;
AR2VEC(one, oneV)
AR2VEC(two, twoV)
const std::vector<T> ret = Add(oneV, twoV);
return ret;
}
template <class T>
std::vector<T> VecOp::AddConstMem(const std::vector<T> & a, const std::vector<T> & b) const
{
std::vector<T> ret(a);
std::copy (b.begin(), b.end(), std::back_inserter(ret));
return ret;
}
template <class T>
std::vector<std::vector<T> > VecOp::Split(const std::vector<T> & one, std::size_t num) const
{
std::vector<std::vector<T> > ret;
if (num == 0)
{
return ret;
}
if (num == 1)
{
ret.push_back(one);
return ret;
}
const std::size_t len = one.size();
const std::size_t numPerSlice = len / num;
std::vector<T> accum;
for (std::size_t i = 0; i < len; ++i)
{
const T & val = one.at(i);
if (ret.size() == num)
{
ret.back().push_back(val);
}
else
{
accum.push_back(val);
if (accum.size() >= numPerSlice)
{
ret.push_back(accum);
accum.clear();
}
}
}
return ret;
}
template <class T>
void VecOp::AddRef(const std::vector<T> & a, std::vector<T> * two) const
{
std::copy (a.begin(), a.end(), std::back_inserter(*two));
}
template <class T>
int VecOp::FindMaxIdx(const std::vector<T> & v) const
{
T mv = -1;
int mi = -1;
for (unsigned i = 0; i < v.size(); ++i)
{
const T & val = v.at(i);
if (mi == -1 || val > mv)
{
mi = i;
mv = val;
}
}
return mi;
}
template <class T>
int VecOp::FindMinIdx(const std::vector<T> & v) const
{
T mv = -1;
int mi = -1;
for (unsigned i = 0; i < v.size(); ++i)
{
const T & val = v.at(i);
if (mi == -1 || val < mv)
{
mi = i;
mv = val;
}
}
return mi;
}
}
#endif // VECOP_H
| 23.765152 | 116 | 0.535544 | [
"vector"
] |
733e074aee9dbb39734ffeab030b8aed4ee3a428 | 3,004 | cpp | C++ | Localization/ParticleFilter/simulator.cpp | daniel-s-ingram/CppRobotics | 02d79d79705c801afb564e67c1083e96d69bbb86 | [
"MIT"
] | 41 | 2019-02-22T21:32:04.000Z | 2022-03-17T16:11:53.000Z | Localization/ParticleFilter/simulator.cpp | daniel-s-ingram/CppRobotics | 02d79d79705c801afb564e67c1083e96d69bbb86 | [
"MIT"
] | null | null | null | Localization/ParticleFilter/simulator.cpp | daniel-s-ingram/CppRobotics | 02d79d79705c801afb564e67c1083e96d69bbb86 | [
"MIT"
] | 3 | 2019-10-24T15:25:49.000Z | 2020-08-24T22:54:01.000Z | #include "simulator.h"
Simulator::Simulator(int w, int h, int nL, int nP, float fNoise, float tNoise, float sNoise) : w(w), h(h), nLandmarks(nL), nParticles(nP), fNoise(fNoise), tNoise(tNoise), sNoise(sNoise)
{
cv::namedWindow("Particle Filter", 0);
robot = Robot(cv::Point(w/2, h/2), 0, fNoise, tNoise, sNoise);
filter = ParticleFilter(nParticles);
initLandmarks();
initParticles();
}
void Simulator::initLandmarks()
{
srand(time(NULL));
landmarks.clear();
for (int i = 0; i < nLandmarks; i++)
{
float x = w * (double)std::rand() / RAND_MAX;
float y = h * (double)std::rand() / RAND_MAX;
landmarks.push_back(cv::Point(x, y));
}
}
void Simulator::initParticles()
{
particles.clear();
for (int i = 0; i < nParticles; i++)
{
float x = w * (double)std::rand() / RAND_MAX;
float y = h * (double)std::rand() / RAND_MAX;
float yaw = 2 * M_PI * (double)std::rand() / RAND_MAX;
Robot p = Robot(cv::Point(x, y), yaw, fNoise, tNoise, sNoise);
particles.push_back(p);
}
}
void Simulator::drawScene(cv::Mat& canvas)
{
canvas.setTo(cv::Scalar(255, 255, 255));
cv::circle(canvas, robot.pos, 10, cv::Scalar(0, 0, 0), -1);
for (auto& landmark : landmarks)
{
cv::circle(canvas, landmark, 5, cv::Scalar(0, 0, 255), -1);
cv::line(canvas, landmark, robot.pos, cv::Scalar(255, 0, 255), 1, CV_AA);
}
for (auto& particle : particles)
{
cv::Scalar color = cv::Scalar(std::rand() % 255, std::rand() % 255, std::rand() % 255);
cv::circle(canvas, particle.pos, 1, color, -1);
}
}
int Simulator::run()
{
cv::Mat canvas(h, w, CV_8UC3);
vector<float> weights(nParticles, 0);
vector<float> Z(nLandmarks, 0);
Robot p;
//cv::VideoWriter video("part.mp4", CV_FOURCC('F','M','P','4'), 100, cv::Size(w, h));
while (true)
{
float turn = 2 * M_PI * (double)std::rand() / RAND_MAX;
float forward = 0.5;
robot.move(turn, forward);
robot.sense(landmarks, Z);
for (int i = 0; i < nParticles; i++)
{
p = particles[i].move(turn, forward);
particles[i] = p;
weights[i] = p.measProb(landmarks, Z);
}
float norm = 0.0;
for (const auto& weight : weights)
{
norm += weight;
}
for (auto& weight : weights)
{
weight /= norm;
}
int maxIndex = filter.resample(weights, particles);
std::cout << "Actual robot position: [" << robot.pos.x << ", " << robot.pos.y << "]\n"
"Estimated robot position: " << particles[maxIndex] << std::endl;
drawScene(canvas);
cv::imshow("Particle Filter", canvas);
//video.write(canvas);
if (cv::waitKey(1) == 27)
break;
}
//video.release();
cv::destroyAllWindows();
return 0;
} | 29.45098 | 185 | 0.533289 | [
"vector"
] |
733e5a123d73fd520fde2d0199cce99521cd8923 | 13,864 | cc | C++ | library/common/glfw/embedder.cc | jbg/flutter-desktop-embedding | f490eb6fdac3ffcb5716540e8864bbcc2d7abcfd | [
"Apache-2.0"
] | 1 | 2019-02-19T14:48:27.000Z | 2019-02-19T14:48:27.000Z | library/common/glfw/embedder.cc | jbg/flutter-desktop-embedding | f490eb6fdac3ffcb5716540e8864bbcc2d7abcfd | [
"Apache-2.0"
] | null | null | null | library/common/glfw/embedder.cc | jbg/flutter-desktop-embedding | f490eb6fdac3ffcb5716540e8864bbcc2d7abcfd | [
"Apache-2.0"
] | 1 | 2019-03-25T01:52:33.000Z | 2019-03-25T01:52:33.000Z | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "library/include/flutter_desktop_embedding/glfw/embedder.h"
#include <assert.h>
#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <flutter_embedder.h>
#include "library/common/glfw/key_event_handler.h"
#include "library/common/glfw/keyboard_hook_handler.h"
#include "library/common/glfw/text_input_plugin.h"
#include "library/common/internal/plugin_handler.h"
#ifdef __linux__
// For plugin-compatible event handling (e.g., modal windows).
#include <X11/Xlib.h>
#include <gtk/gtk.h>
#endif
// GLFW_TRUE & GLFW_FALSE are introduced since libglfw-3.3,
// add definitions here to compile under the old versions.
#ifndef GLFW_TRUE
#define GLFW_TRUE 1
#endif
#ifndef GLFW_FALSE
#define GLFW_FALSE 0
#endif
static_assert(FLUTTER_ENGINE_VERSION == 1, "");
static constexpr double kDpPerInch = 160.0;
// Struct for storing state within an instance of the GLFW Window.
struct FlutterEmbedderState {
FlutterEngine engine;
std::unique_ptr<flutter_desktop_embedding::PluginHandler> plugin_handler;
// Handlers for keyboard events from GLFW.
std::vector<std::unique_ptr<flutter_desktop_embedding::KeyboardHookHandler>>
keyboard_hook_handlers;
// The screen coordinates per inch on the primary monitor. Defaults to a sane
// value based on pixel_ratio 1.0.
double monitor_screen_coordinates_per_inch = kDpPerInch;
// The ratio of pixels per screen coordinate for the window.
double window_pixels_per_screen_coordinate = 1.0;
};
static constexpr char kDefaultWindowTitle[] = "Flutter";
// Retrieves state bag for the window in question from the GLFWWindow.
static FlutterEmbedderState *GetSavedEmbedderState(GLFWwindow *window) {
return reinterpret_cast<FlutterEmbedderState *>(
glfwGetWindowUserPointer(window));
}
// Returns the number of screen coordinates per inch for the main monitor.
// If the information is unavailable, returns a default value that assumes
// that a screen coordinate is one dp.
static double GetScreenCoordinatesPerInch() {
auto *primary_monitor = glfwGetPrimaryMonitor();
auto *primary_monitor_mode = glfwGetVideoMode(primary_monitor);
int primary_monitor_width_mm;
glfwGetMonitorPhysicalSize(primary_monitor, &primary_monitor_width_mm,
nullptr);
if (primary_monitor_width_mm == 0) {
return kDpPerInch;
}
return primary_monitor_mode->width / (primary_monitor_width_mm / 25.4);
}
// When GLFW calls back to the window with a framebuffer size change, notify
// FlutterEngine about the new window metrics.
// The Flutter pixel_ratio is defined as DPI/dp.
static void GLFWFramebufferSizeCallback(GLFWwindow *window, int width_px,
int height_px) {
int width;
glfwGetWindowSize(window, &width, nullptr);
auto state = GetSavedEmbedderState(window);
state->window_pixels_per_screen_coordinate = width_px / width;
double dpi = state->window_pixels_per_screen_coordinate *
state->monitor_screen_coordinates_per_inch;
FlutterWindowMetricsEvent event = {};
event.struct_size = sizeof(event);
event.width = width_px;
event.height = height_px;
event.pixel_ratio = dpi / kDpPerInch;
FlutterEngineSendWindowMetricsEvent(state->engine, &event);
}
// When GLFW calls back to the window with a cursor position move, forwards to
// FlutterEngine as a pointer event with appropriate phase.
static void GLFWCursorPositionCallbackAtPhase(GLFWwindow *window,
FlutterPointerPhase phase,
double x, double y) {
auto state = GetSavedEmbedderState(window);
FlutterPointerEvent event = {};
event.struct_size = sizeof(event);
event.phase = phase;
event.x = x * state->window_pixels_per_screen_coordinate;
event.y = y * state->window_pixels_per_screen_coordinate;
event.timestamp =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
FlutterEngineSendPointerEvent(state->engine, &event, 1);
}
// Reports cursor move to the Flutter engine.
static void GLFWCursorPositionCallback(GLFWwindow *window, double x, double y) {
GLFWCursorPositionCallbackAtPhase(window, FlutterPointerPhase::kMove, x, y);
}
// Reports mouse button press to the Flutter engine.
static void GLFWMouseButtonCallback(GLFWwindow *window, int key, int action,
int mods) {
double x, y;
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_PRESS) {
glfwGetCursorPos(window, &x, &y);
GLFWCursorPositionCallbackAtPhase(window, FlutterPointerPhase::kDown, x, y);
glfwSetCursorPosCallback(window, GLFWCursorPositionCallback);
}
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_RELEASE) {
glfwGetCursorPos(window, &x, &y);
GLFWCursorPositionCallbackAtPhase(window, FlutterPointerPhase::kUp, x, y);
glfwSetCursorPosCallback(window, nullptr);
}
}
// Passes character input events to registered handlers.
static void GLFWCharCallback(GLFWwindow *window, unsigned int code_point) {
for (const auto &handler :
GetSavedEmbedderState(window)->keyboard_hook_handlers) {
handler->CharHook(window, code_point);
}
}
// Passes raw key events to registered handlers.
static void GLFWKeyCallback(GLFWwindow *window, int key, int scancode,
int action, int mods) {
for (const auto &handler :
GetSavedEmbedderState(window)->keyboard_hook_handlers) {
handler->KeyboardHook(window, key, scancode, action, mods);
}
}
// Flushes event queue and then assigns default window callbacks.
static void GLFWAssignEventCallbacks(GLFWwindow *window) {
glfwPollEvents();
glfwSetKeyCallback(window, GLFWKeyCallback);
glfwSetCharCallback(window, GLFWCharCallback);
glfwSetMouseButtonCallback(window, GLFWMouseButtonCallback);
}
// Clears default window events.
static void GLFWClearEventCallbacks(GLFWwindow *window) {
glfwSetKeyCallback(window, nullptr);
glfwSetCharCallback(window, nullptr);
glfwSetMouseButtonCallback(window, nullptr);
}
// The Flutter Engine calls out to this function when new platform messages are
// available
static void GLFWOnFlutterPlatformMessage(const FlutterPlatformMessage *message,
void *user_data) {
if (message->struct_size != sizeof(FlutterPlatformMessage)) {
std::cerr << "Invalid message size received. Expected: "
<< sizeof(FlutterPlatformMessage) << " but received "
<< message->struct_size << std::endl;
return;
}
GLFWwindow *window = reinterpret_cast<GLFWwindow *>(user_data);
auto state = GetSavedEmbedderState(window);
state->plugin_handler->HandleMethodCallMessage(
message, [window] { GLFWClearEventCallbacks(window); },
[window] { GLFWAssignEventCallbacks(window); });
}
static bool GLFWMakeContextCurrent(void *user_data) {
GLFWwindow *window = reinterpret_cast<GLFWwindow *>(user_data);
glfwMakeContextCurrent(window);
return true;
}
static bool GLFWClearContext(void *user_data) {
glfwMakeContextCurrent(nullptr);
return true;
}
static bool GLFWPresent(void *user_data) {
GLFWwindow *window = reinterpret_cast<GLFWwindow *>(user_data);
glfwSwapBuffers(window);
return true;
}
static uint32_t GLFWGetActiveFbo(void *user_data) { return 0; }
// Clears the GLFW window to Material Blue-Grey.
//
// This function is primarily to fix an issue when the Flutter Engine is
// spinning up, wherein artifacts of existing windows are rendered onto the
// canvas for a few moments.
//
// This function isn't necessary, but makes starting the window much easier on
// the eyes.
static void GLFWClearCanvas(GLFWwindow *window) {
glfwMakeContextCurrent(window);
// This color is Material Blue Grey.
glClearColor(236.0 / 255.0, 239.0 / 255.0, 241.0 / 255.0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glFlush();
glfwSwapBuffers(window);
glfwMakeContextCurrent(nullptr);
}
// Resolves the address of the specified OpenGL or OpenGL ES
// core or extension function, if it is supported by the current context.
static void *GLFWProcResolver(void *user_data, const char *name) {
return reinterpret_cast<void *>(glfwGetProcAddress(name));
}
// Spins up an instance of the Flutter Engine.
//
// This function launches the Flutter Engine in a background thread, supplying
// the necessary callbacks for rendering within a GLFWwindow.
//
// Returns a caller-owned pointer to the engine.
static FlutterEngine RunFlutterEngine(
GLFWwindow *window, const std::string &main_path,
const std::string &assets_path, const std::string &packages_path,
const std::string &icu_data_path,
const std::vector<std::string> &arguments) {
std::vector<const char *> argv;
std::transform(
arguments.begin(), arguments.end(), std::back_inserter(argv),
[](const std::string &arg) -> const char * { return arg.c_str(); });
FlutterRendererConfig config = {};
config.type = kOpenGL;
config.open_gl.struct_size = sizeof(config.open_gl);
config.open_gl.make_current = GLFWMakeContextCurrent;
config.open_gl.clear_current = GLFWClearContext;
config.open_gl.present = GLFWPresent;
config.open_gl.fbo_callback = GLFWGetActiveFbo;
config.open_gl.gl_proc_resolver = GLFWProcResolver;
FlutterProjectArgs args = {};
args.struct_size = sizeof(FlutterProjectArgs);
args.assets_path = assets_path.c_str();
args.main_path = main_path.c_str();
args.packages_path = packages_path.c_str();
args.icu_data_path = icu_data_path.c_str();
args.command_line_argc = argv.size();
args.command_line_argv = &argv[0];
args.platform_message_callback = GLFWOnFlutterPlatformMessage;
FlutterEngine engine = nullptr;
auto result =
FlutterEngineRun(FLUTTER_ENGINE_VERSION, &config, &args, window, &engine);
if (result != kSuccess || engine == nullptr) {
return nullptr;
}
return engine;
}
namespace flutter_desktop_embedding {
// Initialize glfw
bool FlutterInit() { return glfwInit(); }
// Tear down glfw
void FlutterTerminate() { glfwTerminate(); }
PluginRegistrar *GetRegistrarForPlugin(GLFWwindow *flutter_window,
const std::string &plugin_name) {
auto *state = GetSavedEmbedderState(flutter_window);
// Currently, PluginHandler acts as the registrar for all plugins, so the
// name is ignored. It is part of the API to reduce churn in the future when
// aligning more closely with the Flutter registrar system.
return state->plugin_handler.get();
}
GLFWwindow *CreateFlutterWindowInSnapshotMode(
size_t initial_width, size_t initial_height, const std::string &assets_path,
const std::string &icu_data_path,
const std::vector<std::string> &arguments) {
return CreateFlutterWindow(initial_width, initial_height, "", assets_path, "",
icu_data_path, arguments);
}
GLFWwindow *CreateFlutterWindow(size_t initial_width, size_t initial_height,
const std::string &main_path,
const std::string &assets_path,
const std::string &packages_path,
const std::string &icu_data_path,
const std::vector<std::string> &arguments) {
#ifdef __linux__
gtk_init(0, nullptr);
#endif
auto window = glfwCreateWindow(initial_width, initial_height,
kDefaultWindowTitle, NULL, NULL);
if (window == nullptr) {
return nullptr;
}
GLFWClearCanvas(window);
auto engine = RunFlutterEngine(window, main_path, assets_path, packages_path,
icu_data_path, arguments);
if (engine == nullptr) {
glfwDestroyWindow(window);
return nullptr;
}
FlutterEmbedderState *state = new FlutterEmbedderState();
state->plugin_handler = std::make_unique<PluginHandler>(engine);
state->engine = engine;
// Set up the keyboard handlers.
state->keyboard_hook_handlers.push_back(
std::make_unique<KeyEventHandler>(state->plugin_handler.get()));
state->keyboard_hook_handlers.push_back(
std::make_unique<TextInputPlugin>(state->plugin_handler.get()));
glfwSetWindowUserPointer(window, state);
state->monitor_screen_coordinates_per_inch = GetScreenCoordinatesPerInch();
int width_px, height_px;
glfwGetFramebufferSize(window, &width_px, &height_px);
glfwSetFramebufferSizeCallback(window, GLFWFramebufferSizeCallback);
GLFWFramebufferSizeCallback(window, width_px, height_px);
GLFWAssignEventCallbacks(window);
return window;
}
void FlutterWindowLoop(GLFWwindow *flutter_window) {
#ifdef __linux__
// Necessary for GTK thread safety.
XInitThreads();
#endif
while (!glfwWindowShouldClose(flutter_window)) {
#ifdef __linux__
glfwPollEvents();
if (gtk_events_pending()) {
gtk_main_iteration();
}
#else
glfwWaitEvents();
#endif
// TODO(awdavies): This will be deprecated soon.
__FlutterEngineFlushPendingTasksNow();
}
auto state = GetSavedEmbedderState(flutter_window);
FlutterEngineShutdown(state->engine);
delete state;
glfwDestroyWindow(flutter_window);
}
} // namespace flutter_desktop_embedding
| 36.774536 | 80 | 0.728361 | [
"vector",
"transform"
] |
73441faab0cc5a9b4e6640da41c296aa6113cccb | 1,282 | hpp | C++ | src/common/abstractDataTypes/src/abstractDataTypes/SubsetUnion.hpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | 12 | 2017-02-17T10:33:51.000Z | 2022-03-01T02:48:10.000Z | src/common/abstractDataTypes/src/abstractDataTypes/SubsetUnion.hpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | 28 | 2017-10-17T20:23:52.000Z | 2021-03-04T16:07:13.000Z | src/common/abstractDataTypes/src/abstractDataTypes/SubsetUnion.hpp | vallesch/MDE4CPP | 7f8a01dd6642820913b2214d255bef2ea76be309 | [
"MIT"
] | 22 | 2017-03-24T19:03:58.000Z | 2022-03-31T12:10:07.000Z | /*
* SubsetUnion.hpp
*
* Created on: 12.05.2017
* Author: frbe5612
*/
#ifndef ABSTRACTDATATPYES_SUBSETUNION_HPP
#define ABSTRACTDATATPYES_SUBSETUNION_HPP
#include <memory>
#include <vector>
#include <iostream>
#include "abstractDataTypes/Subset.hpp"
#include "abstractDataTypes/Union.hpp"
template<class T, class ... U>
class SubsetUnion : public Subset<T, U ...>, public Union<T>
{
public:
SubsetUnion() : Subset<T, U ...>(), Union<T>()
{
}
SubsetUnion(std::shared_ptr<Union<U> > ... u) :
Subset<T, U ...>(u ...), Union<T>()
{
}
void initSubsetUnion(std::shared_ptr<Union<U> > ... u)
{
Subset<T,U ... >::initSubset(u ...);
}
typedef typename std::vector<std::shared_ptr<T> >::iterator iterator;
virtual ~SubsetUnion()
{
}
virtual void push_back(std::shared_ptr<T> el)
{
add(el);
}
virtual void add(std::shared_ptr<T> el)
{
Subset<T, U ...>::add(el);
}
void insert(const Bag<T> &b)
{
Subset<T, U ...>::insert(b);
}
void insert(iterator a, iterator b, iterator c)
{
Subset<T, U ...>::insert(a, b, c);
}
void insert(iterator a, std::shared_ptr<T> b)
{
Subset<T, U ...>::insert(a, b);
}
virtual void erase(std::shared_ptr<T> el)
{
Subset<T, U ...>::erase(el);
}
};
#endif
| 17.324324 | 71 | 0.602964 | [
"vector"
] |
734885bf69a6419b77a5d5d066d8e2277e48e60f | 675 | cpp | C++ | acmicpc.net/source/10471.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 7 | 2019-06-26T07:03:32.000Z | 2020-11-21T16:12:51.000Z | acmicpc.net/source/10471.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | null | null | null | acmicpc.net/source/10471.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 9 | 2019-02-28T03:34:54.000Z | 2020-12-18T03:02:40.000Z | // 10471. 공간을 만들어 봅시다
// 2021.09.09
// 브루트 포스
#include<iostream>
#include<set>
#include<vector>
using namespace std;
int arr[101];
int main()
{
int w, p;
cin >> w >> p;
vector<int> v;
v.push_back(0);
v.push_back(w);
for (int i = 0; i < p; i++)
{
int k;
cin >> k;
v.push_back(k);
}
set<int> s;
for (int i = 0; i < v.size(); i++)
{
for (int j = 0; j < v.size(); j++)
{
if (v[i] - v[j] != 0)
{
s.insert(abs(v[i] - v[j]));
}
}
}
for (auto num : s)
{
cout << num << " ";
}
cout << endl;
return 0;
}
| 15 | 43 | 0.386667 | [
"vector"
] |
735078e5a14656a7677c33cf9947b9bf9e549e47 | 4,247 | hpp | C++ | cppcache/src/ClientMetadata.hpp | davebarnes97/geode-native | 3f2333f4dc527d2ac799e55801e18d9048ddfd8a | [
"Apache-2.0"
] | null | null | null | cppcache/src/ClientMetadata.hpp | davebarnes97/geode-native | 3f2333f4dc527d2ac799e55801e18d9048ddfd8a | [
"Apache-2.0"
] | null | null | null | cppcache/src/ClientMetadata.hpp | davebarnes97/geode-native | 3f2333f4dc527d2ac799e55801e18d9048ddfd8a | [
"Apache-2.0"
] | 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.
*/
#pragma once
#ifndef GEODE_CLIENTMETADATA_H_
#define GEODE_CLIENTMETADATA_H_
#include <map>
#include <vector>
#include <geode/PartitionResolver.hpp>
#include "BucketServerLocation.hpp"
#include "FixedPartitionAttributesImpl.hpp"
#include "ReadWriteLock.hpp"
#include "ServerLocation.hpp"
#include "util/Log.hpp"
/*Stores the information such as partition attributes and meta data details*/
namespace apache {
namespace geode {
namespace client {
class ThinClientPoolDM;
class ClientMetadata;
typedef std::vector<std::shared_ptr<BucketServerLocation>>
BucketServerLocationsType;
// typedef std::map<int,BucketServerLocationsType >
// BucketServerLocationsListType;
typedef std::vector<BucketServerLocationsType> BucketServerLocationsListType;
typedef std::map<std::string, std::vector<int>> FixedMapType;
class ClientMetadata {
private:
void setPartitionNames();
std::shared_ptr<CacheableHashSet> m_partitionNames;
BucketServerLocationsListType m_bucketServerLocationsList;
std::shared_ptr<ClientMetadata> m_previousOne;
int m_totalNumBuckets;
// std::shared_ptr<PartitionResolver> m_partitionResolver;
std::string m_colocatedWith;
ThinClientPoolDM* m_tcrdm;
FixedMapType m_fpaMap;
inline void checkBucketId(size_t bucketId) {
if (bucketId >= m_bucketServerLocationsList.size()) {
LOGERROR("ClientMetadata::getServerLocation(): BucketId out of range.");
throw IllegalStateException(
"ClientMetadata::getServerLocation(): BucketId out of range.");
}
}
public:
void setPreviousone(std::shared_ptr<ClientMetadata> cptr) {
m_previousOne = cptr;
}
~ClientMetadata();
ClientMetadata();
ClientMetadata(
int totalNumBuckets, std::string colocatedWith, ThinClientPoolDM* tcrdm,
std::vector<std::shared_ptr<FixedPartitionAttributesImpl>>* fpaSet);
void getServerLocation(int bucketId, bool tryPrimary,
std::shared_ptr<BucketServerLocation>& serverLocation,
int8_t& version);
// ServerLocation getPrimaryServerLocation(int bucketId);
void updateBucketServerLocations(
int bucketId, BucketServerLocationsType bucketServerLocations);
int getTotalNumBuckets();
// std::shared_ptr<PartitionResolver> getPartitionResolver();
const std::string& getColocatedWith();
int assignFixedBucketId(const char* partitionName,
std::shared_ptr<CacheableKey> resolvekey);
std::shared_ptr<CacheableHashSet>& getFixedPartitionNames() {
/* if(m_fpaMap.size() >0)
{
auto partitionNames = CacheableHashSet::create();
for ( FixedMapType::iterator it=m_fpaMap.begin() ; it != m_fpaMap.end();
it++ ) {
partitionNames->insert(CacheableString::create(((*it).first).c_str()));
}
return partitionNames;
}*/
return m_partitionNames;
}
ClientMetadata(ClientMetadata& other);
ClientMetadata& operator=(const ClientMetadata&) = delete;
std::vector<std::shared_ptr<BucketServerLocation>> adviseServerLocations(
int bucketId);
std::shared_ptr<BucketServerLocation> advisePrimaryServerLocation(
int bucketId);
std::shared_ptr<BucketServerLocation> adviseRandomServerLocation();
void removeBucketServerLocation(
const std::shared_ptr<BucketServerLocation>& serverLocation);
std::string toString();
};
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_CLIENTMETADATA_H_
| 35.099174 | 80 | 0.745467 | [
"vector"
] |
735c0e23a474cedd5af37f1ce89aae0197d8ca74 | 15,929 | cc | C++ | test/ResidualTest.cc | zhonghongcheng/SVT-AV1 | 27b95fb35e5ea62dc6938b5350b70f7f0f8d9b88 | [
"BSD-2-Clause-Patent"
] | null | null | null | test/ResidualTest.cc | zhonghongcheng/SVT-AV1 | 27b95fb35e5ea62dc6938b5350b70f7f0f8d9b88 | [
"BSD-2-Clause-Patent"
] | null | null | null | test/ResidualTest.cc | zhonghongcheng/SVT-AV1 | 27b95fb35e5ea62dc6938b5350b70f7f0f8d9b88 | [
"BSD-2-Clause-Patent"
] | null | null | null | /*
* Copyright(c) 2019 Netflix, Inc.
* SPDX - License - Identifier: BSD - 2 - Clause - Patent
*/
/******************************************************************************
* @file ResidualTest.cc
*
* @brief Unit test for Residual related functions:
* - residual_kernel_avx2
* - residual_kernel16bit_sse2_intrin
* - residual_kernel_sub_sampled{w}x{h}_sse_intrin
* - sum_residual8bit_avx2_intrin
*
* @author Cidana-Ivy, Cidana-Wenyao
*
******************************************************************************/
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
#include <new>
// workaround to eliminate the compiling warning on linux
// The macro will conflict with definition in gtest.h
#ifdef __USE_GNU
#undef __USE_GNU // defined in EbThreads.h
#endif
#ifdef _GNU_SOURCE
#undef _GNU_SOURCE // defined in EbThreads.h
#endif
#include "EbDefinitions.h"
#include "EbPictureOperators.h"
#include "EbIntraPrediction.h"
#include "EbUtility.h"
#include "EbUnitTestUtility.h"
#include "aom_dsp_rtcd.h"
#include "random.h"
#include "util.h"
using svt_av1_test_tool::SVTRandom; // to generate the random
namespace {
typedef enum { VAL_MIN, VAL_MAX, VAL_RANDOM } TestPattern;
TestPattern TEST_PATTERNS[] = {VAL_MIN, VAL_MAX, VAL_RANDOM};
/**
* @Brief Base class for Residual related test, it will create input buffer,
* prediction buffer and two residual buffers to store the results.
*/
class ResidualTestBase : public ::testing::Test {
public:
ResidualTestBase(TestPattern test_pattern) {
test_pattern_ = test_pattern;
}
void SetUp() override {
input_ = (uint8_t *)eb_aom_memalign(8, test_size_);
pred_ = (uint8_t *)eb_aom_memalign(8, test_size_);
residual1_ = (int16_t *)eb_aom_memalign(16, 2 * test_size_);
residual2_ = (int16_t *)eb_aom_memalign(16, 2 * test_size_);
}
void TearDown() override {
if (input_)
eb_aom_free(input_);
if (pred_)
eb_aom_free(pred_);
if (residual1_)
eb_aom_free(residual1_);
if (residual2_)
eb_aom_free(residual2_);
}
protected:
virtual void prepare_data() {
const uint8_t mask = (1 << 8) - 1;
switch (test_pattern_) {
case VAL_MIN: {
memset(input_, 0, test_size_ * sizeof(input_[0]));
memset(pred_, 0, test_size_ * sizeof(pred_[0]));
break;
}
case VAL_MAX: {
memset(input_, mask, test_size_ * sizeof(input_[0]));
memset(pred_, 0, test_size_ * sizeof(pred_[0]));
break;
}
case VAL_RANDOM: {
eb_buf_random_u8(input_, test_size_);
eb_buf_random_u8(pred_, test_size_);
break;
}
default: break;
}
}
void check_residuals(uint32_t width, uint32_t height) {
int mismatched_count_ = 0;
for (uint32_t j = 0; j < height; j++) {
for (uint32_t k = 0; k < width; k++) {
if (residual1_[k + j * residual_stride_] !=
residual2_[k + j * residual_stride_])
++mismatched_count_;
}
}
EXPECT_EQ(0, mismatched_count_)
<< "compare residual result error"
<< "in test area for " << mismatched_count_ << " times";
}
TestPattern test_pattern_;
uint32_t area_width_, area_height_;
uint32_t input_stride_, pred_stride_, residual_stride_;
uint8_t *input_, *pred_;
int16_t *residual1_, *residual2_;
uint32_t test_size_;
};
typedef void (*residual_kernel8bit_func)(uint8_t *input, uint32_t input_stride,
uint8_t *pred, uint32_t pred_stride,
int16_t *residual, uint32_t residual_stride,
uint32_t area_width, uint32_t area_height);
static const residual_kernel8bit_func residual_kernel8bit_func_table[] = {
residual_kernel8bit_avx2,
#ifndef NON_AVX512_SUPPORT
residual_kernel8bit_avx512
#endif
};
typedef std::tuple<uint32_t, uint32_t> AreaSize;
AreaSize TEST_AREA_SIZES[] = {
AreaSize(4, 4), AreaSize(4, 8), AreaSize(8, 4), AreaSize(8, 8),
AreaSize(16, 16), AreaSize(4, 16), AreaSize(16, 4), AreaSize(16, 8),
AreaSize(8, 16), AreaSize(32, 32), AreaSize(32, 8), AreaSize(16, 32),
AreaSize(8, 32), AreaSize(32, 16), AreaSize(16, 64), AreaSize(64, 16),
AreaSize(64, 64), AreaSize(64, 32), AreaSize(32, 64), AreaSize(128, 128),
AreaSize(64, 128), AreaSize(128, 64)};
typedef std::tuple<AreaSize, TestPattern> TestResidualParam;
class ResidualKernelTest
: public ResidualTestBase,
public ::testing::WithParamInterface<TestResidualParam> {
public:
ResidualKernelTest() : ResidualTestBase(TEST_GET_PARAM(1)) {
area_width_ = std::get<0>(TEST_GET_PARAM(0));
area_height_ = std::get<1>(TEST_GET_PARAM(0));
input_stride_ = pred_stride_ = residual_stride_ = MAX_SB_SIZE;
test_size_ = MAX_SB_SQUARE;
input16bit_ = (uint16_t *)eb_aom_memalign(16, 2 * test_size_);
pred16bit_ = (uint16_t *)eb_aom_memalign(16, 2 * test_size_);
}
~ResidualKernelTest() {
if (input16bit_)
eb_aom_free(input16bit_);
if (pred16bit_)
eb_aom_free(pred16bit_);
}
protected:
void prepare_16bit_data() {
const uint16_t mask = (1 << 16) - 1;
switch (test_pattern_) {
case VAL_MIN: {
memset(input16bit_, 0, test_size_ * sizeof(input16bit_[0]));
memset(pred16bit_, 0, test_size_ * sizeof(pred16bit_[0]));
break;
}
case VAL_MAX: {
for (uint32_t i = 0; i < test_size_; ++i)
input16bit_[i] = mask;
memset(pred16bit_, 0, test_size_ * sizeof(pred16bit_[0]));
break;
}
case VAL_RANDOM: {
eb_buf_random_u16(input16bit_, test_size_);
eb_buf_random_u16(pred16bit_, test_size_);
break;
}
default: break;
}
}
void run_test() {
prepare_data();
residual_kernel8bit_c(input_,
input_stride_,
pred_,
pred_stride_,
residual1_,
residual_stride_,
area_width_,
area_height_);
for (int i = 0; i < sizeof(residual_kernel8bit_func_table) /
sizeof(*residual_kernel8bit_func_table);
i++) {
eb_buf_random_s16(residual2_, test_size_);
residual_kernel8bit_func_table[i](input_,
input_stride_,
pred_,
pred_stride_,
residual2_,
residual_stride_,
area_width_,
area_height_);
check_residuals(area_width_, area_height_);
}
}
void speed_test() {
double time_c, time_o;
uint64_t start_time_seconds, start_time_useconds;
uint64_t middle_time_seconds, middle_time_useconds;
uint64_t finish_time_seconds, finish_time_useconds;
const uint64_t num_loop = 10000000000 / (area_width_ * area_height_);
prepare_data();
EbStartTime(&start_time_seconds, &start_time_useconds);
for (uint64_t i = 0; i < num_loop; i++) {
residual_kernel8bit_c(input_,
input_stride_,
pred_,
pred_stride_,
residual1_,
residual_stride_,
area_width_,
area_height_);
}
EbStartTime(&middle_time_seconds, &middle_time_useconds);
EbComputeOverallElapsedTimeMs(start_time_seconds,
start_time_useconds,
middle_time_seconds,
middle_time_useconds,
&time_c);
for (int i = 0; i < sizeof(residual_kernel8bit_func_table) /
sizeof(*residual_kernel8bit_func_table);
i++) {
eb_buf_random_s16(residual2_, test_size_);
EbStartTime(&middle_time_seconds, &middle_time_useconds);
for (uint64_t j = 0; j < num_loop; j++) {
residual_kernel8bit_func_table[i](input_,
input_stride_,
pred_,
pred_stride_,
residual2_,
residual_stride_,
area_width_,
area_height_);
}
check_residuals(area_width_, area_height_);
EbStartTime(&finish_time_seconds, &finish_time_useconds);
EbComputeOverallElapsedTimeMs(middle_time_seconds,
middle_time_useconds,
finish_time_seconds,
finish_time_useconds,
&time_o);
printf("residual_kernel8bit(%3dx%3d): %6.2f\n",
area_width_,
area_height_,
time_c / time_o);
}
}
void run_16bit_test() {
prepare_16bit_data();
residual_kernel16bit_sse2_intrin(input16bit_,
input_stride_,
pred16bit_,
pred_stride_,
residual1_,
residual_stride_,
area_width_,
area_height_);
residual_kernel16bit_c(input16bit_,
input_stride_,
pred16bit_,
pred_stride_,
residual2_,
residual_stride_,
area_width_,
area_height_);
check_residuals(area_width_, area_height_);
}
uint16_t *input16bit_, *pred16bit_;
};
TEST_P(ResidualKernelTest, MatchTest) {
run_test();
};
TEST_P(ResidualKernelTest, DISABLED_SpeedTest) {
speed_test();
};
TEST_P(ResidualKernelTest, 16bitMatchTest) {
run_16bit_test();
};
INSTANTIATE_TEST_CASE_P(ResidualUtil, ResidualKernelTest,
::testing::Combine(::testing::ValuesIn(TEST_AREA_SIZES),
::testing::ValuesIn(TEST_PATTERNS)));
typedef void (*SUB_SAMPLED_TEST_FUNC)(uint8_t *input, uint32_t input_stride,
uint8_t *pred, uint32_t pred_stride,
int16_t *residual,
uint32_t residual_stride,
uint32_t area_width, uint32_t area_height,
uint8_t last_line);
typedef struct SubSampledParam {
AreaSize area_size;
SUB_SAMPLED_TEST_FUNC test_func;
} SubSampledParam;
SubSampledParam SUB_SAMPLED_PARAMS[] = {
{AreaSize(4, 4), &residual_kernel_sub_sampled4x4_sse_intrin},
{AreaSize(8, 8), &residual_kernel_sub_sampled8x8_sse2_intrin},
{AreaSize(16, 16), &residual_kernel_sub_sampled16x16_sse2_intrin},
{AreaSize(32, 32), &residual_kernel_sub_sampled32x32_sse2_intrin},
{AreaSize(64, 64), &residual_kernel_sub_sampled64x64_sse2_intrin}};
typedef std::tuple<TestPattern, SubSampledParam> TestSubParam;
class ResidualSubSampledTest
: public ResidualTestBase,
public ::testing::WithParamInterface<TestSubParam> {
public:
ResidualSubSampledTest() : ResidualTestBase(TEST_GET_PARAM(0)) {
area_width_ = std::get<0>(TEST_GET_PARAM(1).area_size);
area_height_ = std::get<1>(TEST_GET_PARAM(1).area_size);
sub_sampled_test_func_ = TEST_GET_PARAM(1).test_func;
input_stride_ = pred_stride_ = residual_stride_ = MAX_PU_SIZE;
test_size_ = MAX_PU_SIZE * MAX_PU_SIZE;
}
protected:
void run_sub_sample_test() {
prepare_data();
sub_sampled_test_func_(input_,
input_stride_,
pred_,
pred_stride_,
residual1_,
residual_stride_,
area_width_,
area_height_,
false);
residual_kernel_subsampled(input_,
input_stride_,
pred_,
pred_stride_,
residual2_,
residual_stride_,
area_width_,
area_height_,
false);
check_residuals(area_width_, area_height_);
}
SUB_SAMPLED_TEST_FUNC sub_sampled_test_func_;
};
TEST_P(ResidualSubSampledTest, MatchTest) {
run_sub_sample_test();
};
INSTANTIATE_TEST_CASE_P(
ResidualUtil, ResidualSubSampledTest,
::testing::Combine(::testing::ValuesIn(TEST_PATTERNS),
::testing::ValuesIn(SUB_SAMPLED_PARAMS)));
typedef std::tuple<int, TestPattern> TestSumParam;
class ResidualSumTest : public ::testing::Test,
public ::testing::WithParamInterface<TestSumParam> {
public:
ResidualSumTest() {
test_pattern_ = TEST_GET_PARAM(1);
size_ = TEST_GET_PARAM(0);
residual_stride_ = MAX_SB_SIZE;
residual_ = (int16_t *)eb_aom_memalign(16, 2 * MAX_SB_SQUARE);
}
~ResidualSumTest() {
if (residual_)
eb_aom_free(residual_);
}
protected:
void prepare_data() {
// There is an assumption in sum_residual8bit_avx2_intrin, which is
// 9bit or 11bit residual data.
const int16_t mask = (1 << 10) - 1;
SVTRandom rnd(-(1 << 10), mask);
switch (test_pattern_) {
case VAL_MIN: {
memset(residual_, 0, MAX_SB_SQUARE * sizeof(residual_[0]));
break;
}
case VAL_MAX: {
for (uint32_t i = 0; i < MAX_SB_SQUARE; ++i)
residual_[i] = mask;
break;
}
case VAL_RANDOM: {
for (uint32_t i = 0; i < MAX_SB_SQUARE; ++i)
residual_[i] = rnd.random();
break;
}
default: break;
}
}
void run_test() {
int32_t sum_block1 = 0, sum_block2 = 0;
prepare_data();
sum_block1 =
sum_residual8bit_avx2_intrin(residual_, size_, residual_stride_);
sum_block2 = sum_residual_c(residual_, size_, residual_stride_);
EXPECT_EQ(sum_block1, sum_block2)
<< "compare sum residual result error";
}
uint32_t size_;
TestPattern test_pattern_;
int16_t *residual_;
uint32_t residual_stride_;
};
TEST_P(ResidualSumTest, MatchTest) {
run_test();
};
INSTANTIATE_TEST_CASE_P(ResidualUtil, ResidualSumTest,
::testing::Combine(::testing::Values(4, 8, 16, 32, 64),
::testing::ValuesIn(TEST_PATTERNS)));
} // namespace
| 34.779476 | 80 | 0.536443 | [
"3d"
] |
735fe65c20e9e8945b5e6232c0baaed7fbd53cea | 33,967 | cpp | C++ | src/mlpack/tests/cf_test.cpp | PrakashChoure2002/mlpack | 21b0cb2e7c353047a1277d2972fc338e0131b0e6 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-12-14T22:37:05.000Z | 2020-12-14T22:37:05.000Z | src/mlpack/tests/cf_test.cpp | FeurialBlack/mlpack | ac500373a8b4eefacc21c916137c295f49edffb7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/tests/cf_test.cpp | FeurialBlack/mlpack | ac500373a8b4eefacc21c916137c295f49edffb7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @file tests/cf_test.cpp
* @author Mudit Raj Gupta
* @author Haritha Nair
*
* Test file for CF class.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/cf/cf.hpp>
#include <mlpack/methods/cf/decomposition_policies/batch_svd_method.hpp>
#include <mlpack/methods/cf/decomposition_policies/bias_svd_method.hpp>
#include <mlpack/methods/cf/decomposition_policies/randomized_svd_method.hpp>
#include <mlpack/methods/cf/decomposition_policies/regularized_svd_method.hpp>
#include <mlpack/methods/cf/decomposition_policies/svd_complete_method.hpp>
#include <mlpack/methods/cf/decomposition_policies/svd_incomplete_method.hpp>
#include <mlpack/methods/cf/decomposition_policies/svdplusplus_method.hpp>
#include <mlpack/methods/cf/normalization/no_normalization.hpp>
#include <mlpack/methods/cf/normalization/overall_mean_normalization.hpp>
#include <mlpack/methods/cf/normalization/user_mean_normalization.hpp>
#include <mlpack/methods/cf/normalization/item_mean_normalization.hpp>
#include <mlpack/methods/cf/normalization/z_score_normalization.hpp>
#include <mlpack/methods/cf/normalization/combined_normalization.hpp>
#include <mlpack/methods/cf/neighbor_search_policies/lmetric_search.hpp>
#include <mlpack/methods/cf/neighbor_search_policies/cosine_search.hpp>
#include <mlpack/methods/cf/neighbor_search_policies/pearson_search.hpp>
#include <mlpack/methods/cf/interpolation_policies/average_interpolation.hpp>
#include <mlpack/methods/cf/interpolation_policies/similarity_interpolation.hpp>
#include <mlpack/methods/cf/interpolation_policies/regression_interpolation.hpp>
#include <iostream>
#include "catch.hpp"
#include "test_catch_tools.hpp"
#include "serialization_catch.hpp"
using namespace mlpack;
using namespace mlpack::cf;
using namespace std;
// Get train and test datasets.
static void GetDatasets(arma::mat& dataset, arma::mat& savedCols)
{
if (!data::Load("GroupLensSmall.csv", dataset))
FAIL("Cannot load test dataset GroupLensSmall.csv!");
savedCols.set_size(3, 50);
// Save the columns we've removed.
savedCols.fill(/* random very large value */ 10000000);
size_t currentCol = 0;
for (size_t i = 0; i < dataset.n_cols; ++i)
{
if (currentCol == 50)
break;
if (dataset(2, i) > 4.5) // 5-star rating.
{
// Make sure we don't have this user yet. This is a slow way to do this
// but I don't particularly care here because it's in the tests.
bool found = false;
for (size_t j = 0; j < currentCol; ++j)
{
if (savedCols(0, j) == dataset(0, i))
{
found = true;
break;
}
}
// If this user doesn't already exist in savedCols, add them.
// Otherwise ignore this point.
if (!found)
{
savedCols.col(currentCol) = dataset.col(i);
dataset.shed_col(i);
++currentCol;
}
}
}
}
/**
* Make sure that correct number of recommendations are generated when query
* set. Default case.
*/
template<typename DecompositionPolicy>
void GetRecommendationsAllUsers()
{
DecompositionPolicy decomposition;
// Dummy number of recommendations.
size_t numRecs = 3;
// GroupLensSmall.csv dataset has 200 users.
size_t numUsers = 200;
// Matrix to save recommendations into.
arma::Mat<size_t> recommendations;
// Load GroupLens data.
arma::mat dataset;
if (!data::Load("GroupLensSmall.csv", dataset))
FAIL("Cannot load test dataset GroupLensSamll.csv!");
CFType<DecompositionPolicy> c(dataset, decomposition, 5, 5, 30);
// Generate recommendations when query set is not specified.
c.GetRecommendations(numRecs, recommendations);
// Check if correct number of recommendations are generated.
REQUIRE(recommendations.n_rows == numRecs);
// Check if recommendations are generated for all users.
REQUIRE(recommendations.n_cols == numUsers);
}
/**
* Make sure that the recommendations are generated for queried users only.
*/
template<typename DecompositionPolicy>
void GetRecommendationsQueriedUser()
{
DecompositionPolicy decomposition;
// Number of users that we will search for recommendations for.
size_t numUsers = 10;
// Default number of recommendations.
size_t numRecsDefault = 5;
// Create dummy query set.
arma::Col<size_t> users = arma::zeros<arma::Col<size_t> >(numUsers, 1);
for (size_t i = 0; i < numUsers; ++i)
users(i) = i;
// Matrix to save recommendations into.
arma::Mat<size_t> recommendations;
// Load GroupLens data.
arma::mat dataset;
if (!data::Load("GroupLensSmall.csv", dataset))
FAIL("Cannot load test dataset GroupLensSmall.csv!");
CFType<DecompositionPolicy> c(dataset, decomposition, 5, 5, 30);
// Generate recommendations when query set is specified.
c.GetRecommendations(numRecsDefault, recommendations, users);
// Check if correct number of recommendations are generated.
REQUIRE(recommendations.n_rows == numRecsDefault);
// Check if recommendations are generated for the right number of users.
REQUIRE(recommendations.n_cols == numUsers);
}
/**
* Make sure recommendations that are generated are reasonably accurate.
*/
template<typename DecompositionPolicy,
typename NormalizationType = NoNormalization>
void RecommendationAccuracy(const size_t allowedFailures = 17)
{
DecompositionPolicy decomposition;
// Small GroupLens dataset.
arma::mat dataset;
// Save the columns we've removed.
arma::mat savedCols;
GetDatasets(dataset, savedCols);
CFType<DecompositionPolicy,
NormalizationType> c(dataset, decomposition, 5, 5, 30);
// Obtain 150 recommendations for the users in savedCols, and make sure the
// missing item shows up in most of them. First, create the list of users,
// which requires casting from doubles...
arma::Col<size_t> users(50);
for (size_t i = 0; i < 50; ++i)
users(i) = (size_t) savedCols(0, i);
arma::Mat<size_t> recommendations;
size_t numRecs = 150;
c.GetRecommendations(numRecs, recommendations, users);
REQUIRE(recommendations.n_rows == numRecs);
REQUIRE(recommendations.n_cols == 50);
size_t failures = 0;
for (size_t i = 0; i < 50; ++i)
{
size_t targetItem = (size_t) savedCols(1, i);
bool found = false;
// Make sure the target item shows up in the recommendations.
for (size_t j = 0; j < numRecs; ++j)
{
const size_t user = users(i);
const size_t item = recommendations(j, i);
if (item == targetItem)
{
found = true;
}
else
{
// Make sure we aren't being recommended an item that the user already
// rated.
REQUIRE((double) c.CleanedData()(item, user) == 0.0);
}
}
if (!found)
++failures;
}
// Make sure the right item showed up in at least 2/3 of the recommendations.
REQUIRE(failures < allowedFailures);
}
// Make sure that Predict() is returning reasonable results.
template<typename DecompositionPolicy,
typename NormalizationType = OverallMeanNormalization,
typename NeighborSearchPolicy = EuclideanSearch,
typename InterpolationPolicy = AverageInterpolation>
void CFPredict(const double rmseBound = 1.5)
{
DecompositionPolicy decomposition;
// Small GroupLens dataset.
arma::mat dataset;
// Save the columns we've removed.
arma::mat savedCols;
GetDatasets(dataset, savedCols);
CFType<DecompositionPolicy,
NormalizationType> c(dataset, decomposition, 5, 5, 30);
// Now, for each removed rating, make sure the prediction is... reasonably
// accurate.
double totalError = 0.0;
for (size_t i = 0; i < savedCols.n_cols; ++i)
{
const double prediction = c.template Predict<NeighborSearchPolicy,
InterpolationPolicy>(savedCols(0, i), savedCols(1, i));
const double error = std::pow(prediction - savedCols(2, i), 2.0);
totalError += error;
}
const double rmse = std::sqrt(totalError / savedCols.n_cols);
// The root mean square error should be less than ?.
REQUIRE(rmse < rmseBound);
}
// Do the same thing as the previous test, but ensure that the ratings we
// predict with the batch Predict() are the same as the individual Predict()
// calls.
template<typename DecompositionPolicy>
void BatchPredict()
{
DecompositionPolicy decomposition;
// Small GroupLens dataset.
arma::mat dataset;
// Save the columns we've removed.
arma::mat savedCols;
GetDatasets(dataset, savedCols);
CFType<DecompositionPolicy> c(dataset, decomposition, 5, 5, 30);
// Get predictions for all user/item pairs we held back.
arma::Mat<size_t> combinations(2, savedCols.n_cols);
for (size_t i = 0; i < savedCols.n_cols; ++i)
{
combinations(0, i) = size_t(savedCols(0, i));
combinations(1, i) = size_t(savedCols(1, i));
}
arma::vec predictions;
c.Predict(combinations, predictions);
for (size_t i = 0; i < combinations.n_cols; ++i)
{
const double prediction = c.Predict(combinations(0, i), combinations(1, i));
REQUIRE(prediction == Approx(predictions[i]).epsilon(1e-10));
}
}
/**
* Make sure we can train an already-trained model and it works okay.
*/
template<typename DecompositionPolicy>
void Train(DecompositionPolicy& decomposition)
{
// Generate random data.
arma::sp_mat randomData;
randomData.sprandu(100, 100, 0.3);
CFType<DecompositionPolicy> c(randomData, decomposition, 5, 5, 30);
// Small GroupLens dataset.
arma::mat dataset;
// Save the columns we've removed.
arma::mat savedCols;
GetDatasets(dataset, savedCols);
// Make data into sparse matrix.
arma::sp_mat cleanedData;
CFType<DecompositionPolicy>::CleanData(dataset, cleanedData);
// Now retrain.
c.Train(dataset, decomposition, 30);
// Get predictions for all user/item pairs we held back.
arma::Mat<size_t> combinations(2, savedCols.n_cols);
for (size_t i = 0; i < savedCols.n_cols; ++i)
{
combinations(0, i) = size_t(savedCols(0, i));
combinations(1, i) = size_t(savedCols(1, i));
}
arma::vec predictions;
c.Predict(combinations, predictions);
for (size_t i = 0; i < combinations.n_cols; ++i)
{
const double prediction = c.Predict(combinations(0, i),
combinations(1, i));
REQUIRE(prediction == Approx(predictions[i]).epsilon(1e-10));
}
}
/**
* Make sure we can train an already-trained model and it works okay
* for policies that use coordinate lists.
*/
template<typename DecompositionPolicy>
void TrainWithCoordinateList(DecompositionPolicy& decomposition)
{
arma::mat randomData(3, 100);
randomData.row(0) = arma::linspace<arma::rowvec>(0, 99, 100);
randomData.row(1) = arma::linspace<arma::rowvec>(0, 99, 100);
randomData.row(2).fill(3);
CFType<DecompositionPolicy> c(randomData, decomposition, 5, 5, 30);
// Now retrain with data we know about.
// Small GroupLens dataset.
arma::mat dataset;
// Save the columns we've removed.
arma::mat savedCols;
GetDatasets(dataset, savedCols);
// Now retrain.
c.Train(dataset, decomposition, 30);
// Get predictions for all user/item pairs we held back.
arma::Mat<size_t> combinations(2, savedCols.n_cols);
for (size_t i = 0; i < savedCols.n_cols; ++i)
{
combinations(0, i) = size_t(savedCols(0, i));
combinations(1, i) = size_t(savedCols(1, i));
}
arma::vec predictions;
c.Predict(combinations, predictions);
for (size_t i = 0; i < combinations.n_cols; ++i)
{
const double prediction = c.Predict(combinations(0, i), combinations(1, i));
REQUIRE(prediction == Approx(predictions[i]).epsilon(1e-10));
}
}
/**
* Make sure we can train a model after using the empty constructor.
*/
template<typename DecompositionPolicy>
void EmptyConstructorTrain()
{
DecompositionPolicy decomposition;
// Use default constructor.
CFType<DecompositionPolicy> c;
// Now retrain with data we know about.
// Small GroupLens dataset.
arma::mat dataset;
// Save the columns we've removed.
arma::mat savedCols;
GetDatasets(dataset, savedCols);
c.Train(dataset, decomposition, 30);
// Get predictions for all user/item pairs we held back.
arma::Mat<size_t> combinations(2, savedCols.n_cols);
for (size_t i = 0; i < savedCols.n_cols; ++i)
{
combinations(0, i) = size_t(savedCols(0, i));
combinations(1, i) = size_t(savedCols(1, i));
}
arma::vec predictions;
c.Predict(combinations, predictions);
for (size_t i = 0; i < combinations.n_cols; ++i)
{
const double prediction = c.Predict(combinations(0, i),
combinations(1, i));
REQUIRE(prediction == Approx(predictions[i]).epsilon(1e-10));
}
}
/**
* Ensure we can load and save the CF model.
*/
template<typename DecompositionPolicy,
typename NormalizationType = NoNormalization>
void Serialization()
{
DecompositionPolicy decomposition;
// Load a dataset to train on.
arma::mat dataset;
if (!data::Load("GroupLensSmall.csv", dataset))
FAIL("Cannot load test dataset GroupLensSmall.csv!");
arma::sp_mat cleanedData;
CFType<DecompositionPolicy,
NormalizationType>::CleanData(dataset, cleanedData);
CFType<DecompositionPolicy,
NormalizationType> c(cleanedData, decomposition, 5, 5, 30);
arma::sp_mat randomData;
randomData.sprandu(100, 100, 0.3);
CFType<DecompositionPolicy,
NormalizationType> cXml(randomData, decomposition, 5, 5, 30);
CFType<DecompositionPolicy,
NormalizationType> cBinary;
CFType<DecompositionPolicy,
NormalizationType> cText(cleanedData, decomposition, 5, 5, 30);
SerializeObjectAll(c, cXml, cText, cBinary);
// Check the internals.
REQUIRE(c.NumUsersForSimilarity() == cXml.NumUsersForSimilarity());
REQUIRE(c.NumUsersForSimilarity() == cBinary.NumUsersForSimilarity());
REQUIRE(c.NumUsersForSimilarity() == cText.NumUsersForSimilarity());
REQUIRE(c.Rank() == cXml.Rank());
REQUIRE(c.Rank() == cBinary.Rank());
REQUIRE(c.Rank() == cText.Rank());
CheckMatrices(c.Decomposition().W(), cXml.Decomposition().W(),
cBinary.Decomposition().W(), cText.Decomposition().W());
CheckMatrices(c.Decomposition().H(), cXml.Decomposition().H(),
cBinary.Decomposition().H(), cText.Decomposition().H());
REQUIRE(c.CleanedData().n_rows == cXml.CleanedData().n_rows);
REQUIRE(c.CleanedData().n_rows == cBinary.CleanedData().n_rows);
REQUIRE(c.CleanedData().n_rows == cText.CleanedData().n_rows);
REQUIRE(c.CleanedData().n_cols == cXml.CleanedData().n_cols);
REQUIRE(c.CleanedData().n_cols == cBinary.CleanedData().n_cols);
REQUIRE(c.CleanedData().n_cols == cText.CleanedData().n_cols);
REQUIRE(c.CleanedData().n_nonzero == cXml.CleanedData().n_nonzero);
REQUIRE(c.CleanedData().n_nonzero == cBinary.CleanedData().n_nonzero);
REQUIRE(c.CleanedData().n_nonzero == cText.CleanedData().n_nonzero);
c.CleanedData().sync();
for (size_t i = 0; i <= c.CleanedData().n_cols; ++i)
{
REQUIRE(c.CleanedData().col_ptrs[i] == cXml.CleanedData().col_ptrs[i]);
REQUIRE(c.CleanedData().col_ptrs[i] == cBinary.CleanedData().col_ptrs[i]);
REQUIRE(c.CleanedData().col_ptrs[i] == cText.CleanedData().col_ptrs[i]);
}
for (size_t i = 0; i <= c.CleanedData().n_nonzero; ++i)
{
REQUIRE(c.CleanedData().row_indices[i] ==
cXml.CleanedData().row_indices[i]);
REQUIRE(c.CleanedData().row_indices[i] ==
cBinary.CleanedData().row_indices[i]);
REQUIRE(c.CleanedData().row_indices[i] ==
cText.CleanedData().row_indices[i]);
REQUIRE(c.CleanedData().values[i] ==
Approx(cXml.CleanedData().values[i]).epsilon(1e-7));
REQUIRE(c.CleanedData().values[i] ==
Approx(cBinary.CleanedData().values[i]).epsilon(1e-7));
REQUIRE(c.CleanedData().values[i] ==
Approx(cText.CleanedData().values[i]).epsilon(1e-7));
}
}
/**
* Make sure that correct number of recommendations are generated when query
* set for randomized SVD.
*/
TEST_CASE("CFGetRecommendationsAllUsersRandSVDTest", "[CFTest]")
{
GetRecommendationsAllUsers<RandomizedSVDPolicy>();
}
/**
* Make sure that correct number of recommendations are generated when query
* set for regularized SVD.
*/
TEST_CASE("CFGetRecommendationsAllUsersRegSVDTest", "[CFTest]")
{
GetRecommendationsAllUsers<RegSVDPolicy>();
}
/**
* Make sure that correct number of recommendations are generated when query
* set for Batch SVD.
*/
TEST_CASE("CFGetRecommendationsAllUsersBatchSVDTest", "[CFTest]")
{
GetRecommendationsAllUsers<BatchSVDPolicy>();
}
/**
* Make sure that correct number of recommendations are generated when query
* set for NMF.
*/
TEST_CASE("CFGetRecommendationsAllUsersNMFTest", "[CFTest]")
{
GetRecommendationsAllUsers<NMFPolicy>();
}
/**
* Make sure that correct number of recommendations are generated when query
* set for SVD Complete Incremental method.
*/
TEST_CASE("CFGetRecommendationsAllUsersSVDCompleteTest", "[CFTest]")
{
GetRecommendationsAllUsers<SVDCompletePolicy>();
}
/**
* Make sure that correct number of recommendations are generated when query
* set for SVD Incomplete Incremental method.
*/
TEST_CASE("CFGetRecommendationsAllUsersSVDIncompleteTest", "[CFTest]")
{
GetRecommendationsAllUsers<SVDIncompletePolicy>();
}
/**
* Make sure that correct number of recommendations are generated when query
* set for Bias SVD method.
*/
TEST_CASE("CFGetRecommendationsAllUsersBiasSVDTest", "[CFTest]")
{
GetRecommendationsAllUsers<BiasSVDPolicy>();
}
/**
* Make sure that correct number of recommendations are generated when query
* set for SVDPlusPlus method.
*/
TEST_CASE("CFGetRecommendationsAllUsersSVDPPTest", "[CFTest]")
{
GetRecommendationsAllUsers<SVDPlusPlusPolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for randomized SVD.
*/
TEST_CASE("CFGetRecommendationsQueriedUserRandSVDTest", "[CFTest]")
{
GetRecommendationsQueriedUser<RandomizedSVDPolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for regularized SVD.
*/
TEST_CASE("CFGetRecommendationsQueriedUserRegSVDTest", "[CFTest]")
{
GetRecommendationsQueriedUser<RegSVDPolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for batch SVD.
*/
TEST_CASE("CFGetRecommendationsQueriedUserBatchSVDTest", "[CFTest]")
{
GetRecommendationsQueriedUser<BatchSVDPolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for NMF.
*/
TEST_CASE("CFGetRecommendationsQueriedUserNMFTest", "[CFTest]")
{
GetRecommendationsQueriedUser<NMFPolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for SVD Complete Incremental method.
*/
TEST_CASE("CFGetRecommendationsQueriedUserSVDCompleteTest", "[CFTest]")
{
GetRecommendationsQueriedUser<SVDCompletePolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for SVD Incomplete Incremental method.
*/
TEST_CASE("CFGetRecommendationsQueriedUserSVDIncompleteTest", "[CFTest]")
{
GetRecommendationsQueriedUser<SVDIncompletePolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for Bias SVD method.
*/
TEST_CASE("CFGetRecommendationsQueriedUserBiasSVDTest", "[CFTest]")
{
GetRecommendationsQueriedUser<BiasSVDPolicy>();
}
/**
* Make sure that the recommendations are generated for queried users only
* for SVDPlusPlus method.
*/
TEST_CASE("CFGetRecommendationsQueriedUserSVDPPTest", "[CFTest]")
{
GetRecommendationsQueriedUser<SVDPlusPlusPolicy>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for randomized SVD.
*/
TEST_CASE("RecommendationAccuracyRandSVDTest", "[CFTest]")
{
RecommendationAccuracy<RandomizedSVDPolicy>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for regularized SVD.
*/
TEST_CASE("RecommendationAccuracyRegSVDTest", "[CFTest]")
{
RecommendationAccuracy<RegSVDPolicy>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for batch SVD.
*/
TEST_CASE("RecommendationAccuracyBatchSVDTest", "[CFTest]")
{
RecommendationAccuracy<BatchSVDPolicy>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for NMF.
*/
TEST_CASE("RecommendationAccuracyNMFTest", "[CFTest]")
{
RecommendationAccuracy<NMFPolicy>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for SVD Complete Incremental method.
*/
TEST_CASE("RecommendationAccuracySVDCompleteTest", "[CFTest]")
{
RecommendationAccuracy<SVDCompletePolicy>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for SVD Incomplete Incremental method.
*/
TEST_CASE("RecommendationAccuracySVDIncompleteTest", "[CFTest]")
{
RecommendationAccuracy<SVDIncompletePolicy>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for Bias SVD method.
*/
TEST_CASE("RecommendationAccuracyBiasSVDTest", "[CFTest]")
{
// This algorithm seems to be far less effective than others.
// We therefore allow failures on 44% of the runs.
RecommendationAccuracy<BiasSVDPolicy>(22);
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for SVDPlusPlus method.
*/
// This test is commented out because it fails and we haven't solved it yet.
// Please refer to issue #1501 for more info about this test.
// TEST_CASE("RecommendationAccuracySVDPPTest", "[CFTest]")
// {
// RecommendationAccuracy<SVDPlusPlusPolicy>();
// }
// Make sure that Predict() is returning reasonable results for randomized SVD.
TEST_CASE("CFPredictRandSVDTest", "[CFTest]")
{
CFPredict<RandomizedSVDPolicy>();
}
// Make sure that Predict() is returning reasonable results for regularized SVD.
TEST_CASE("CFPredictRegSVDTest", "[CFTest]")
{
CFPredict<RegSVDPolicy>();
}
// Make sure that Predict() is returning reasonable results for batch SVD.
TEST_CASE("CFPredictBatchSVDTest", "[CFTest]")
{
CFPredict<BatchSVDPolicy>();
}
// Make sure that Predict() is returning reasonable results for NMF.
TEST_CASE("CFPredictNMFTest", "[CFTest]")
{
CFPredict<NMFPolicy>();
}
/**
* Make sure that Predict() is returning reasonable results for SVD Complete
* Incremental method.
*/
TEST_CASE("CFPredictSVDCompleteTest", "[CFTest]")
{
CFPredict<SVDCompletePolicy>();
}
/**
* Make sure that Predict() is returning reasonable results for SVD Incomplete
* Incremental method.
*/
TEST_CASE("CFPredictSVDIncompleteTest", "[CFTest]")
{
CFPredict<SVDIncompletePolicy>();
}
/**
* Make sure that Predict() is returning reasonable results for Bias SVD
* method.
*/
TEST_CASE("CFPredictBiasSVDTest", "[CFTest]")
{
CFPredict<BiasSVDPolicy>();
}
/**
* Make sure that Predict() is returning reasonable results for SVDPlusPlus
* method.
*/
TEST_CASE("CFPredictSVDPPTest", "[CFTest]")
{
CFPredict<SVDPlusPlusPolicy>();
}
// Compare batch Predict() and individual Predict() for randomized SVD.
TEST_CASE("CFBatchPredictRandSVDTest", "[CFTest]")
{
BatchPredict<RandomizedSVDPolicy>();
}
// Compare batch Predict() and individual Predict() for regularized SVD.
TEST_CASE("CFBatchPredictRegSVDTest", "[CFTest]")
{
BatchPredict<RegSVDPolicy>();
}
// Compare batch Predict() and individual Predict() for batch SVD.
TEST_CASE("CFBatchPredictBatchSVDTest", "[CFTest]")
{
BatchPredict<BatchSVDPolicy>();
}
// Compare batch Predict() and individual Predict() for NMF.
TEST_CASE("CFBatchPredictNMFTest", "[CFTest]")
{
BatchPredict<NMFPolicy>();
}
// Compare batch Predict() and individual Predict() for
// SVD Complete Incremental method.
TEST_CASE("CFBatchPredictSVDCompleteTest", "[CFTest]")
{
BatchPredict<SVDCompletePolicy>();
}
// Compare batch Predict() and individual Predict() for
// SVD Incomplete Incremental method.
TEST_CASE("CFBatchPredictSVDIncompleteTest", "[CFTest]")
{
BatchPredict<SVDIncompletePolicy>();
}
// Compare batch Predict() and individual Predict() for
// Bias SVD method.
TEST_CASE("CFBatchPredictBiasSVDTest", "[CFTest]")
{
BatchPredict<BiasSVDPolicy>();
}
// Compare batch Predict() and individual Predict() for
// SVDPlusPlus method.
TEST_CASE("CFBatchPredictSVDPPTest", "[CFTest]")
{
BatchPredict<SVDPlusPlusPolicy>();
}
/**
* Make sure we can train an already-trained model and it works okay for
* randomized SVD.
*/
TEST_CASE("TrainRandSVDTest", "[CFTest]")
{
RandomizedSVDPolicy decomposition;
Train(decomposition);
}
/**
* Make sure we can train an already-trained model and it works okay for
* regularized SVD.
*/
TEST_CASE("TrainRegSVDTest", "[CFTest]")
{
RegSVDPolicy decomposition;
TrainWithCoordinateList(decomposition);
}
/**
* Make sure we can train an already-trained model and it works okay for
* batch SVD.
*/
TEST_CASE("TrainBatchSVDTest", "[CFTest]")
{
BatchSVDPolicy decomposition;
Train(decomposition);
}
/**
* Make sure we can train an already-trained model and it works okay for
* NMF.
*/
TEST_CASE("TrainNMFTest", "[CFTest]")
{
NMFPolicy decomposition;
Train(decomposition);
}
/**
* Make sure we can train an already-trained model and it works okay for
* SVD Complete Incremental method.
*/
TEST_CASE("TrainSVDCompleteTest", "[CFTest]")
{
SVDCompletePolicy decomposition;
Train(decomposition);
}
/**
* Make sure we can train an already-trained model and it works okay for
* SVD Incomplete Incremental method.
*/
TEST_CASE("TrainSVDIncompleteTest", "[CFTest]")
{
SVDIncompletePolicy decomposition;
Train(decomposition);
}
/**
* Make sure we can train an already-trained model and it works okay for
* BiasSVD method.
*/
TEST_CASE("TrainBiasSVDTest", "[CFTest]")
{
BiasSVDPolicy decomposition;
TrainWithCoordinateList(decomposition);
}
/**
* Make sure we can train an already-trained model and it works okay for
* SVDPlusPlus method.
*/
TEST_CASE("TrainSVDPPTest", "[CFTest]")
{
SVDPlusPlusPolicy decomposition;
TrainWithCoordinateList(decomposition);
}
/**
* Make sure we can train a model after using the empty constructor when
* using randomized SVD.
*/
TEST_CASE("EmptyConstructorTrainRandSVDTest", "[CFTest]")
{
EmptyConstructorTrain<RandomizedSVDPolicy>();
}
/**
* Make sure we can train a model after using the empty constructor when
* using regularized SVD.
*/
TEST_CASE("EmptyConstructorTrainRegSVDTest", "[CFTest]")
{
EmptyConstructorTrain<RegSVDPolicy>();
}
/**
* Make sure we can train a model after using the empty constructor when
* using batch SVD.
*/
TEST_CASE("EmptyConstructorTrainBatchSVDTest", "[CFTest]")
{
EmptyConstructorTrain<BatchSVDPolicy>();
}
/**
* Make sure we can train a model after using the empty constructor when
* using NMF.
*/
TEST_CASE("EmptyConstructorTrainNMFTest", "[CFTest]")
{
EmptyConstructorTrain<NMFPolicy>();
}
/**
* Make sure we can train a model after using the empty constructor when
* using SVD Complete Incremental method.
*/
TEST_CASE("EmptyConstructorTrainSVDCompleteTest", "[CFTest]")
{
EmptyConstructorTrain<SVDCompletePolicy>();
}
/**
* Make sure we can train a model after using the empty constructor when
* using SVD Incomplete Incremental method.
*/
TEST_CASE("EmptyConstructorTrainSVDIncompleteTest", "[CFTest]")
{
EmptyConstructorTrain<SVDIncompletePolicy>();
}
/**
* Ensure we can load and save the CF model using randomized SVD policy.
*/
TEST_CASE("SerializationRandSVDTest", "[CFTest]")
{
Serialization<RandomizedSVDPolicy>();
}
/**
* Ensure we can load and save the CF model using batch SVD policy.
*/
TEST_CASE("SerializationBatchSVDTest", "[CFTest]")
{
Serialization<BatchSVDPolicy>();
}
/**
* Ensure we can load and save the CF model using NMF policy.
*/
TEST_CASE("SerializationNMFTest", "[CFTest]")
{
Serialization<NMFPolicy>();
}
/**
* Ensure we can load and save the CF model using SVD Complete Incremental.
*/
TEST_CASE("SerializationSVDCompleteTest", "[CFTest]")
{
Serialization<SVDCompletePolicy>();
}
/**
* Ensure we can load and save the CF model using SVD Incomplete Incremental.
*/
TEST_CASE("SerializationSVDIncompleteTest", "[CFTest]")
{
Serialization<SVDIncompletePolicy>();
}
/**
* Make sure that Predict() is returning reasonable results for NMF and
* OverallMeanNormalization.
*/
TEST_CASE("CFPredictOverallMeanNormalization", "[CFTest]")
{
CFPredict<NMFPolicy, OverallMeanNormalization>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for NMF and
* UserMeanNormalization.
*/
TEST_CASE("CFPredictUserMeanNormalization", "[CFTest]")
{
CFPredict<NMFPolicy, UserMeanNormalization>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for NMF and
* ItemMeanNormalization.
*/
TEST_CASE("CFPredictItemMeanNormalization", "[CFTest]")
{
CFPredict<NMFPolicy, ItemMeanNormalization>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for NMF and
* ZScoreNormalization.
*/
TEST_CASE("CFPredictZScoreNormalization", "[CFTest]")
{
CFPredict<NMFPolicy, ZScoreNormalization>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for NMF and
* CombinedNormalization<OverallMeanNormalization, UserMeanNormalization,
* ItemMeanNormalization>.
*/
TEST_CASE("CFPredictCombinedNormalization", "[CFTest]")
{
CFPredict<NMFPolicy,
CombinedNormalization<
OverallMeanNormalization,
UserMeanNormalization,
ItemMeanNormalization>>(2.0);
}
/**
* Make sure that Predict() works with NoNormalization.
*/
TEST_CASE("CFPredictNoNormalization", "[CFTest]")
{
CFPredict<RegSVDPolicy, NoNormalization>(2.0);
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for OverallMeanNormalization.
*/
TEST_CASE("RecommendationAccuracyOverallMeanNormalizationTest", "[CFTest]")
{
RecommendationAccuracy<NMFPolicy, OverallMeanNormalization>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for UserMeanNormalization.
*/
TEST_CASE("RecommendationAccuracyUserMeanNormalizationTest", "[CFTest]")
{
RecommendationAccuracy<NMFPolicy, UserMeanNormalization>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for ItemMeanNormalization.
*/
TEST_CASE("RecommendationAccuracyItemMeanNormalizationTest", "[CFTest]")
{
RecommendationAccuracy<NMFPolicy, ItemMeanNormalization>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for ZScoreNormalization.
*/
TEST_CASE("RecommendationAccuracyZScoreNormalizationTest", "[CFTest]")
{
RecommendationAccuracy<NMFPolicy, ZScoreNormalization>();
}
/**
* Make sure recommendations that are generated are reasonably accurate
* for CombinedNormalization.
*/
TEST_CASE("RecommendationAccuracyCombinedNormalizationTest", "[CFTest]")
{
RecommendationAccuracy<NMFPolicy,
CombinedNormalization<
OverallMeanNormalization,
UserMeanNormalization,
ItemMeanNormalization>>();
}
/**
* Ensure we can load and save the CF model using OverallMeanNormalization.
*/
TEST_CASE("SerializationOverallMeanNormalizationTest", "[CFTest]")
{
Serialization<NMFPolicy, OverallMeanNormalization>();
}
/**
* Ensure we can load and save the CF model using UserMeanNormalization.
*/
TEST_CASE("SerializationUserMeanNormalizationTest", "[CFTest]")
{
Serialization<NMFPolicy, UserMeanNormalization>();
}
/**
* Ensure we can load and save the CF model using ItemMeanNormalization.
*/
TEST_CASE("SerializationItemMeanNormalizationTest", "[CFTest]")
{
Serialization<NMFPolicy, ItemMeanNormalization>();
}
/**
* Ensure we can load and save the CF model using ZScoreMeanNormalization.
*/
TEST_CASE("SerializationZScoreNormalizationTest", "[CFTest]")
{
Serialization<NMFPolicy, ZScoreNormalization>();
}
/**
* Ensure we can load and save the CF model using CombinedNormalization.
*/
TEST_CASE("SerializationCombinedNormalizationTest", "[CFTest]")
{
Serialization<NMFPolicy,
CombinedNormalization<
OverallMeanNormalization,
UserMeanNormalization,
ItemMeanNormalization>>();
}
/**
* Make sure that Predict() is returning reasonable results for
* EuclideanSearch.
*/
TEST_CASE("CFPredictEuclideanSearch", "[CFTest]")
{
CFPredict<NMFPolicy, OverallMeanNormalization, EuclideanSearch>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for
* CosineSearch.
*/
TEST_CASE("CFPredictCosineSearch", "[CFTest]")
{
CFPredict<NMFPolicy, OverallMeanNormalization, CosineSearch>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for
* PearsonSearch.
*/
TEST_CASE("CFPredictPearsonSearch", "[CFTest]")
{
CFPredict<NMFPolicy, OverallMeanNormalization, PearsonSearch>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for
* AverageInterpolation.
*/
TEST_CASE("CFPredictAverageInterpolation", "[CFTest]")
{
CFPredict<NMFPolicy,
OverallMeanNormalization,
EuclideanSearch,
AverageInterpolation>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for
* SimilarityInterpolation.
*/
TEST_CASE("CFPredictSimilarityInterpolation", "[CFTest]")
{
CFPredict<NMFPolicy,
OverallMeanNormalization,
EuclideanSearch,
SimilarityInterpolation>(2.0);
}
/**
* Make sure that Predict() is returning reasonable results for
* RegressionInterpolation.
*/
TEST_CASE("CFPredictRegressionInterpolation", "[CFTest]")
{
CFPredict<RegSVDPolicy,
OverallMeanNormalization,
EuclideanSearch,
RegressionInterpolation>(2.0);
}
| 27.660423 | 80 | 0.723055 | [
"model"
] |
73666067c87c86eca38ac2718b9398d70d29897d | 11,432 | cc | C++ | tensorflow/core/data/service/data_service_test.cc | 10088/tensorflow | 92e8fc62e31a131978d426452881b3a16ec9069c | [
"Apache-2.0"
] | 1 | 2022-01-10T22:07:28.000Z | 2022-01-10T22:07:28.000Z | tensorflow/core/data/service/data_service_test.cc | 10088/tensorflow | 92e8fc62e31a131978d426452881b3a16ec9069c | [
"Apache-2.0"
] | null | null | null | tensorflow/core/data/service/data_service_test.cc | 10088/tensorflow | 92e8fc62e31a131978d426452881b3a16ec9069c | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include <vector>
#include "tensorflow/core/data/service/common.pb.h"
#include "tensorflow/core/data/service/dispatcher.pb.h"
#include "tensorflow/core/data/service/dispatcher_client.h"
#include "tensorflow/core/data/service/export.pb.h"
#include "tensorflow/core/data/service/test_cluster.h"
#include "tensorflow/core/data/service/test_util.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/status_matchers.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/tstring.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/data_service.pb.h"
namespace tensorflow {
namespace data {
namespace {
using ::tensorflow::data::testing::InterleaveTextlineDataset;
using ::tensorflow::data::testing::RangeDataset;
using ::tensorflow::data::testing::RangeDatasetWithShardHint;
using ::tensorflow::data::testing::WaitWhile;
using ::tensorflow::testing::IsOkAndHolds;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::HasSubstr;
using ::testing::Pair;
using ::testing::TestWithParam;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;
using ::testing::Values;
tstring LocalTempFilename() {
std::string path;
CHECK(Env::Default()->LocalTempFilename(&path));
return tstring(path);
}
std::vector<int64_t> Range(const int64 range) {
std::vector<int64_t> result;
for (int64 i = 0; i < range; ++i) {
result.push_back(i);
}
return result;
}
TEST(DataServiceTest, RangeDataset_NoShard) {
TestCluster cluster(/*num_workers=*/5);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<int64_t> dataset_client(cluster);
EXPECT_THAT(
dataset_client.Read(RangeDataset(20), ProcessingModeDef::OFF,
TARGET_WORKERS_AUTO),
IsOkAndHolds(UnorderedElementsAre(
Pair(cluster.WorkerAddress(0), ElementsAreArray(Range(20))),
Pair(cluster.WorkerAddress(1), ElementsAreArray(Range(20))),
Pair(cluster.WorkerAddress(2), ElementsAreArray(Range(20))),
Pair(cluster.WorkerAddress(3), ElementsAreArray(Range(20))),
Pair(cluster.WorkerAddress(4), ElementsAreArray(Range(20))))));
}
TEST(DataServiceTest, RangeDataset_DynamicShard) {
TestCluster cluster(/*num_workers=*/5);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<int64_t> dataset_client(cluster);
TF_ASSERT_OK_AND_ASSIGN(
DatasetClient<int64_t>::WorkerResultMap worker_results,
dataset_client.Read(RangeDataset(20), ProcessingModeDef::DYNAMIC,
TARGET_WORKERS_AUTO));
std::vector<int64_t> result;
for (const auto& worker_result : worker_results) {
result.insert(result.end(), worker_result.second.begin(),
worker_result.second.end());
}
EXPECT_THAT(result, UnorderedElementsAreArray(Range(20)));
}
using DataServiceTest_DataShard =
::testing::TestWithParam<ProcessingModeDef::ShardingPolicy>;
TEST_P(DataServiceTest_DataShard, RangeDataset_DataShard) {
TestCluster cluster(/*num_workers=*/5);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<int64_t> dataset_client(cluster);
EXPECT_THAT(
dataset_client.Read(RangeDataset(20), GetParam(), TARGET_WORKERS_LOCAL),
IsOkAndHolds(UnorderedElementsAre(
Pair(cluster.WorkerAddress(0), ElementsAre(0, 5, 10, 15)),
Pair(cluster.WorkerAddress(1), ElementsAre(1, 6, 11, 16)),
Pair(cluster.WorkerAddress(2), ElementsAre(2, 7, 12, 17)),
Pair(cluster.WorkerAddress(3), ElementsAre(3, 8, 13, 18)),
Pair(cluster.WorkerAddress(4), ElementsAre(4, 9, 14, 19)))));
}
INSTANTIATE_TEST_SUITE_P(ShardingPolicy, DataServiceTest_DataShard,
Values(ProcessingModeDef::FILE_OR_DATA,
ProcessingModeDef::DATA));
TEST(DataServiceTest, RangeDataset_HintShard) {
TestCluster cluster(/*num_workers=*/5);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<int64_t> dataset_client(cluster);
EXPECT_THAT(
dataset_client.Read(RangeDatasetWithShardHint(20),
ProcessingModeDef::HINT, TARGET_WORKERS_LOCAL),
IsOkAndHolds(UnorderedElementsAre(
Pair(cluster.WorkerAddress(0), ElementsAre(0, 5, 10, 15)),
Pair(cluster.WorkerAddress(1), ElementsAre(1, 6, 11, 16)),
Pair(cluster.WorkerAddress(2), ElementsAre(2, 7, 12, 17)),
Pair(cluster.WorkerAddress(3), ElementsAre(3, 8, 13, 18)),
Pair(cluster.WorkerAddress(4), ElementsAre(4, 9, 14, 19)))));
}
TEST(DataServiceTest, TextlineDataset_NoShard) {
TestCluster cluster(/*num_workers=*/5);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<tstring> dataset_client(cluster);
std::vector<tstring> filenames = {LocalTempFilename(), LocalTempFilename(),
LocalTempFilename(), LocalTempFilename(),
LocalTempFilename()};
TF_ASSERT_OK_AND_ASSIGN(
const DatasetDef dataset,
InterleaveTextlineDataset(
filenames, {"0", "1\n1", "2\n2\n2", "3\n3\n3\n3", "4\n4\n4\n4\n4"}));
std::vector<tstring> expected = {"0", "1", "2", "3", "4", "1", "2", "3",
"4", "2", "3", "4", "3", "4", "4"};
EXPECT_THAT(
dataset_client.Read(dataset, ProcessingModeDef::OFF, TARGET_WORKERS_ANY),
IsOkAndHolds(UnorderedElementsAre(
Pair(cluster.WorkerAddress(0), ElementsAreArray(expected)),
Pair(cluster.WorkerAddress(1), ElementsAreArray(expected)),
Pair(cluster.WorkerAddress(2), ElementsAreArray(expected)),
Pair(cluster.WorkerAddress(3), ElementsAreArray(expected)),
Pair(cluster.WorkerAddress(4), ElementsAreArray(expected)))));
}
TEST(DataServiceTest, TextlineDataset_DataShard) {
TestCluster cluster(/*num_workers=*/5);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<tstring> dataset_client(cluster);
std::vector<tstring> filenames = {LocalTempFilename(), LocalTempFilename(),
LocalTempFilename(), LocalTempFilename(),
LocalTempFilename()};
TF_ASSERT_OK_AND_ASSIGN(
const DatasetDef dataset,
InterleaveTextlineDataset(
filenames, {"0", "1\n1", "2\n2\n2", "3\n3\n3\n3", "4\n4\n4\n4\n4"}));
EXPECT_THAT(dataset_client.Read(dataset, ProcessingModeDef::DATA,
TARGET_WORKERS_LOCAL),
IsOkAndHolds(UnorderedElementsAre(
Pair(cluster.WorkerAddress(0), ElementsAre("0", "1", "3")),
Pair(cluster.WorkerAddress(1), ElementsAre("1", "2", "4")),
Pair(cluster.WorkerAddress(2), ElementsAre("2", "3", "3")),
Pair(cluster.WorkerAddress(3), ElementsAre("3", "4", "4")),
Pair(cluster.WorkerAddress(4), ElementsAre("4", "2", "4")))));
}
using DataServiceTest_FileShard =
::testing::TestWithParam<ProcessingModeDef::ShardingPolicy>;
TEST_P(DataServiceTest_FileShard, TextlineDataset_FileShard) {
TestCluster cluster(/*num_workers=*/5);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<tstring> dataset_client(cluster);
std::vector<tstring> filenames = {LocalTempFilename(), LocalTempFilename(),
LocalTempFilename(), LocalTempFilename(),
LocalTempFilename()};
TF_ASSERT_OK_AND_ASSIGN(
const DatasetDef dataset,
InterleaveTextlineDataset(
filenames, {"0", "1\n1", "2\n2\n2", "3\n3\n3\n3", "4\n4\n4\n4\n4"}));
EXPECT_THAT(
dataset_client.Read(dataset, ProcessingModeDef::FILE_OR_DATA,
TARGET_WORKERS_LOCAL),
IsOkAndHolds(UnorderedElementsAre(
Pair(cluster.WorkerAddress(0), ElementsAre("0")),
Pair(cluster.WorkerAddress(1), ElementsAre("1", "1")),
Pair(cluster.WorkerAddress(2), ElementsAre("2", "2", "2")),
Pair(cluster.WorkerAddress(3), ElementsAre("3", "3", "3", "3")),
Pair(cluster.WorkerAddress(4),
ElementsAre("4", "4", "4", "4", "4")))));
}
INSTANTIATE_TEST_SUITE_P(ShardingPolicy, DataServiceTest_FileShard,
Values(ProcessingModeDef::FILE_OR_DATA,
ProcessingModeDef::FILE));
TEST(DataServiceTest, GcMissingClientsWithSmallTimeout) {
TestCluster::Config config;
config.num_workers = 5;
config.job_gc_check_interval_ms = 10;
config.job_gc_timeout_ms = 10;
config.client_timeout_ms = 10;
TestCluster cluster(config);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<tstring> dataset_client(cluster);
TF_ASSERT_OK_AND_ASSIGN(int64_t job_client_id, dataset_client.CreateJob());
Env::Default()->SleepForMicroseconds(1000 * 1000); // 1 second.
// Job should not be garbage collected before the client has started reading.
EXPECT_THAT(cluster.NumActiveJobs(), IsOkAndHolds(1));
TF_ASSERT_OK(dataset_client.GetTasks(job_client_id).status());
// Job should be garbage collected within 10 seconds.
absl::Time wait_start = absl::Now();
TF_ASSERT_OK(WaitWhile([&]() -> StatusOr<bool> {
TF_ASSIGN_OR_RETURN(size_t num_jobs, cluster.NumActiveJobs());
return num_jobs > 0;
}));
EXPECT_LT(absl::Now(), wait_start + absl::Seconds(10));
}
TEST(DataServiceTest, DontGcMissingClientsWithLargeTimeout) {
TestCluster::Config config;
config.num_workers = 5;
config.job_gc_check_interval_ms = 10;
config.job_gc_timeout_ms = 10;
config.client_timeout_ms = 10000000000;
TestCluster cluster(config);
TF_ASSERT_OK(cluster.Initialize());
DatasetClient<tstring> dataset_client(cluster);
TF_ASSERT_OK(dataset_client.CreateJob().status());
Env::Default()->SleepForMicroseconds(1000 * 1000); // 1 second.
// Job should not be garbage collected, since the client hasn't timed out.
EXPECT_THAT(cluster.NumActiveJobs(), IsOkAndHolds(1));
}
TEST(DataServiceTest, GetWorkers) {
TestCluster cluster(1);
TF_ASSERT_OK(cluster.Initialize());
DataServiceDispatcherClient dispatcher(cluster.DispatcherAddress(), "grpc");
std::vector<WorkerInfo> workers;
TF_EXPECT_OK(dispatcher.GetWorkers(workers));
EXPECT_EQ(1, workers.size());
}
TEST(DataServiceTest, DispatcherStateExport) {
TestCluster cluster(1);
TF_ASSERT_OK(cluster.Initialize());
ServerStateExport dispatcher_state_export = cluster.ExportDispatcherState();
EXPECT_THAT(
dispatcher_state_export.dispatcher_state_export().worker_addresses(),
ElementsAre(HasSubstr("localhost")));
}
} // namespace
} // namespace data
} // namespace tensorflow
| 41.42029 | 80 | 0.689556 | [
"vector"
] |
736879aaf1fad643a6cd17624890297466ad8448 | 22,172 | cpp | C++ | PlanetaEngine/src/planeta/util/TLSFMemoryAllocator.cpp | CdecPGL/PlanetaEngine | b15d5b13c3b2aee886d3f92d13777f1b12860260 | [
"MIT"
] | null | null | null | PlanetaEngine/src/planeta/util/TLSFMemoryAllocator.cpp | CdecPGL/PlanetaEngine | b15d5b13c3b2aee886d3f92d13777f1b12860260 | [
"MIT"
] | 15 | 2018-01-14T14:14:47.000Z | 2018-01-14T15:00:15.000Z | PlanetaEngine/src/planeta/util/TLSFMemoryAllocator.cpp | CdecPGL/PlanetaEngine | b15d5b13c3b2aee886d3f92d13777f1b12860260 | [
"MIT"
] | null | null | null | #include <array>
#include "TLSFMemoryAllocator.hpp"
#include "BadAllocException.hpp"
namespace {
const std::array<size_t,32> _eo2_table = {
1u << 0, 1u << 1, 1u << 3, 1u << 4, 1u << 5, 1u << 6, 1u << 7, 1u << 8, 1u << 9,
1u << 10, 1u << 11, 1u << 13, 1u << 14, 1u << 15, 1u << 16, 1u << 17, 1u << 18, 1u << 19,
1u << 20, 1u << 21, 1u << 23, 1u << 24, 1u << 25, 1u << 26, 1u << 27, 1u << 28, 1u << 29,
1u << 30, 1u << 31
};
const size_t SECOND_LEVEL_INDEX_SEPARATION_EXPONENT_OF_TWO(5); //第二カテゴリ分割数べき乗数(2の冪乗数でないといけない2^4=16or2^5=32が適切らしい。)
//http://sackys-blog-extend.cocolog-nifty.com/blog/2012/07/tlsf-5-e929.html
inline static unsigned _LSB(unsigned int word)
{
int bit = 0;
if (word)
{
word &= ~word + 1;
if (word & 0xffff0000) bit += 16;
if (word & 0xff00ff00) bit += 8;
if (word & 0xf0f0f0f0) bit += 4;
if (word & 0xcccccccc) bit += 2;
if (word & 0xaaaaaaaa) ++bit;
++bit;
}
return bit;
}
inline static unsigned _MSB(unsigned int word)
{
int bit = 32;
if (!word) --bit;
if (!(word & 0xffff0000)) { word <<= 16; bit -= 16; }
if (!(word & 0xff000000)) { word <<= 8; bit -= 8; }
if (!(word & 0xf0000000)) { word <<= 4; bit -= 4; }
if (!(word & 0xc0000000)) { word <<= 2; bit -= 2; }
if (!(word & 0x80000000)) { word <<= 1; --bit; }
return bit;
}
//http://marupeke296.com/cgi-bin/cbbs/cbbs.cgi?mode=al2&namber=5198&rev=&no=0&P=R&KLOG=5
static unsigned count1_32(unsigned val) {
val = (val & 0x55555555) + ((val >> 1) & 0x55555555);
val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
val = (val & 0x0f0f0f0f) + ((val >> 4) & 0x0f0f0f0f);
val = (val & 0x00ff00ff) + ((val >> 8) & 0x00ff00ff);
return (val & 0x0000ffff) + ((val >> 16) & 0x0000ffff);
}
static bool LSB32(unsigned val, unsigned* out) {
if (val == 0) return false;
val |= (val << 1);
val |= (val << 2);
val |= (val << 4);
val |= (val << 8);
val |= (val << 16);
*out = 32 - count1_32(val);
return true;
}
static bool MSB32(unsigned val, unsigned* out) {
if (val == 0) return false;
val |= (val >> 1);
val |= (val >> 2);
val |= (val >> 4);
val |= (val >> 8);
val |= (val >> 16);
*out = count1_32(val) - 1;
return true;
}
inline unsigned long getMSB(unsigned size) {
return _MSB(size) - 1;
/*unsigned long index;
_BitScanReverse(&index, size);
return index;*/
}
inline unsigned long getLSB(unsigned size) {
return _LSB(size) - 1;
/*unsigned long index;
_BitScanForward(&index, size);
return index;*/
}
int getFreeListSLI(unsigned int mySLI, unsigned freeListBit) {
// 自分のSLI以上が立っているビット列を作成 (ID = 0なら0xffffffff)
unsigned myBit = 0xffffffff << mySLI;
// myBitとfreeListBitを論理積すれば、確保可能なブロックを持つSLIが出てきます
// freeListBit = 1100 ([192-223]と[224-255]にあるとします)
unsigned enableListBit = freeListBit & myBit;
// LSBを求めれば確保可能な一番サイズの小さいフリーリストブロックの発見
if (enableListBit == 0)
return -1; // フリーリスト無し
return static_cast<int>(getLSB(enableListBit));
}
}
namespace plnt {
namespace util {
//////////////////////////////////////////////////////////////////////////
//TLSFTLSFMemoryAllocator::_Impl
/////////////////////////////////////////////////////////////////////////
class TLSFMemoryAllocator::_Impl {
public:
_Impl(TLSFMemoryAllocator& ptlsf) :_tlsf(ptlsf), _second_level_index_separation_exponent_of_2(SECOND_LEVEL_INDEX_SEPARATION_EXPONENT_OF_TWO), _second_level_index_separation(1u << _second_level_index_separation_exponent_of_2), _free_block_list(nullptr), _free_block_list_size(0) {}
~_Impl() { release_free_block_list(); }
bool reserve_memory(size_t size);
MemoryDetailScanResult detail_scan()const;
void* alloc(size_t size);
void dealloc(void*);
void release_free_block_list(); //フリーブロックリストように確保していた領域を解放
private:
class _MemoryBlock {
public:
_MemoryBlock(); //ダミー作成ようコンストラクタ
_MemoryBlock(bool footer_valid_flag); //コンストラクタ(trueでフッター書き込み。falseで書き込みなし)
_MemoryBlock(size_t data_size); //指定データサイズのメモリブロック作成
_MemoryBlock(size_t size, bool fit); //第二引数がtrueなら、合計サイズが第一引数になるように、falseなら第一引数がデータサイズになるようにメモリブロックを作成する
~_MemoryBlock();
static void* operator new(size_t size, void* buf){ return buf; } //placement new
static void operator delete(void* p, void* buf) {} //placement delete(使わない)
static void* operator new(size_t size){ return malloc(size); } //通常のnew
static void operator delete(void* p) { free(p); } //通常のdelete
static void* operator new[](size_t size) { return malloc(size); } //通常のnew[]
static void operator delete[](void* p) { free(p); } //通常のdelete[]
size_t GetDataSize()const { return _data_size; }
size_t GetTotalSize()const { return CalcTotalSizeByDataSize(_data_size); }
char* GetDataBlockPointer() { return reinterpret_cast<char*>(this) + header_size; }
size_t* GetFooterPointer() { return reinterpret_cast<size_t*>(reinterpret_cast<char*>(GetDataBlockPointer()) + _data_size); }
bool ErrorCheck()const { return _error_check_data != error_check_code; } //エラーチェック。エラーならtrue
bool FooterErrorCheck()const { return GetTotalSize() != *const_cast<_MemoryBlock*>(this)->GetFooterPointer(); } //フッターの値が正当化確認
void LeaveFromList(); //現在のリストから外れる
void JoinToLIst(_MemoryBlock*); //指定ブロックの後ろに追加
bool IsUsing()const { return _use_flag; }
void SetUsingFlag(bool f) { _use_flag = f; }
static size_t CalcTotalSizeByDataSize(size_t data_size) { return data_size + manage_area_size; } //データサイズから、ブロックの号掲載ぞを計算する
_MemoryBlock* next() { return _next; }
_MemoryBlock* prev() { return _prev; }
const static size_t header_size; //ヘッダサイズ
const static size_t footer_size; //フッタサイズ
const static size_t manage_area_size; //管理用領域サイズ(ヘッダ+フッタ)
const static size_t error_check_code; //エラー確認コード
private:
bool _use_flag; //使用中フラグ
size_t _data_size; //データ領域のサイズ
_MemoryBlock *_prev; //リストの前へのポインタ
_MemoryBlock *_next; //リストの後ろへのポインタ
size_t _error_check_data; //エラー確認用データ
};
_MemoryBlock* _free_block_list; //フリーブロックリスト
size_t _free_block_list_size;
std::vector<size_t> _second_level_index_free_bit_array; //フリーブロックリスト第二カテゴリビット
size_t _first_level_index_free_bit_array; //フリーブロックリスト第一カテゴリビット
void _init_free_block_list(size_t cate1_size, size_t cate2_size); //フリーブロック初期化
void _push_free_block(_MemoryBlock* block); //フリーブロック追加
_MemoryBlock* _pop_free_block(size_t cate1, size_t cate2); //フリーブロックから指定されたカテゴリが格納可能なブロックを返す
void _remove_free_block(_MemoryBlock* block);
_MemoryBlock* _marge_free_block(_MemoryBlock*); //可能ならフローブロックを結合する(この関数内ではフリーブロックリストへの登録は行わない。マージしたブロックの登録解除は行う)
_MemoryBlock* _devide_free_block(_MemoryBlock*, size_t); //可能ならフリーブロックを指定サイズに分割する。分割した右ブロックへのポインタを返す(この関数内ではフリーブロックリストへの登録は行わない)
size_t _second_level_index_separation_exponent_of_2; //第二カテゴリの分割数の2べき乗
size_t _second_level_index_separation; //第二カテゴリの分割数
//最上位ビットインデックスを求める
static size_t calcMSB(size_t size); //最上位ビットを求める
// static size_t calcLSB(size_t size);
size_t _calc_second_level_index(size_t size, size_t first_category); //第二カテゴリを計算する
size_t _get_free_block_list_index(size_t cate1, size_t cate2); //フリーブロックリストのインデックスを計算する。
TLSFMemoryAllocator& _tlsf;
};
inline bool TLSFMemoryAllocator::_Impl::reserve_memory(size_t size)
{
if (_tlsf._memory_pool) { free(_tlsf._memory_pool); } //確保してある領域を解放
_tlsf._allocated_memory_count = 0;
_tlsf._allcated_memory_size = 0;
_tlsf._using_memory_size = 0;
//最低管理領域(両端のダミーブロック、一つ目のデータブロックの合計領域と最低データ領域(第二カテゴリ分割数))に足りなかったらエラー
if (size <= _MemoryBlock::manage_area_size * 3 + _second_level_index_separation) { return false; }
_tlsf._memory_pool = reinterpret_cast<char*>(std::malloc(size)); //メモリ確保
_tlsf._memory_pool_size = size;
//前後にダミーブロックを作成
_MemoryBlock* head_dumy = new(_tlsf._memory_pool)_MemoryBlock();
_MemoryBlock* foot_dumy = new(reinterpret_cast<char*>(_tlsf._memory_pool) + _tlsf._memory_pool_size - _MemoryBlock::manage_area_size)_MemoryBlock();
head_dumy->SetUsingFlag(true);
foot_dumy->SetUsingFlag(true);
_tlsf._using_memory_size += head_dumy->GetTotalSize();
_tlsf._using_memory_size += foot_dumy->GetTotalSize();
//領域に収まるようにメモリブロック作成
size_t create_block_size = (_tlsf._memory_pool_size - head_dumy->GetTotalSize() - foot_dumy->GetTotalSize());
_MemoryBlock* block = new(reinterpret_cast<char*>(head_dumy) + head_dumy->GetTotalSize())_MemoryBlock(create_block_size, true);
//作製したデータの格納カテゴリを求める
size_t cate1 = calcMSB(block->GetDataSize() + 1);
size_t cate2 = _calc_second_level_index(block->GetDataSize() + 1, cate1);
if (cate2 == 0) { --cate1; cate2 = _second_level_index_separation - 1; }
else { --cate2; }
//指定されたサイズ分のフリーブロックリスト領域を確保
_init_free_block_list(cate1 + 1, cate2 + 1);
//確保したメモリブロックをフリーブロックリストに登録
_push_free_block(block);
return true;
}
inline TLSFMemoryAllocator::MemoryDetailScanResult TLSFMemoryAllocator::_Impl::detail_scan() const
{
MemoryDetailScanResult res;
if (_tlsf._memory_pool == nullptr) { return res; }
char* ptr = _tlsf._memory_pool;
//メモリブロック探索
while (ptr < _tlsf._memory_pool + _tlsf._memory_pool_size) {
_MemoryBlock* block = reinterpret_cast<_MemoryBlock*>(ptr);
if (block->ErrorCheck() || block->FooterErrorCheck()) { res.corruption = true; break; } //エラーチェック
size_t data_size = block->GetDataSize();
size_t total_size = block->GetTotalSize();
bool use_flag = block->IsUsing();
if (use_flag) { //アクティブブロック
if (data_size > 0) { ++res.active_block_count; }
else { ++res.dumy_block_count; }
res.allocated_memory_size += data_size;
res.using_memory_size += total_size;
}
else { //フリーブロック
if (data_size > 0) { ++res.free_block_count; }
else { ++res.dumy_block_count; }
res.available_memory_size += data_size;
res.free_memory_size += total_size;
if (res.available_max_memory_allocation_size < data_size) { res.available_max_memory_allocation_size = data_size; }
}
++res.total_block_count;
res.reserved_memory_size += total_size;
ptr += total_size;
}
//フリーブロックリストのスキャン
size_t free_list_count = 0;
size_t correct_first_free_block_bit_array = 0;
for (size_t i = 0; i < _free_block_list_size; ++i) {
bool is_exist_free_block = false;
_MemoryBlock* list_top = &_free_block_list[i];
while (list_top == list_top->next()) { ++free_list_count; is_exist_free_block = true; }
if ((((_second_level_index_free_bit_array[i / _second_level_index_separation])&(1u << (i % _second_level_index_separation))) ? true : false) != (is_exist_free_block ? true : false)) {
res.inconsistency_at_second_free_block_list_bit_array = true;
}
if (is_exist_free_block) { correct_first_free_block_bit_array |= (1u << (i / _second_level_index_separation)); }
}
//エラー検出
res.inconsistency_at_allocated_memory_count = (_tlsf._allocated_memory_count != res.active_block_count);
res.inconsistency_at_allocated_memory_size = (_tlsf._allcated_memory_size != res.allocated_memory_size);
res.inconsistency_at_reserved_memory_size = (res.reserved_memory_size != _tlsf._memory_pool_size);
res.inconsistency_at_using_memory_size = (res.using_memory_size != _tlsf._using_memory_size);
res.inconsistency_at_dumy_count = (res.dumy_block_count != 2);
res.inconsistency_at_free_block_list = res.free_block_count != free_list_count;
res.inconsistency_at_second_free_block_list_bit_array = (_first_level_index_free_bit_array != correct_first_free_block_bit_array);
res.error = res.corruption || res.inconsistency_at_allocated_memory_count || res.inconsistency_at_allocated_memory_size || res.inconsistency_at_using_memory_size || res.inconsistency_at_dumy_count || res.inconsistency_at_free_block_list || res.inconsistency_at_first_free_block_list_bit_array || res.inconsistency_at_second_free_block_list_bit_array;
//断片化率計算
res.fragment_ratio = 1.0 - ((double)res.available_max_memory_allocation_size / res.available_memory_size);
return res;
}
inline void* TLSFMemoryAllocator::_Impl::alloc(size_t size)
{
if (size == 0) { throw BadAlloc("Size must not equal zero."); }
//要求メモリのカテゴリを確認
size_t cate_1 = calcMSB(size);
size_t cate_2 = _calc_second_level_index(size, cate_1);
_MemoryBlock* _allocated_block = _pop_free_block(cate_1, cate_2);
if (_allocated_block == nullptr) {
char err[256] = "\0";
sprintf_s(err, 256, "failed to allocate memory. avalable free block is not exist. (size : %ul)", size);
throw BadAlloc(err);
}
//可能なら分割する
_MemoryBlock* remain_block = _devide_free_block(_allocated_block, size);
_allocated_block->SetUsingFlag(true);
if (remain_block) { _push_free_block(remain_block); }
_tlsf._allcated_memory_size += _allocated_block->GetDataSize();
_tlsf._using_memory_size += _allocated_block->GetTotalSize();
++_tlsf._allocated_memory_count;
return _allocated_block->GetDataBlockPointer(); //データ領域のポインタを返す
}
inline void TLSFMemoryAllocator::_Impl::dealloc(void* ptr)
{
//指定ポインタが確保領域内か確認(両端のダミー領域も範囲外とみなす)
if (ptr < (_tlsf._memory_pool + _MemoryBlock::manage_area_size) || ptr >= (_tlsf._memory_pool + _tlsf._memory_pool_size - _MemoryBlock::manage_area_size)) { throw BadAlloc("Designated pointer is out of range,"); }
_MemoryBlock* _block = reinterpret_cast<_MemoryBlock*>(reinterpret_cast<char*>(ptr) - sizeof(_MemoryBlock));
if (_block->ErrorCheck()) { throw BadAlloc("Designated pointer is invalied."); } //指定ポインターが有効か確認
if (!_block->IsUsing()) { throw BadAlloc("Designated pointer is already deallocated."); } //指定ポインターが使用中か確認
_tlsf._allcated_memory_size -= _block->GetDataSize();
_tlsf._using_memory_size -= _block->GetTotalSize();
--_tlsf._allocated_memory_count;
_block->SetUsingFlag(false);
//必要ならマージする
_block = _marge_free_block(_block);
//フリーリストに追加
_push_free_block(_block);
}
inline void TLSFMemoryAllocator::_Impl::release_free_block_list() {
if (_free_block_list) { /*delete[] _free_block_list;*/free(_free_block_list); }
_free_block_list_size = 0;
}
inline void TLSFMemoryAllocator::_Impl::_init_free_block_list(size_t cate1_size, size_t cate2_size)
{
release_free_block_list();
size_t fbl_size = (cate1_size - 1) * _second_level_index_separation + cate2_size;
_free_block_list = reinterpret_cast<_MemoryBlock*>(malloc(sizeof(_MemoryBlock)*fbl_size)); //領域確保して
for (unsigned int i = 0; i < fbl_size; ++i) {
new(&_free_block_list[i]) _MemoryBlock(false); //配置newで初期化
}
_free_block_list_size = fbl_size;
_first_level_index_free_bit_array = 0;
_second_level_index_free_bit_array.clear();
_second_level_index_free_bit_array.resize(cate1_size, 0);
}
inline void TLSFMemoryAllocator::_Impl::_push_free_block(_MemoryBlock* block) {
//自分の所属カテゴリより一つ下にいれる
size_t cate1 = calcMSB(block->GetDataSize() + 1);
size_t cate2 = _calc_second_level_index(block->GetDataSize() + 1, cate1);
if (cate2 == 0) { --cate1; cate2 = _second_level_index_separation - 1; }
else { --cate2; }
block->JoinToLIst(&_free_block_list[_get_free_block_list_index(cate1, cate2)]);
_first_level_index_free_bit_array |= (1u << cate1);
_second_level_index_free_bit_array[cate1] |= (1u << cate2);
}
//////////////////////////////////////////////////////////////////////////
//TLSFTLSFMemoryAllocator::_Impl::_MemoryBlock
/////////////////////////////////////////////////////////////////////////
inline TLSFMemoryAllocator::_Impl::_MemoryBlock* TLSFMemoryAllocator::_Impl::_pop_free_block(size_t cate_1, size_t cate_2) {
int cate_1u((signed)cate_1), cate_2u((signed)cate_2);
cate_2u = getFreeListSLI(cate_2, _second_level_index_free_bit_array[cate_1]);
if (cate_2u < 0) { //なかったら所属可能な第一カテゴリを探す
cate_1u = getFreeListSLI(cate_1, _first_level_index_free_bit_array);
if (cate_1u >= 0) {
cate_2u = getFreeListSLI(0, _second_level_index_free_bit_array[cate_1u]);
if (cate_2u < 0) { throw std::logic_error("フリーブロックリストビットの矛盾"); } //割り当て失敗(ありえない)
}
else { return nullptr; } //割り当て失敗
}
cate_1 = (unsigned)cate_1u;
cate_2 = (unsigned)cate_2u;
size_t free_list_idx = _get_free_block_list_index(cate_1, cate_2);
if (free_list_idx >= _free_block_list_size) { throw std::logic_error("attempt to access out of free bit list! "); }
_MemoryBlock* _allocated_block = _free_block_list[free_list_idx].next();
_remove_free_block(_allocated_block); //フリーブロックリストから除去
return _allocated_block;
}
inline void TLSFMemoryAllocator::_Impl::_remove_free_block(_MemoryBlock* block) {
block->LeaveFromList();
size_t cate1 = calcMSB(block->GetDataSize() + 1);
size_t cate2 = _calc_second_level_index(block->GetDataSize() + 1, cate1);
if (cate2 == 0) { --cate1; cate2 = _second_level_index_separation - 1; }
else { --cate2; }
size_t idx = _get_free_block_list_index(cate1, cate2);
if (_free_block_list[idx].next() == nullptr) {
_second_level_index_free_bit_array[cate1] &= ~(1u << cate2);
if (_second_level_index_free_bit_array[cate1] == 0) { _first_level_index_free_bit_array &= ~(1u << cate1); }
}
}
inline size_t TLSFMemoryAllocator::_Impl::calcMSB(size_t size)
{
return getMSB(size);
/*size_t ret = 16;
unsigned int seg = 16;
while ((seg >>= 1)) {
size_t e2 = _eo2_table[ret - 1];
if (size > e2) { ret += seg; }
else if (size < e2) { ret -= seg; }
else { break; }
}
if (_eo2_table[ret - 1] > size) { --ret; }
return ret;*/
}
inline size_t TLSFMemoryAllocator::_Impl::_calc_second_level_index(size_t size, size_t first_category)
{
// 最上位ビット未満のビット列だけを有効にするマスク
const unsigned mask = (1 << first_category) - 1; // 1000 0000 -> 0111 1111
// 右へのシフト数を算出
const unsigned rs = first_category - _second_level_index_separation_exponent_of_2; // 7 - 3 = 4 (8分割ならN=3です)
// 引数sizeにマスクをかけて、右へシフトすればインデックスに
return (size & mask) >> rs;
}
inline size_t TLSFMemoryAllocator::_Impl::_get_free_block_list_index(size_t cate1, size_t cate2)
{
return cate1 * (1u << _second_level_index_separation_exponent_of_2) + cate2 - 1;
}
inline TLSFMemoryAllocator::_Impl::_MemoryBlock* TLSFMemoryAllocator::_Impl::_marge_free_block(_MemoryBlock* block) {
//右
_MemoryBlock* right = reinterpret_cast<_MemoryBlock*>(reinterpret_cast<char*>(block) + block->GetTotalSize());
if (!right->IsUsing()) {
_remove_free_block(right);
new(block)_MemoryBlock(block->GetTotalSize() + right->GetDataSize());
}
//左
size_t tsize = *(reinterpret_cast<size_t*>(reinterpret_cast<char*>(block) - _MemoryBlock::footer_size));
_MemoryBlock* left = reinterpret_cast<_MemoryBlock*>(reinterpret_cast<char*>(block) - tsize);
if (!left->IsUsing()) {
_remove_free_block(left);
block = new(left)_MemoryBlock(left->GetTotalSize() + block->GetDataSize());
}
return block;
}
inline TLSFMemoryAllocator::_Impl::_MemoryBlock* TLSFMemoryAllocator::_Impl::_devide_free_block(_MemoryBlock* block, size_t size) {
//分割後の残り領域サイズが最低値より小さかったら分割しない確保できないなら
if (block->GetDataSize() <= size + sizeof(_MemoryBlock) + _MemoryBlock::footer_size + _second_level_index_separation) { return nullptr; }
size_t remain_data_size = block->GetDataSize() - size - sizeof(_MemoryBlock) - _MemoryBlock::footer_size;
new(block)_MemoryBlock(size);
block = new(reinterpret_cast<char*>(block) + block->GetTotalSize())_MemoryBlock(remain_data_size);
return block;
}
const size_t TLSFMemoryAllocator::_Impl::_MemoryBlock::footer_size = sizeof(size_t);
const size_t TLSFMemoryAllocator::_Impl::_MemoryBlock::header_size = sizeof(_MemoryBlock);
const size_t TLSFMemoryAllocator::_Impl::_MemoryBlock::manage_area_size = (footer_size + header_size);
const size_t TLSFMemoryAllocator::_Impl::_MemoryBlock::error_check_code = 0xCDECECEC;
inline TLSFMemoryAllocator::_Impl::_MemoryBlock::_MemoryBlock(size_t data_size) : _data_size(data_size), _use_flag(false), _prev(nullptr), _next(nullptr), _error_check_data(error_check_code)
{
*GetFooterPointer() = GetTotalSize();
}
inline TLSFMemoryAllocator::_Impl::_MemoryBlock::_MemoryBlock(size_t size, bool fit) : _MemoryBlock(fit ? size - sizeof(_MemoryBlock) - footer_size : size)
{
}
inline TLSFMemoryAllocator::_Impl::_MemoryBlock::_MemoryBlock(bool list_top_flag) : _data_size(0), _use_flag(false), _prev(nullptr), _next(nullptr), _error_check_data(error_check_code) {
//フッターに合計サイズ書き込み
if (list_top_flag) { *GetFooterPointer() = GetTotalSize(); }
}
inline TLSFMemoryAllocator::_Impl::_MemoryBlock::_MemoryBlock() : _MemoryBlock((size_t)0)
{
}
inline TLSFMemoryAllocator::_Impl::_MemoryBlock::~_MemoryBlock()
{
}
inline void TLSFMemoryAllocator::_Impl::_MemoryBlock::LeaveFromList() {
if (_prev) { _prev->_next = _next; }
if (_next) { _next->_prev = _prev; }
_prev = nullptr;
_next = nullptr;
}
inline void TLSFMemoryAllocator::_Impl::_MemoryBlock::JoinToLIst(_MemoryBlock* _pre_block) {
_prev = _pre_block;
_next = _prev->_next;
_pre_block->_next = this;
if (_next) { _next->_prev = this; }
}
//////////////////////////////////////////////////////////////////////////
//TLSFTLSFMemoryAllocator
/////////////////////////////////////////////////////////////////////////
TLSFMemoryAllocator::TLSFMemoryAllocator() : _memory_pool_size(0), _memory_pool(nullptr), _using_memory_size(0), _allocated_memory_count(0), _impl(new _Impl(*this))
{
}
TLSFMemoryAllocator::TLSFMemoryAllocator(size_t t) :TLSFMemoryAllocator(){
ReserveMemory(t);
}
TLSFMemoryAllocator::~TLSFMemoryAllocator()
{
if (_memory_pool) { free(_memory_pool); }
delete _impl;
}
bool TLSFMemoryAllocator::ReserveMemory(size_t size) { return _impl->reserve_memory(size); }
void TLSFMemoryAllocator::ReleaseMemory() {
if (_memory_pool) { free(_memory_pool); }
_impl->release_free_block_list();
}
TLSFMemoryAllocator::MemoryDetailScanResult TLSFMemoryAllocator::DetailScan() const { return _impl->detail_scan(); }
void* TLSFMemoryAllocator::_alloc(size_t size) { return _impl->alloc(size); }
void TLSFMemoryAllocator::_dealloc(void* ptr) { return _impl->dealloc(ptr); }
}
}
| 43.992063 | 353 | 0.706612 | [
"vector"
] |
73690ce15f599c46f05b583b0ecbac1518f0c5ac | 22,334 | cpp | C++ | Code/GraphMol/MolHash/hashfunctions.cpp | ncfirth/rdkit | c3220f30a0369cbb70415a3bf2e4d9aa46f37e96 | [
"PostgreSQL"
] | null | null | null | Code/GraphMol/MolHash/hashfunctions.cpp | ncfirth/rdkit | c3220f30a0369cbb70415a3bf2e4d9aa46f37e96 | [
"PostgreSQL"
] | null | null | null | Code/GraphMol/MolHash/hashfunctions.cpp | ncfirth/rdkit | c3220f30a0369cbb70415a3bf2e4d9aa46f37e96 | [
"PostgreSQL"
] | 1 | 2020-09-15T15:48:44.000Z | 2020-09-15T15:48:44.000Z | /*==============================================*/
/* Copyright (C) 2011-2019 NextMove Software */
/* All rights reserved. */
/* */
/* This file is part of molhash. */
/* */
/* The contents are covered by the terms of the */
/* BSD license, which is included in the file */
/* license.txt. */
/*==============================================*/
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/RDKitQueries.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include "nmmolhash.h"
#include "mf.h"
namespace {
unsigned int NMRDKitBondGetOrder(const RDKit::Bond *bnd) {
PRECONDITION(bnd, "bad bond");
switch (bnd->getBondType()) {
case RDKit::Bond::AROMATIC:
case RDKit::Bond::SINGLE:
return 1;
case RDKit::Bond::DOUBLE:
return 2;
case RDKit::Bond::TRIPLE:
return 3;
case RDKit::Bond::QUADRUPLE:
return 4;
case RDKit::Bond::QUINTUPLE:
return 5;
case RDKit::Bond::HEXTUPLE:
return 6;
default:
return 0;
}
}
RDKit::Bond *NMRDKitMolNewBond(RDKit::RWMol *mol, RDKit::Atom *src,
RDKit::Atom *dst, unsigned int order,
bool arom) {
PRECONDITION(mol, "bad molecule");
PRECONDITION(src, "bad src atom");
PRECONDITION(dst, "bad dest atom");
RDKit::Bond *result;
result = mol->getBondBetweenAtoms(src->getIdx(), dst->getIdx());
if (result) {
if (order == 1) {
switch (result->getBondType()) {
case RDKit::Bond::SINGLE:
result->setBondType(RDKit::Bond::DOUBLE);
break;
case RDKit::Bond::DOUBLE:
result->setBondType(RDKit::Bond::TRIPLE);
break;
default:
break;
}
}
return result;
}
RDKit::Bond::BondType type = RDKit::Bond::UNSPECIFIED;
if (!arom) {
switch (order) {
case 1:
type = RDKit::Bond::SINGLE;
break;
case 2:
type = RDKit::Bond::DOUBLE;
break;
case 3:
type = RDKit::Bond::TRIPLE;
break;
case 4:
type = RDKit::Bond::QUADRUPLE;
break;
}
} else {
type = RDKit::Bond::AROMATIC;
}
result = new RDKit::Bond(type);
result->setOwningMol(mol);
result->setBeginAtom(src);
result->setEndAtom(dst);
mol->addBond(result, true);
if (arom) {
result->setIsAromatic(true);
}
return result;
}
void NMRDKitSanitizeHydrogens(RDKit::RWMol *mol) {
PRECONDITION(mol, "bad molecule");
// Move all of the implicit Hs into one box
for (auto aptr : mol->atoms()) {
unsigned int hcount = aptr->getTotalNumHs();
aptr->setNoImplicit(true);
aptr->setNumExplicitHs(hcount);
aptr->updatePropertyCache(); // or else the valence is reported incorrectly
}
}
} // namespace
namespace RDKit {
namespace MolHash {
static unsigned int NMDetermineComponents(RWMol *mol, unsigned int *parts,
unsigned int acount) {
PRECONDITION(mol, "bad molecule");
PRECONDITION(parts, "bad parts pointer");
memset(parts, 0, acount * sizeof(unsigned int));
std::vector<Atom *> todo;
unsigned int result = 0;
for (auto aptr : mol->atoms()) {
unsigned int idx = aptr->getIdx();
if (parts[idx] == 0) {
parts[idx] = ++result;
todo.push_back(aptr);
while (!todo.empty()) {
aptr = todo.back();
todo.pop_back();
for (auto nbri :
boost::make_iterator_range(mol->getAtomNeighbors(aptr))) {
auto nptr = (*mol)[nbri];
idx = nptr->getIdx();
if (parts[idx] == 0) {
parts[idx] = result;
todo.push_back(nptr);
}
}
}
}
}
return result;
}
static std::string NMMolecularFormula(RWMol *mol, const unsigned int *parts,
unsigned int part) {
PRECONDITION(mol, "bad molecule");
PRECONDITION((!part || parts), "bad parts pointer");
unsigned int hist[256];
int charge = 0;
memset(hist, 0, sizeof(hist));
for (auto aptr : mol->atoms()) {
unsigned int idx = aptr->getIdx();
if (part == 0 || parts[idx] == part) {
unsigned int elem = aptr->getAtomicNum();
if (elem < 256) {
hist[elem]++;
} else {
hist[0]++;
}
hist[1] += aptr->getTotalNumHs(false);
charge += aptr->getFormalCharge();
}
}
char buffer[16];
std::string result;
const unsigned char *perm = hist[6] ? OrganicHillOrder : InorganicHillOrder;
for (unsigned int i = 0; i < 119; i++) {
unsigned int elem = perm[i];
if (hist[elem] > 0) {
result += symbol[elem];
if (hist[elem] > 1) {
sprintf(buffer, "%u", hist[elem]);
result += buffer;
}
}
}
if (charge != 0) {
if (charge > 0) {
result += '+';
if (charge > 1) {
sprintf(buffer, "%d", charge);
result += buffer;
}
} else { // charge < 0
result += '-';
if (charge < -1) {
sprintf(buffer, "%d", -charge);
result += buffer;
}
}
}
return result;
}
static std::string NMMolecularFormula(RWMol *mol, bool sep = false) {
PRECONDITION(mol, "bad molecule");
if (!sep) {
return NMMolecularFormula(mol, nullptr, 0);
}
unsigned int acount = mol->getNumAtoms();
if (acount == 0) {
return "";
}
auto size = (unsigned int)(acount * sizeof(int));
auto *parts = (unsigned int *)malloc(size);
unsigned int pcount = NMDetermineComponents(mol, parts, acount);
std::string result;
if (pcount > 1) {
std::vector<std::string> vmf;
for (unsigned int i = 1; i <= pcount; i++) {
vmf.push_back(NMMolecularFormula(mol, parts, i));
}
// sort
result = vmf[0];
for (unsigned int i = 1; i < pcount; i++) {
result += ".";
result += vmf[i];
}
} else { // pcount == 1
result = NMMolecularFormula(mol, parts, 1);
}
free(parts);
return result;
}
static void NormalizeHCount(Atom *aptr) {
PRECONDITION(aptr, "bad atom pointer");
unsigned int hcount;
switch (aptr->getAtomicNum()) {
case 9: // Fluorine
case 17: // Chlorine
case 35: // Bromine
case 53: // Iodine
hcount = aptr->getDegree();
hcount = hcount < 1 ? 1 - hcount : 0;
break;
case 8: // Oxygen
case 16: // Sulfur
hcount = aptr->getDegree();
hcount = hcount < 2 ? 2 - hcount : 0;
break;
case 5: // Boron
hcount = aptr->getDegree();
hcount = hcount < 3 ? 3 - hcount : 0;
break;
case 7: // Nitogen
case 15: // Phosphorus
hcount = aptr->getDegree();
if (hcount < 3) {
hcount = 3 - hcount;
} else if (hcount == 4) {
hcount = 1;
} else {
hcount = 0;
}
break;
case 6: // Carbon
hcount = aptr->getDegree();
hcount = hcount < 4 ? 4 - hcount : 0;
break;
default:
hcount = 0;
}
aptr->setNoImplicit(true);
aptr->setNumExplicitHs(hcount);
}
static std::string AnonymousGraph(RWMol *mol, bool elem) {
PRECONDITION(mol, "bad molecule");
std::string result;
int charge = 0;
for (auto aptr : mol->atoms()) {
charge += aptr->getFormalCharge();
aptr->setIsAromatic(false);
aptr->setFormalCharge(0);
if (!elem) {
aptr->setNumExplicitHs(0);
aptr->setNoImplicit(true);
aptr->setAtomicNum(0);
} else {
NormalizeHCount(aptr);
}
}
for (auto bptr : mol->bonds()) {
bptr->setBondType(Bond::SINGLE);
}
MolOps::assignRadicals(*mol);
result = MolToSmiles(*mol);
return result;
}
static std::string MesomerHash(RWMol *mol, bool netq) {
PRECONDITION(mol, "bad molecule");
std::string result;
char buffer[32];
int charge = 0;
for (auto aptr : mol->atoms()) {
charge += aptr->getFormalCharge();
aptr->setIsAromatic(false);
aptr->setFormalCharge(0);
}
for (auto bptr : mol->bonds()) {
bptr->setBondType(Bond::SINGLE);
}
MolOps::assignRadicals(*mol);
result = MolToSmiles(*mol);
if (netq) {
sprintf(buffer, "_%d", charge);
result += buffer;
}
return result;
}
static std::string TautomerHash(RWMol *mol, bool proto) {
PRECONDITION(mol, "bad molecule");
std::string result;
char buffer[32];
int hcount = 0;
int charge = 0;
for (auto aptr : mol->atoms()) {
charge += aptr->getFormalCharge();
aptr->setIsAromatic(false);
aptr->setFormalCharge(0);
if (aptr->getAtomicNum() != 6) {
hcount += aptr->getTotalNumHs(false);
aptr->setNoImplicit(true);
aptr->setNumExplicitHs(0);
}
}
for (auto bptr : mol->bonds()) {
if (bptr->getBondType() != Bond::SINGLE &&
(bptr->getIsConjugated() || bptr->getBeginAtom()->getAtomicNum() != 6 ||
bptr->getEndAtom()->getAtomicNum() != 6)) {
bptr->setIsAromatic(false);
bptr->setBondType(Bond::SINGLE);
bptr->setStereo(Bond::BondStereo::STEREONONE);
}
}
MolOps::assignRadicals(*mol);
// we may have just destroyed some stereocenters/bonds
// clean that up:
bool cleanIt = true;
bool force = true;
MolOps::assignStereochemistry(*mol, cleanIt, force);
result = MolToSmiles(*mol);
if (!proto) {
sprintf(buffer, "_%d_%d", hcount, charge);
} else {
sprintf(buffer, "_%d", hcount - charge);
}
result += buffer;
return result;
}
static bool TraverseForRing(Atom *atom, unsigned char *visit) {
PRECONDITION(atom, "bad atom pointer");
PRECONDITION(visit, "bad pointer");
visit[atom->getIdx()] = 1;
for (auto nbri : boost::make_iterator_range(
atom->getOwningMol().getAtomNeighbors(atom))) {
auto nptr = atom->getOwningMol()[nbri];
if (visit[nptr->getIdx()] == 0) {
if (RDKit::queryIsAtomInRing(nptr)) {
return true;
}
if (TraverseForRing(nptr, visit)) {
return true;
}
}
}
return false;
}
static bool DepthFirstSearchForRing(Atom *root, Atom *nbor,
unsigned int maxatomidx) {
PRECONDITION(root, "bad atom pointer");
PRECONDITION(nbor, "bad atom pointer");
unsigned int natoms = maxatomidx;
auto *visit = (unsigned char *)alloca(natoms);
memset(visit, 0, natoms);
visit[root->getIdx()] = true;
return TraverseForRing(nbor, visit);
}
bool IsInScaffold(Atom *atom, unsigned int maxatomidx) {
PRECONDITION(atom, "bad atom pointer");
if (RDKit::queryIsAtomInRing(atom)) {
return true;
}
unsigned int count = 0;
for (auto nbri : boost::make_iterator_range(
atom->getOwningMol().getAtomNeighbors(atom))) {
auto nptr = atom->getOwningMol()[nbri];
if (DepthFirstSearchForRing(atom, nptr, maxatomidx)) {
++count;
}
}
return count > 1;
}
static bool HasNbrInScaffold(Atom *aptr, unsigned char *is_in_scaffold) {
PRECONDITION(aptr, "bad atom pointer");
PRECONDITION(is_in_scaffold, "bad pointer");
for (auto nbri : boost::make_iterator_range(
aptr->getOwningMol().getAtomNeighbors(aptr))) {
auto nptr = aptr->getOwningMol()[nbri];
if (is_in_scaffold[nptr->getIdx()]) {
return true;
}
}
return false;
}
static std::string ExtendedMurckoScaffold(RWMol *mol) {
PRECONDITION(mol, "bad molecule");
RDKit::MolOps::fastFindRings(*mol);
unsigned int maxatomidx = mol->getNumAtoms();
auto *is_in_scaffold = (unsigned char *)alloca(maxatomidx);
for (auto aptr : mol->atoms()) {
is_in_scaffold[aptr->getIdx()] = IsInScaffold(aptr, maxatomidx);
}
std::vector<Atom *> for_deletion;
for (auto aptr : mol->atoms()) {
unsigned int aidx = aptr->getIdx();
if (is_in_scaffold[aidx]) {
continue;
}
if (HasNbrInScaffold(aptr, is_in_scaffold)) {
aptr->setAtomicNum(0);
aptr->setFormalCharge(0);
aptr->setNoImplicit(true);
aptr->setNumExplicitHs(0);
} else {
for_deletion.push_back(aptr);
}
}
for (auto &i : for_deletion) {
mol->removeAtom(i);
}
MolOps::assignRadicals(*mol);
std::string result;
result = MolToSmiles(*mol);
return result;
}
static std::string MurckoScaffoldHash(RWMol *mol) {
PRECONDITION(mol, "bad molecule");
std::vector<Atom *> for_deletion;
do {
for_deletion.clear();
for (auto aptr : mol->atoms()) {
unsigned int deg = aptr->getDegree();
if (deg < 2) {
if (deg == 1) { // i.e. not 0 and the last atom in the molecule
for (const auto &nbri : boost::make_iterator_range(
aptr->getOwningMol().getAtomBonds(aptr))) {
auto bptr = (aptr->getOwningMol())[nbri];
Atom *nbr = bptr->getOtherAtom(aptr);
unsigned int hcount = nbr->getTotalNumHs(false);
nbr->setNumExplicitHs(hcount + NMRDKitBondGetOrder(bptr));
nbr->setNoImplicit(true);
}
}
for_deletion.push_back(aptr);
}
}
for (auto &i : for_deletion) {
mol->removeAtom(i);
}
} while (!for_deletion.empty());
MolOps::assignRadicals(*mol);
std::string result;
result = MolToSmiles(*mol);
return result;
}
static std::string NetChargeHash(RWMol *mol) {
PRECONDITION(mol, "bad molecule");
int totalq = 0;
for (auto aptr : mol->atoms()) {
totalq += aptr->getFormalCharge();
}
char buffer[16];
sprintf(buffer, "%d", totalq);
return buffer;
}
static std::string SmallWorldHash(RWMol *mol, bool brl) {
PRECONDITION(mol, "bad molecule");
char buffer[64];
unsigned int acount = mol->getNumAtoms();
unsigned int bcount = mol->getNumBonds();
unsigned int rcount = (bcount + 1) - acount;
if (brl) {
unsigned int lcount = 0;
for (auto aptr : mol->atoms()) {
if (aptr->getDegree() == 2) {
lcount++;
}
}
sprintf(buffer, "B%uR%uL%u", bcount, rcount, lcount);
} else {
sprintf(buffer, "B%uR%u", bcount, rcount);
}
return buffer;
}
static void DegreeVector(RWMol *mol, unsigned int *v) {
memset(v, 0, 4 * sizeof(unsigned int));
for (auto aptr : mol->atoms()) {
switch (aptr->getDegree()) {
case 4:
v[0]++;
break;
case 3:
v[1]++;
break;
case 2:
v[2]++;
break;
case 1:
v[3]++;
break;
}
}
}
static bool HasDoubleBond(Atom *atom) {
PRECONDITION(atom, "bad atom");
for (const auto &nbri :
boost::make_iterator_range(atom->getOwningMol().getAtomBonds(atom))) {
auto bptr = (atom->getOwningMol())[nbri];
if (NMRDKitBondGetOrder(bptr) == 2) {
return true;
}
}
return false;
}
// Determine whether/how to fragment bond
// -1 means don't fragment bond
// 0 means break, with hydrogens on both beg and end
// 1 means break, with asterisk on beg and hydrogen on end
// 2 means break, with hydrogen on beg and asterisk on end
// 3 means break, with asterisks on both beg and end
static int RegioisomerBond(Bond *bnd) {
PRECONDITION(bnd, "bad bond");
if (NMRDKitBondGetOrder(bnd) != 1) {
return -1;
}
if (RDKit::queryIsBondInRing(bnd)) {
return -1;
}
Atom *beg = bnd->getBeginAtom();
Atom *end = bnd->getEndAtom();
unsigned int beg_elem = beg->getAtomicNum();
unsigned int end_elem = end->getAtomicNum();
if (beg_elem == 0 || end_elem == 0) {
return -1;
}
if (RDKit::queryIsAtomInRing(beg)) {
if (RDKit::queryIsAtomInRing(end)) {
return 0;
}
return 2;
}
if (RDKit::queryIsAtomInRing(end)) {
return 1;
}
if (beg_elem != 6 && end_elem == 6 && !HasDoubleBond(end)) {
return 1;
}
if (beg_elem == 6 && end_elem != 6 && !HasDoubleBond(beg)) {
return 2;
}
return -1;
}
static void ClearEZStereo(Atom *atm) {
PRECONDITION(atm, "bad atom");
for (const auto &nbri :
boost::make_iterator_range(atm->getOwningMol().getAtomBonds(atm))) {
auto bptr = (atm->getOwningMol())[nbri];
if (bptr->getStereo() > RDKit::Bond::STEREOANY) {
bptr->setStereo(RDKit::Bond::STEREOANY);
}
}
}
static std::string RegioisomerHash(RWMol *mol) {
PRECONDITION(mol, "bad molecule");
// we need a copy of the molecule so that we can loop over the bonds of
// something while modifying something else
RDKit::MolOps::fastFindRings(*mol);
RDKit::ROMol molcpy(*mol);
for (int i = molcpy.getNumBonds() - 1; i >= 0; --i) {
auto bptr = molcpy.getBondWithIdx(i);
int split = RegioisomerBond(bptr);
if (split >= 0) {
bptr = mol->getBondWithIdx(i);
Atom *beg = bptr->getBeginAtom();
Atom *end = bptr->getEndAtom();
mol->removeBond(bptr->getBeginAtomIdx(), bptr->getEndAtomIdx());
ClearEZStereo(beg);
ClearEZStereo(end);
if (split & 1) {
Atom *star = new RDKit::Atom(0);
mol->addAtom(star, true, true);
star->setNoImplicit(true);
NMRDKitMolNewBond(mol, beg, star, 1, false);
} else {
unsigned int hcount = beg->getTotalNumHs(false);
beg->setNumExplicitHs(hcount + 1);
beg->setNoImplicit(true);
}
if (split & 2) {
Atom *star = new RDKit::Atom(0);
mol->addAtom(star, true, true);
star->setNoImplicit(true);
NMRDKitMolNewBond(mol, end, star, 1, false);
} else {
unsigned int hcount = end->getTotalNumHs(false);
end->setNumExplicitHs(hcount + 1);
end->setNoImplicit(true);
}
}
}
std::string result;
result = MolToSmiles(*mol);
return result;
}
static std::string ArthorSubOrderHash(RWMol *mol) {
PRECONDITION(mol, "bad molecule");
char buffer[256];
unsigned int acount = mol->getNumAtoms();
unsigned int bcount = mol->getNumBonds();
unsigned int pcount = 1;
unsigned int size = 4 * mol->getNumAtoms() + 4;
auto *parts = (unsigned int *)malloc(size);
if (parts) {
memset(parts, 0, size);
pcount = NMDetermineComponents(mol, parts, acount);
free(parts);
}
unsigned int ccount = 0;
unsigned int ocount = 0;
unsigned int zcount = 0;
unsigned int icount = 0;
unsigned int qcount = 0;
unsigned int rcount = 0;
for (auto aptr : mol->atoms()) {
unsigned int elem = aptr->getAtomicNum();
int charge = aptr->getFormalCharge();
switch (elem) {
case 6: // Carbon
ccount++;
if (charge == 0 && aptr->getTotalValence() != 4) {
rcount++;
}
break;
case 7: // Nitrogen
case 15: // Phosphorus
ocount++;
if (charge == 0) {
unsigned int valence = aptr->getTotalValence();
if (valence != 3 && valence != 5) {
rcount++;
}
}
break;
case 8: // Oxygen
ocount++;
if (charge && aptr->getTotalValence() != 2) {
rcount++;
}
break;
case 9: // Fluorine
ocount++;
if (charge && aptr->getTotalValence() != 1) {
rcount++;
}
break;
case 17: // Chlorine
case 35: // Bromine
case 53: // Iodine
ocount++;
if (charge == 0) {
unsigned int valence = aptr->getTotalValence();
if (valence != 1 && valence != 3 && valence != 5 && valence != 7) {
rcount++;
}
}
break;
case 16: // Sulfur
ocount++;
if (charge == 0) {
unsigned int valence = aptr->getTotalValence();
if (valence != 2 && valence != 4 && valence != 6) {
rcount++;
}
}
break;
}
zcount += elem;
if (aptr->getIsotope() != 0) {
icount++;
}
if (charge != 0) {
qcount++;
}
}
if (acount > 0xffff) {
acount = 0xffff;
}
if (bcount > 0xffff) {
bcount = 0xffff;
}
if (pcount > 0xff) {
pcount = 0xff;
}
if (ccount > 0xffff) {
ccount = 0xffff;
}
if (ocount > 0xffff) {
ocount = 0xffff;
}
if (zcount > 0xffffff) {
zcount = 0xffffff;
}
if (rcount > 0xff) {
rcount = 0xff;
}
if (qcount > 0xff) {
qcount = 0xff;
}
if (icount > 0xff) {
icount = 0xff;
}
sprintf(buffer, "%04x%04x%02x%04x%04x%06x%02x%02x%02x", acount, bcount,
pcount, ccount, ocount, zcount, rcount, qcount, icount);
return buffer;
}
std::string MolHash(RWMol *mol, HashFunction func) {
PRECONDITION(mol, "bad molecule");
std::string result;
char buffer[32];
NMRDKitSanitizeHydrogens(mol);
switch (func) {
default:
case HashFunction::AnonymousGraph:
result = AnonymousGraph(mol, false);
break;
case HashFunction::ElementGraph:
result = AnonymousGraph(mol, true);
break;
case HashFunction::CanonicalSmiles:
result = MolToSmiles(*mol);
break;
case HashFunction::MurckoScaffold:
result = MurckoScaffoldHash(mol);
break;
case HashFunction::ExtendedMurcko:
result = ExtendedMurckoScaffold(mol);
break;
case HashFunction::Mesomer:
result = MesomerHash(mol, true);
break;
case HashFunction::RedoxPair:
result = MesomerHash(mol, false);
break;
case HashFunction::HetAtomTautomer:
result = TautomerHash(mol, false);
break;
case HashFunction::HetAtomProtomer:
result = TautomerHash(mol, true);
break;
case HashFunction::MolFormula:
result = NMMolecularFormula(mol);
break;
case HashFunction::AtomBondCounts:
sprintf(buffer, "%u,%u", mol->getNumAtoms(), mol->getNumBonds());
result = buffer;
break;
case HashFunction::NetCharge:
result = NetChargeHash(mol);
break;
case HashFunction::SmallWorldIndexBR:
result = SmallWorldHash(mol, false);
break;
case HashFunction::SmallWorldIndexBRL:
result = SmallWorldHash(mol, true);
break;
case HashFunction::DegreeVector: {
unsigned int dv[4];
DegreeVector(mol, dv);
sprintf(buffer, "%u,%u,%u,%u", dv[0], dv[1], dv[2], dv[3]);
result = buffer;
} break;
case HashFunction::ArthorSubstructureOrder:
result = ArthorSubOrderHash(mol);
break;
case HashFunction::Regioisomer:
result = RegioisomerHash(mol);
break;
}
return result;
}
} // namespace MolHash
} // namespace RDKit
| 25.969767 | 80 | 0.57952 | [
"vector"
] |
7369514a840c4ca7ebaf529bc51bebd88e89e19e | 4,557 | cpp | C++ | triangle_v4_pthreads.cpp | pkarakal/vertexwise-triangle-counting | 1f935ef9870f86dcb4a40a0cd505223148a4e510 | [
"MIT"
] | 1 | 2020-12-06T13:13:14.000Z | 2020-12-06T13:13:14.000Z | triangle_v4_pthreads.cpp | pkarakal/vertexwise-triangle-counting | 1f935ef9870f86dcb4a40a0cd505223148a4e510 | [
"MIT"
] | 1 | 2020-12-06T05:55:45.000Z | 2020-12-06T14:04:09.000Z | triangle_v4_pthreads.cpp | pkarakal/vertexwise-triangle-counting | 1f935ef9870f86dcb4a40a0cd505223148a4e510 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <chrono>
#include <vector>
#include <pthread.h>
#include <algorithm>
#include "Graph.hpp"
extern "C" {
#include "mmio.h"
#include "coo2csc.h"
}
int main(int argc, char** argv){
int ret_code;
MM_typecode matcode;
FILE *f;
int M, N, nnz;
uint32_t i;
std::vector<uint32_t> I, J;
std::vector<double> val;
if (argc < 2)
{
fprintf(stderr, "Usage: %s [martix-market-filename] [0 for binary or 1 for non binary]\n", argv[0]);
exit(1);
}
else
{
if ((f = fopen(argv[1], "r")) == nullptr)
exit(1);
}
if (mm_read_banner(f, &matcode) != 0)
{
printf("Could not process Matrix Market banner.\n");
exit(1);
}
int threads{};
if(argc == 3){
threads= atoi(argv[2]);
} else {
threads = 4;
}
/* This is how one can screen matrix types if their application */
/* only supports a subset of the Matrix Market data types. */
if (mm_is_complex(matcode) && mm_is_matrix(matcode) &&
mm_is_sparse(matcode) )
{
printf("Sorry, this application does not support ");
printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode));
exit(1);
}
/* find out size of sparse matrix .... */
if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nnz)) != 0)
exit(1);
I = std::vector<uint32_t>(nnz);
J = std::vector<uint32_t>(nnz);
val = std::vector<double>(nnz);
std::vector<uint32_t> cscRow = std::vector<uint32_t>(2*nnz);
std::vector<uint32_t> cscColumn = std::vector<uint32_t>(N+1);
std::vector<uint32_t> c_values = std::vector<uint32_t>(0);
/* NOTE: when reading in doubles, ANSI C requires the use of the "l" */
/* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */
/* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */
/* Replace missing val column with 1s and change the fscanf to match pattern matrices*/
if (!mm_is_pattern(matcode)) {
for (i = 0; i < nnz; i++) {
fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]);
I[i]--; /* adjust from 1-based to 0-based */
J[i]--;
}
} else {
for (i = 0; i < nnz; i++) {
fscanf(f, "%d %d\n", &I[i], &J[i]);
val[i] = 1;
I[i]--; /* adjust from 1-based to 0-based */
J[i]--;
}
}
if (f !=stdin) fclose(f);
if(M != N) {
printf("COO matrix' columns and rows are not the same");
}
// create symmetric values
std::vector<uint32_t> temp1 = std::vector<uint32_t>(I.begin(), I.end());
I.insert(std::end(I), std::begin(J), std::end(J));
J.insert(std::end(J), std::begin(temp1), std::end(temp1));
temp1.clear();
if (I[0] < J[0]) {
coo2csc(&cscRow[0], &cscColumn[0], &I[0], &J[0], 2 * nnz, M, 0);
} else {
coo2csc(&cscRow[0], &cscColumn[0], &J[0], &I[0], 2 * nnz, N, 0);
}
std::sort(cscColumn.begin(), cscColumn.end());
std::vector<int>c3 = std::vector<int>(0);
std::vector<int>ones = std::vector<int>(N, 1);
std::vector<int>result_vector = std::vector<int>(N, 0);
c_values = std::vector<uint32_t>(2*nnz);
auto start = std::chrono::high_resolution_clock::now();
Graph graphs[threads];
pthread_t *pthreads;
pthreads = (pthread_t *)malloc(threads*sizeof(pthread_t));
int chunk = 1;
if(threads > 0) {
chunk = N / (threads);
}
for(i = 0; i < threads-1; i++) {
graphs[i] = Graph(cscRow, cscColumn, c_values, i*chunk, (i+1)*chunk, nnz, i);
pthread_create(&pthreads[i], NULL, Graph::statAdjMatMul, &graphs[i]);
}
graphs[threads -1] = Graph(cscRow,cscColumn, c_values, (threads-1)*chunk, (threads)*chunk + (N%threads), nnz, threads -1 );
pthread_create(&pthreads[threads - 1], NULL, Graph::statAdjMatMul, &graphs[threads - 1]);
for(i = 0; i < threads; i++) {
pthread_join(pthreads[i], NULL);
}
for(i = 0; i < N; i++) {
for(int j = cscColumn.at(i); j < cscColumn.at(i+1); j++) {
int value = c_values.at(j);
result_vector.at(cscRow.at(j)) += value * ones.at(i);
}
}
for(int res: result_vector){
c3.push_back(res/2);
}
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = stop - start;
std::cout<<"Took "<< elapsed.count() <<std::endl;
std::cout<<std::endl;
return 0;
} | 27.957055 | 127 | 0.54707 | [
"vector"
] |
736f20a9861d535ce67d0f844be198968f6280be | 7,662 | hh | C++ | src/Distributed/DistributedBoundary.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/Distributed/DistributedBoundary.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/Distributed/DistributedBoundary.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// DistributedBoundary -- Base class for distributed parallel boundary
// conditions, connecting NodeLists across parallel domains.
//
// Created by JMO, Thu Aug 23 21:34:32 PDT 2001
//----------------------------------------------------------------------------//
#ifndef DistributedBoundary_HH
#define DistributedBoundary_HH
#ifdef USE_MPI
#include <mpi.h>
#endif
#include "Boundary/Boundary.hh"
#include <vector>
#include <map>
#include <list>
// Forward declarations.
namespace Spheral {
template<typename Dimension> class NodeList;
template<typename Dimension> class FieldBase;
template<typename Dimension, typename DataType> class Field;
template<typename Dimension> class DataBase;
}
namespace Spheral {
template<typename Dimension>
class DistributedBoundary: public Boundary<Dimension> {
public:
//--------------------------- Public Interface ---------------------------//
typedef typename Dimension::Scalar Scalar;
typedef typename Dimension::Vector Vector;
typedef typename Dimension::Tensor Tensor;
typedef typename Dimension::SymTensor SymTensor;
typedef typename Dimension::ThirdRankTensor ThirdRankTensor;
typedef typename Dimension::FourthRankTensor FourthRankTensor;
typedef typename Dimension::FifthRankTensor FifthRankTensor;
typedef typename Dimension::FacetedVolume FacetedVolume;
struct DomainBoundaryNodes {
std::vector<int> sendNodes;
std::vector<int> receiveNodes;
};
typedef std::map<int, DomainBoundaryNodes> DomainBoundaryNodeMap;
typedef std::map<NodeList<Dimension>*, DomainBoundaryNodeMap> NodeListDomainBoundaryNodeMap;
// Constructors and destructors.
DistributedBoundary();
virtual ~DistributedBoundary();
// Get this domain ID.
int domainID() const;
// Total number of domains.
int numDomains() const;
// Test if the given NodeList is communicated on this domain or not.
bool communicatedNodeList(const NodeList<Dimension>& nodeList) const;
// Test if the given NodeList is communicated with the given domain.
bool nodeListSharedWithDomain(const NodeList<Dimension>& nodeList,
int neighborDomainID) const;
// Allow read access to the communication information.
const NodeListDomainBoundaryNodeMap& nodeListDomainBoundaryNodeMap() const;
const DomainBoundaryNodeMap& domainBoundaryNodeMap(const NodeList<Dimension>& nodeList) const;
const DomainBoundaryNodes& domainBoundaryNodes(const NodeList<Dimension>&,
int neighborDomainID) const;
// Extract the current set of processors we're communicating with.
void communicatedProcs(std::vector<int>& sendProcs,
std::vector<int>& recvProcs) const;
//****************************************************************************
// Required Boundary interface
virtual void setGhostNodes(NodeList<Dimension>& nodeList) override; // This one should not be used with DistributedBoundary
virtual void updateGhostNodes(NodeList<Dimension>& nodeList) override;
// Distributed boundaries don't have "violate" nodes, so override these methods to no-ops.
virtual void setViolationNodes(NodeList<Dimension>& nodeList) override;
virtual void updateViolationNodes(NodeList<Dimension>& nodeList) override;
// Apply the boundary condition to the given Field.
virtual void applyGhostBoundary(FieldBase<Dimension>& field) const override;
//****************************************************************************
// Require descendent Distributed Neighbors to provide the setGhostNodes method for DataBases.
virtual void setAllGhostNodes(DataBase<Dimension>& dataBase) override = 0;
// Override the Boundary method for culling ghost nodes.
virtual void cullGhostNodes(const FieldList<Dimension, int>& flagSet,
FieldList<Dimension, int>& old2newIndexMap,
std::vector<int>& numNodesRemoved) override;
// Override the base method to finalize ghost boundaries.
virtual void finalizeGhostBoundary() const override;
// We do not want to use the parallel ghost nodes as generators.
virtual bool meshGhostNodes() const override;
//****************************************************************************
// Non-blocking exchanges.
void beginExchangeFieldFixedSize(FieldBase<Dimension>& field) const;
void beginExchangeFieldVariableSize(FieldBase<Dimension>& field) const;
// Force the exchanges which have been registered to execute.
void finalizeExchanges();
// Unpack a packed set of Field values back into the Field.
void unpackField(FieldBase<Dimension>& field,
const std::list< std::vector<char> >& packedValues) const;
// Update the control and ghost nodes of the base class.
void setControlAndGhostNodes();
// Prevent the Boundary virtual methods from being hidden
using Boundary<Dimension>::applyGhostBoundary;
using Boundary<Dimension>::enforceBoundary;
protected:
//--------------------------- Protected Interface ---------------------------//
// Descendent classes get read/write access to the communication maps.
NodeListDomainBoundaryNodeMap& accessNodeListDomainBoundaryNodeMap();
DomainBoundaryNodeMap& accessDomainBoundaryNodeMap(const NodeList<Dimension>& nodeList);
DomainBoundaryNodes& accessDomainBoundaryNodes(const NodeList<Dimension>&,
int neighborDomainID);
// Convenience method to return an iterator to the DomainBoundaryNodes for the
// given NodeList and domain pair. If there isn't an entry for this pair already,
// this method creates one.
DomainBoundaryNodes& openDomainBoundaryNodes(NodeList<Dimension>* nodeListPtr,
const int domainID);
// Inverse of above -- remove the DomainBoundaryNodes for a NodeList/procID pair.
void removeDomainBoundaryNodes(NodeList<Dimension>* nodeListPtr,
const int domainID);
// Override the Boundary method for clearing the maps.
virtual void reset(const DataBase<Dimension>& dataBase) override;
// This handy helper method will build receive and ghost nodes on all each
// domain based on send nodes that have already been filled in.
void buildReceiveAndGhostNodes(const DataBase<Dimension>& dataBase);
private:
//--------------------------- Private Interface ---------------------------//
int mDomainID;
NodeListDomainBoundaryNodeMap mNodeListDomainBoundaryNodeMap;
// List of the fields that are currently backlogged for exchanging.
mutable std::vector<FieldBase<Dimension>*> mExchangeFields;
// Internal tag for MPI communiators.
mutable int mMPIFieldTag;
#ifdef USE_MPI
// Send/receive requests.
mutable std::vector<MPI_Request> mSendRequests;
mutable std::vector<MPI_Request> mRecvRequests;
#endif
#ifdef USE_MPI_DEADLOCK_DETECTION
mutable std::vector<int> mSendProcIDs;
mutable std::vector<int> mRecvProcIDs;
#endif
// Buffers for holding send/receive data.
typedef std::list<std::list<std::vector<char>>> CommBufferSet;
mutable CommBufferSet mSendBuffers;
mutable CommBufferSet mRecvBuffers;
// Maps linking fields to their communication buffers.
typedef std::map<const FieldBase<Dimension>*, std::list<std::vector<char>>*> Field2BufferType;
mutable Field2BufferType mField2SendBuffer;
mutable Field2BufferType mField2RecvBuffer;
};
}
#include "DistributedBoundaryInline.hh"
#else
// Forward declaration.
namespace Spheral {
template<typename Dimension> class DistributedBoundary;
}
#endif
| 38.893401 | 131 | 0.697599 | [
"vector"
] |
7373c98b095d66ab081ad07d708ef04d991054f3 | 1,850 | cpp | C++ | inference-engine/tests/unit/engines/gna/gna_proc_type_test.cpp | FengYen-Chang/dldt | 1a7ab8871de68bef05c959ea20191d8242761635 | [
"Apache-2.0"
] | 1 | 2020-08-26T02:37:00.000Z | 2020-08-26T02:37:00.000Z | inference-engine/tests/unit/engines/gna/gna_proc_type_test.cpp | FengYen-Chang/dldt | 1a7ab8871de68bef05c959ea20191d8242761635 | [
"Apache-2.0"
] | null | null | null | inference-engine/tests/unit/engines/gna/gna_proc_type_test.cpp | FengYen-Chang/dldt | 1a7ab8871de68bef05c959ea20191d8242761635 | [
"Apache-2.0"
] | 1 | 2018-12-14T07:52:51.000Z | 2018-12-14T07:52:51.000Z | //
// Copyright 2016-2018 Intel Corporation.
//
// This software and the related documents are Intel copyrighted materials,
// and your use of them is governed by the express license under which they
// were provided to you (End User License Agreement for the Intel(R) Software
// Development Products (Version May 2017)). Unless the License provides
// otherwise, you may not use, modify, copy, publish, distribute, disclose or
// transmit this software or the related documents without Intel's prior
// written permission.
//
// This software and the related documents are provided as is, with no
// express or implied warranties, other than those that are expressly
// stated in the License.
//
#include <vector>
#include <gtest/gtest.h>
#include <mock_icnn_network.hpp>
#include <gmock/gmock-generated-actions.h>
#include <gna/gna_config.hpp>
#include "gna_plugin.hpp"
#include "gna_mock_api.hpp"
#include "gna_matcher.hpp"
using namespace std;
using namespace InferenceEngine;
using namespace GNAPluginNS;
using namespace ::testing;
class GNAProcTypeTest : public GNATest {
protected:
};
TEST_F(GNAProcTypeTest, defaultProcTypeIsSWEXACT) {
assert_that().onInfer1AFModel().gna().propagate_forward().called_with().proc_type(GNA_SOFTWARE & GNA_HARDWARE);
}
TEST_F(GNAProcTypeTest, canPassHWProcTypeToGNA) {
assert_that().onInfer1AFModel().withGNADeviceMode("GNA_HW").gna().propagate_forward().called_with().proc_type(GNA_HARDWARE);
}
TEST_F(GNAProcTypeTest, canPassSWProcTypeToGNA) {
assert_that().onInfer1AFModel().withGNADeviceMode("GNA_SW").gna().propagate_forward().called_with().proc_type(GNA_SOFTWARE);
}
TEST_F(GNAProcTypeTest, canPassSWEXACTProcTypeToGNA) {
assert_that().onInfer1AFModel().withGNADeviceMode("GNA_SW_EXACT").gna().
propagate_forward().called_with().proc_type(GNA_SOFTWARE & GNA_HARDWARE);
} | 35.576923 | 128 | 0.776216 | [
"vector"
] |
7373f3b9008b59ddebde4155cbe8e32f61349963 | 4,102 | hpp | C++ | redemption/src/regex/regex_utils.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/regex/regex_utils.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/regex/regex_utils.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Product name: redemption, a FLOSS RDP proxy
* Copyright (C) Wallix 2010-2013
* Author(s): Christophe Grosjean, Raphael Zhou, Jonathan Poelen, Meng Tan
*/
#pragma once
#include <vector>
#include "regex_state.hpp"
namespace re {
struct IsNotCapture
{
bool operator()(const State * st) const
{
return ! st->is_cap();
}
};
struct IsEpsilone
{
bool operator()(State * st) const
{
return st->is_epsilone();
}
};
using const_state_list_t = std::vector<const State *>;
using state_list_t = std::vector<State *>;
inline void append_state(State * st, state_list_t& sts)
{
//if (st && st->num != -1u) {
// st->num = -1u;
// sts.push_back(st);
// append_state(st->out1, sts);
// append_state(st->out2, sts);
//}
if (!st) {
return ;
}
state_list_t stack;
stack.reserve(16);
sts.reserve(32);
st->num = -1u;
sts.push_back(st);
stack.push_back(st);
while (!stack.empty()) {
st = stack.back();
while (st->out1 && st->out1->num != -1u) {
st = st->out1;
stack.push_back(st);
sts.push_back(st);
st->num = -1u;
}
st = st->out2;
if (st && st->num != -1u) {
stack.push_back(st);
sts.push_back(st);
st->num = -1u;
continue;
}
stack.pop_back();
while (!stack.empty()) {
st = stack.back()->out2;
if (st && st->num != -1u) {
stack.push_back(st);
sts.push_back(st);
st->num = -1u;
break;
}
stack.pop_back();
}
}
}
template<typename Deleter>
inline void remove_epsilone(state_list_t & states, Deleter deleter)
{
state_list_t::iterator last = states.end();
if (std::find_if(states.begin(), last, IsEpsilone()) != last) {
for (state_list_t::iterator first = states.begin(); first != last; ++first) {
State * nst = (*first)->out1;
while (nst && nst->is_epsilone()) {
nst = nst->out1;
}
(*first)->out1 = nst;
nst = (*first)->out2;
while (nst && nst->is_epsilone()) {
nst = nst->out1;
}
(*first)->out2 = nst;
}
state_list_t::iterator first = states.begin();
while (first != last && !(*first)->is_epsilone()) {
++first;
}
state_list_t::iterator result = first;
for (; first != last; ++first) {
if ((*first)->is_epsilone()) {
deleter(*first);
}
else {
*result = *first;
++result;
}
}
states.resize(result - states.begin());
}
}
struct StateDeleter
{
void operator()(State * st) const
{
delete st; /*NOLINT*/
}
};
} // namespace re
| 28.486111 | 89 | 0.476353 | [
"vector"
] |
7376e64fc06794fa6e8fcfae96942e7a8d08bcdd | 46,869 | cpp | C++ | betteryao/GarbledCircuit.cpp | bt3ze/pcflib | c66cdc5957818cd5b3754430046cad91ce1a921d | [
"BSD-2-Clause"
] | null | null | null | betteryao/GarbledCircuit.cpp | bt3ze/pcflib | c66cdc5957818cd5b3754430046cad91ce1a921d | [
"BSD-2-Clause"
] | null | null | null | betteryao/GarbledCircuit.cpp | bt3ze/pcflib | c66cdc5957818cd5b3754430046cad91ce1a921d | [
"BSD-2-Clause"
] | null | null | null | #ifndef GARBLED_CIRCUIT_CPP
#define GARBLED_CIRCUIT_CPP
#include "GarbledCircuit.h"
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <algorithm>
/**
ACCESSORY FUNCTIONS
*/
/*
void *copy_key(void *old_key)
{
__m128i *new_key = 0;
if (old_key != 0)
{
// first argument is size, second argument is allignment
new_key = (__m128i*)_mm_malloc(sizeof(__m128i), sizeof(__m128i));
*new_key = *reinterpret_cast<__m128i*>(old_key);
}
//print128_num(*new_key);
return new_key;
}
*/
void copy_key(void* source_key, void * dest_key){
// __m128i *new_key = 0;
//fprintf(stdout,"copy key \n");
if (source_key != 0)
{
// first argument is size, second argument is allignment
//new_key = (__m128i*)_mm_malloc(sizeof(__m128i), sizeof(__m128i));
num_copies++;
clock_gettime(CLOCK_REALTIME, ©_start);
_mm_storeu_si128(reinterpret_cast<__m128i*>(dest_key),*reinterpret_cast<__m128i*>(source_key));
clock_gettime(CLOCK_REALTIME, ©_end);
copy_time += ( copy_end.tv_sec - copy_start.tv_sec )
+ ( copy_end.tv_nsec - copy_start.tv_nsec )
/ BILN;
} else{
fprintf(stderr,"no copy\n");
}
// return new_key;
}
void delete_key(void *key)
{
// if (key != 0) _mm_free(key);
}
void save_Key_to_128bit(const Bytes & key, __m128i & destination){
num_buffers++;
clock_gettime(CLOCK_REALTIME, &buffer_start);
Bytes tmp = key;
tmp.resize(16,0);
destination = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
//destination = _mm_loadu_si128(reinterpret_cast<__m128i*>(key[0]));
clock_gettime(CLOCK_REALTIME, &buffer_end);
buffer_time += ( buffer_end.tv_sec - buffer_start.tv_sec )
+ ( buffer_end.tv_nsec - buffer_start.tv_nsec )
/ BILN;
}
void append_m128i_to_Bytes(const __m128i & num, Bytes & dest){
Bytes tmp;
num_buffers++;
clock_gettime(CLOCK_REALTIME, &buffer_start);
tmp.resize(16,0);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]),num);
dest.insert(dest.end(),tmp.begin(),tmp.begin()+Env::key_size_in_bytes());
//m_temp_bufr.clear();
//_mm_storeu_si128(reinterpret_cast<__m128i*>(&m_temp_bufr[0]),num);
//dest.insert(dest.end(),m_temp_bufr.begin(),m_temp_bufr.begin()+Env::key_size_in_bytes());
// _mm_storeu_si128(reinterpret_cast<__m128i*>(&dest[0]),num);
clock_gettime(CLOCK_REALTIME, &buffer_end);
buffer_time += ( buffer_end.tv_sec - buffer_start.tv_sec )
+ ( buffer_end.tv_nsec - buffer_start.tv_nsec )
/ BILN;
}
void insert_to_garbling_bufr(const __m128i & num, Bytes & dest, Bytes & tmp_bufr, uint32_t pos){
//std::fill(tmp_bufr.begin(),tmp_bufr.end(),0);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp_bufr[0]),num);
dest.insert(dest.begin()+pos*Env::key_size_in_bytes(),tmp_bufr.begin(),tmp_bufr.begin()+Env::key_size_in_bytes());
//_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp_bufr[0]),num);
}
/**
These functions serve as intermediaries
to get back to the Garbled Circuit object
since we go through such crazy calling loops with
the pcf interpreter struct
*/
void * gen_next_gate(PCFState *st, PCFGate *current_gate){
// returns void pointer, which is pointer to a key?
// use this one to call the Garbled Circuit object again
//fprintf(stdout,"get next gate\n");
GarbledCircuit &cct = *reinterpret_cast<GarbledCircuit*>(get_external_circuit(st));
return cct.gen_Next_Gate(current_gate);
}
void * evl_next_gate(PCFState *st, PCFGate *current_gate){
// returns void pointer, which is pointer to a key
// use this one to call the Garbled Circuit object again
//fprintf(stdout,"evl next gate\n");
GarbledCircuit &cct = *reinterpret_cast<GarbledCircuit*>(get_external_circuit(st));
// now, call the appropriate function from cct
return cct.evl_Next_Gate(current_gate);
}
void print128_num(__m128i var)
{
uint16_t *val = (uint16_t*) &var;
fprintf(stderr,"Numerical: %x %x %x %x %x %x %x %x \n",
val[0], val[1], val[2], val[3], val[4], val[5],
val[6], val[7]);
}
/**
INITIALIZING GARBLED CIRCUITS
*/
GarbledCircuit::GarbledCircuit(): m_gate_index(0), m_bob_out_ix(0),m_alice_out_ix(0),m_hash_row_idx(0), m_comm_time(0.0) {
// initialize the key Mask
Bytes tmp(16);
for(size_t ix = 0; ix< Env::k(); ix++){
tmp.set_ith_bit(ix,1);
}
m_clear_mask = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
m_alice_out.clear();
m_bob_out.clear();
}
void GarbledCircuit::set_Gen_Circuit_Functions(){
set_key_copy_function(m_st, copy_key);
set_key_delete_function(m_st, delete_key);
set_callback(m_st,gen_next_gate);
}
void GarbledCircuit::set_Evl_Circuit_Functions(){
set_key_copy_function(m_st, copy_key);
set_key_delete_function(m_st, delete_key);
set_callback(m_st,evl_next_gate);
}
void GarbledCircuit::set_Input_Keys(const std::vector<Bytes> * gen_keys, const std::vector<Bytes> * evl_keys){
m_gen_inputs = gen_keys;
m_evl_inputs = evl_keys;
}
void GarbledCircuit::init_Generation_Circuit(const std::vector<Bytes> * gen_keys, const std::vector<Bytes> * evl_keys, const uint32_t gen_inp_size, Bytes & circuit_seed, const Bytes & perm_bits, const Bytes R, const Bytes & zero_key, const Bytes & one_key){
Bytes tmp;
m_prng.seed_rand(circuit_seed);
m_select_bits.insert(m_select_bits.begin(),perm_bits.begin(),perm_bits.begin() + perm_bits.size());
// initialize the value of R
// we initialize tmp with zeros for this so that
// the value of R doesn't get extra nonsense at the end
// from whatever was sitting around in memory
tmp.resize(16,0);
tmp.insert(tmp.begin(),R.begin(),R.begin()+Env::k()/8);
m_R = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&tmp[0]));
// also initialize the Bytes version of R,
// used for returning keys of proper parity for Gen
m_R_bytes = R;
// initialize the constant wires
save_Key_to_128bit(zero_key,m_const_wire[0]);
save_Key_to_128bit(one_key, m_const_wire[1]);
m_gen_inp_size = gen_inp_size;
set_Input_Keys(gen_keys, evl_keys);
// for now, use zeroes and the aes key
__m128i aes_key = m_const_wire[0];
//aes_key = _mm_xor_si128(aes_key,aes_key);
init_circuit_AES_key(aes_key);
m_garbling_bufr.resize(256,0);
m_message_queue.resize(MESSAGE_LIMIT*Env::key_size_in_bytes());
m_message_limit = MESSAGE_LIMIT;
m_messages_waiting = 0;
m_queue_index = 0;
xor_gates = half_gates = other_gates = total_gates = 0;
xor_time = hg_time = og_time = garble_time = 0.0;
}
void GarbledCircuit::init_Evaluation_Circuit(const std::vector<Bytes> * gen_keys, const std::vector<Bytes> * evl_keys,const uint32_t gen_inp_size, const Bytes & evl_input, const Bytes &zero_key, const Bytes & one_key){
set_Input_Keys(gen_keys, evl_keys);
//m_select_bits = evl_input;
m_select_bits.insert(m_select_bits.begin(),evl_input.begin(),evl_input.begin() + evl_input.size());
save_Key_to_128bit(zero_key,m_const_wire[0]);
save_Key_to_128bit(one_key, m_const_wire[1]);
m_gen_inp_size = gen_inp_size;
// for now, let the fixed aes key be zeroes.
__m128i aes_key = m_const_wire[0];
// aes_key = _mm_xor_si128(aes_key,aes_key);
init_circuit_AES_key(aes_key);
m_garbling_bufr.resize(256,0);
m_message_queue.resize(MESSAGE_LIMIT*Env::key_size_in_bytes());
m_message_limit = MESSAGE_LIMIT;
m_messages_waiting = 0;
m_queue_index = 0;
xor_gates = half_gates = other_gates = total_gates = 0;
xor_time = hg_time = og_time = garble_time = 0.0;
}
/**
this function sets our AES key for constant-key garbling
the key must be fed to the function
*/
void GarbledCircuit::init_circuit_AES_key(__m128i &key){
AES_set_encrypt_key((unsigned char*)&key, 128, &m_fixed_key);
}
void * GarbledCircuit::get_Const_Wire(uint32_t i){
assert(i == 0 || i == 1);
return &(m_const_wire[i]);
}
/**
Input Key Accessor Functions
get-Key functions are intended for Gen (although they call the get-Input) functions
get-Input functions are intended for Eval
*/
Bytes GarbledCircuit::get_Gen_Key(uint32_t input_idx, uint32_t parity){
assert(parity == 0 || parity == 1);
return get_Gen_Input(2*input_idx + parity);
}
Bytes GarbledCircuit::get_Evl_Key(uint32_t input_idx, uint32_t parity){
assert(parity == 0 || parity == 1);
return get_Evl_Input(2*input_idx + parity);
}
Bytes GarbledCircuit::get_Gen_Input(uint32_t idx){
Bytes ret = (*m_gen_inputs)[idx];
return ret;
}
Bytes GarbledCircuit::get_Evl_Input(uint32_t idx){
if(idx < m_evl_inputs->size()){
return (*m_evl_inputs)[idx];
} else{
fprintf(stdout,"Eval uninitialized wire: %i\n",idx);
Bytes tmp;
__m128i key = *((__m128i*)get_Const_Wire(0));
append_m128i_to_Bytes(key, tmp );
return tmp;
}
}
uint32_t GarbledCircuit::get_Input_Parity(uint32_t idx){
// Gen uses this to look up permutation bits
// Eval uses this function to figure out what input key to decrpyt
if(idx < m_select_bits.size()*8){
return m_select_bits.get_ith_bit(idx);
} else{
fprintf(stdout,"input out of bounds: %x\n",idx);
return 0;
}
}
/**
EVALUATION/GARBLING FUNCTION
*/
void GarbledCircuit::Garble_Circuit(){
while(get_next_gate(m_st)){
}
send_buffer(); // last send, in case there's something left over
}
void GarbledCircuit::Evaluate_Circuit(){
do {
} while(get_next_gate(m_st));
//retrieve_buffer();
fprintf(stderr,"finish evaluating\n");
}
/**
GARBLING ACCESSORY FUNCTIONS
*/
/**
This function doubles in GF2 by shifting "key" left one bit.
the clear mask is included to ensure that all keys remain the same length
(we don't want a key boundary overflowing!)
*/
void Double(__m128i & key, __m128i & clear_mask){
uint64_t * modifier = (uint64_t*) &key;
uint64_t carry = modifier[0] & ((uint64_t) 0x8000000000000000) > 0 ? 1 : 0;
modifier[0] = modifier[0]<<1;
modifier[1] = (modifier[1]<<1) | carry;
key = _mm_and_si128(key, clear_mask);
}
/**
This function computes the permutation on an input key
it is destructive of key so must make copies of the inputs first
it returns H(K) = pi(L) xor L where L = 2key ^ tweak
*/
void H_Pi(__m128i & destination, __m128i &key, __m128i & tweak, __m128i & clear_mask, AES_KEY_J & fixed_key){
__m128i K; // ,K1;
Double(key, clear_mask);
K = _mm_xor_si128(key,tweak);
KDF128((uint8_t*)&destination,(uint8_t*)&K, &fixed_key);
destination = _mm_xor_si128(destination, K);
destination = _mm_and_si128(destination,clear_mask);
}
/**
remember to copy the keys before they enter this function, because it's destructive to key1 and key2
*/
void H_Pi256(__m128i & destination, __m128i &key1, __m128i &key2, __m128i & tweak, __m128i & clear_mask, AES_KEY_J & fixed_key){
// takes two keys and computes a ciphertest, A la JustGarble
__m128i K;
Double(key1,clear_mask);
Double(key2,clear_mask);
Double(key2,clear_mask);
K = _mm_xor_si128(key1,key2);
K = _mm_xor_si128(K,tweak);
KDF128((uint8_t*)&destination,(uint8_t*)&K, &fixed_key);
destination = _mm_xor_si128(destination, K);
destination = _mm_and_si128(destination,clear_mask);
}
/**
throughout garbling, Gen will maintain the zero-semantic keys for each wire
and use them to generate all of the ciphertexts (find the 1-semantics by XOR with R)
that are sent to Eval
this function returns current_key to the pcf_state struct
*/
void * GarbledCircuit::gen_Next_Gate(PCFGate *current_gate){
//clock_gettime(CLOCK_REALTIME, &bstart);
// double start = MPI_Wtime();
static __m128i current_key; // must be static to return it
if(current_gate->tag == TAG_INTERNAL){
// actual gate
clear_garbling_bufr();
generate_Gate(current_gate,current_key,m_garbling_bufr);
m_gate_index++;
} else if(current_gate->tag == TAG_INPUT_A){
// fprintf(stdout, "Alice Input!");
clear_garbling_bufr();
generate_Alice_Input(current_gate, current_key, m_garbling_bufr);
// send two ciphertexts
// return ¤t_key;
} else if (current_gate->tag == TAG_INPUT_B){
// fprintf(stdout, "Bob Input!");
generate_Bob_Input(current_gate, current_key);
// return ¤t_key;
} else if (current_gate->tag == TAG_OUTPUT_A) {
// fprintf(stdout,"Alice Output!\n");
clear_garbling_bufr();
generate_Alice_Output(current_gate,current_key, m_garbling_bufr);
m_gate_index++;
// return ¤t_key;
} else if (current_gate->tag == TAG_OUTPUT_B){
// fprintf(stdout,"Bob Output!\n");
clear_garbling_bufr();
generate_Bob_Output(current_gate, current_key, m_garbling_bufr);
Bytes tmp;
append_m128i_to_Bytes(current_key,tmp);
m_gen_output_labels.push_back(tmp); // for output authenticity proof
m_gate_index++;
//return ¤t_key;
} else {
fprintf(stdout,"read gate error\n");
exit(0);
//return ¤t_key;
}
// benchmark_time += MPI_Wtime() - start;
// clock_gettime(CLOCK_REALTIME, &bend);
//btime2 += ( bend.tv_sec - bstart.tv_sec )
// + ( bend.tv_nsec - bstart.tv_nsec )
// / BILN;
return ¤t_key;
}
void * GarbledCircuit::evl_Next_Gate(PCFGate *current_gate){
// double start = MPI_Wtime();
//clock_gettime(CLOCK_REALTIME, &bstart);
static __m128i current_key; // must be static to return it
if(current_gate->tag == TAG_INTERNAL){
evaluate_Gate(current_gate,current_key, m_garbling_bufr);
m_gate_index++;
} else if(current_gate->tag == TAG_INPUT_A){
evaluate_Alice_Input(current_gate, current_key, m_garbling_bufr);
//return ¤t_key;
} else if (current_gate->tag == TAG_INPUT_B){
evaluate_Bob_Input(current_gate,current_key);
//return ¤t_key;
} else if (current_gate->tag == TAG_OUTPUT_A) {
// fprintf(stdout,"Alice Output!\n");
evaluate_Alice_Output(current_gate,current_key, m_garbling_bufr);
m_gate_index++;
//return ¤t_key;
} else if (current_gate->tag == TAG_OUTPUT_B){
// fprintf(stdout,"Bob Output!\n");
//mask Bob's output with his output masking key
evaluate_Bob_Output(current_gate, current_key, m_garbling_bufr);
// save this for later, when we need to do gen's
// output authenticity proof
Bytes tmp;
append_m128i_to_Bytes(current_key,tmp);
m_gen_output_labels.push_back(tmp);
m_gate_index++;
//return ¤t_key;
} else {
fprintf(stderr,"gate read error\n");
exit(0);
//return ¤t_key;
}
// benchmark_time += MPI_Wtime() - start;
//clock_gettime(CLOCK_REALTIME, &bend);
//btime2 += ( bend.tv_sec - bstart.tv_sec )
// + ( bend.tv_nsec - bstart.tv_nsec )
// / BILN;
return ¤t_key;
}
void GarbledCircuit::xor_Gate(__m128i & key1, __m128i & key2, __m128i ¤t_key){
current_key = _mm_xor_si128(key1,key2);
}
uint32_t GarbledCircuit::increment_index(){
return m_gate_index++;
}
void GarbledCircuit::generate_Bob_Input(PCFGate* current_gate, __m128i ¤t_key){
// Gen's input keys have already been generated and determined
// by his input keys; here, we return the proper input key encoding 0
uint32_t gen_input_idx = current_gate->wire1; // wire1 holds the input index
Bytes gen_input = get_Gen_Key(gen_input_idx,get_Input_Parity(gen_input_idx));
save_Key_to_128bit(gen_input,current_key);
// we need to set the garbling buffer to something (or nothing)
// because it will be sent by default between gates
// m_garbling_bufr = Bytes(0);
}
void GarbledCircuit::evaluate_Bob_Input(PCFGate* current_gate, __m128i ¤t_key){
// here, Gen's input keys have been sent to Eval
// she needs only to assign the input key to the wire
uint32_t gen_input_idx = current_gate->wire1; // wire1 holds the input index
Bytes gen_input = get_Gen_Input(gen_input_idx);
save_Key_to_128bit(gen_input,current_key);
// and current_key is available up the call stack
}
void GarbledCircuit::generate_Alice_Input(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
// Here, Eval already has her input keys, but Gen doesn't know
// which to use. So he will generate a new key and its XOR-offset,
// encrypt it using the respective Eval input keys, and send the keys to Eval.
// She will decrypt the proper one and use it
__m128i output_keys[2];
Bytes new_zero_key;
Bytes tmp; // used for loading input keys
new_zero_key = m_prng.rand_bits(Env::k());
new_zero_key.resize(16,0);
new_zero_key.set_ith_bit(0,0);
// save this zero-key for future access
current_key = _mm_loadu_si128(reinterpret_cast<__m128i*>(&new_zero_key[0]));
// load the first output key
tmp = get_Evl_Key(current_gate->wire1,0);
tmp.resize(16,0);
output_keys[0] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
// load the second output key
tmp = get_Evl_Key(current_gate->wire1,1); // wire1 = wire2
tmp.resize(16,0);
output_keys[1] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
// encrypt the output keys so that Eval can get only one of them
output_keys[0] = _mm_xor_si128(output_keys[0], current_key);
output_keys[1] = _mm_xor_si128(output_keys[1], _mm_xor_si128(current_key,m_R));
// send the output keys to Eval for decryption
append_m128i_to_Bytes(output_keys[0],garbling_bufr);
append_m128i_to_Bytes(output_keys[1],garbling_bufr);
assert(garbling_bufr.size() == 2*Env::key_size_in_bytes());
send_half_gate(garbling_bufr);
}
void GarbledCircuit::evaluate_Alice_Input(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
// here, Eval already knows which input key she wants to use
// she selects it and assigns it to her wire value
uint32_t gen_input_idx = current_gate->wire1; // wire1 holds the input index
Bytes evl_input = get_Evl_Input(gen_input_idx);
// receive 2 ciphertexts
//garbling_bufr = read_half_gate();
read_half_gate(garbling_bufr);
assert(garbling_bufr.size() == 2*Env::key_size_in_bytes());
// find the input ciphertext that corresponds to Eval's chosen bit
uint32_t bit = get_Input_Parity(current_gate->wire1);
assert(bit == 0 || bit == 1);
// select the one to decrypt
Bytes encrypted_input;
encrypted_input.insert(encrypted_input.end(),
garbling_bufr.begin() + bit * Env::key_size_in_bytes(),
garbling_bufr.begin() + Env::key_size_in_bytes() + bit * Env::key_size_in_bytes());
assert(evl_input.size() == Env::key_size_in_bytes());
evl_input = evl_input ^ encrypted_input;
save_Key_to_128bit(evl_input,current_key);
}
// Alice's outputs
void GarbledCircuit::evaluate_Alice_Output(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
evaluate_Gate(current_gate,current_key,garbling_bufr);
//print128_num(current_key);
if(m_alice_out.size()*8 <= m_alice_out_ix){
m_alice_out.resize((m_alice_out.size()+1)*2,0); // grow by doubling
}
uint8_t out_bit = _mm_extract_epi8(current_key, 0) & 0x01;
m_alice_out.set_ith_bit(m_alice_out_ix, out_bit);
m_alice_out_ix++;
}
// Gen's outputs
void GarbledCircuit::evaluate_Bob_Output(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
if (m_bob_out.size()*8 <= m_bob_out_ix)
{
// dynamically grow output array by doubling
m_bob_out.resize((m_bob_out.size()+1)*2, 0);
}
Bytes output_mask = get_Gen_Input(m_gen_inp_size + m_bob_out_ix);
__m128i output_mask_key;
save_Key_to_128bit(output_mask, output_mask_key);
current_key = _mm_xor_si128(output_mask_key, current_key);
evaluate_Gate(current_gate, current_key, garbling_bufr);
uint8_t out_bit = _mm_extract_epi8(current_key,0)& 0x01;
m_bob_out.set_ith_bit(m_bob_out_ix, out_bit);
m_bob_out_ix++;
}
void GarbledCircuit::generate_Alice_Output(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
generate_Gate(current_gate, current_key, garbling_bufr);
// gen moves through all of his output bits and saves the parity of
// the current zero keys, to be transmitted to Evl all together after
// protocol execution
if(m_alice_out.size()*8 <= m_alice_out_ix){
m_alice_out.resize((m_alice_out.size()+1)*2,0); // grow by doubling for less work
}
uint8_t out_bit = _mm_extract_epi8(current_key, 0) & 0x01;
// gen out contains the permutation bits of the output keys
m_alice_out.set_ith_bit(m_alice_out_ix, out_bit);
m_alice_out_ix++;
}
void GarbledCircuit::generate_Bob_Output(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
if (m_bob_out.size()*8 <= m_bob_out_ix)
{
// dynamically grow output array by doubling
m_bob_out.resize((m_bob_out.size()+1)*2, 0);
}
Bytes output_mask = get_Gen_Key(m_gen_inp_size + m_bob_out_ix,get_Input_Parity(m_gen_inp_size+m_bob_out_ix));
__m128i output_mask_key;
save_Key_to_128bit(output_mask, output_mask_key);
current_key = _mm_xor_si128(output_mask_key, current_key);
generate_Gate(current_gate,current_key, garbling_bufr);
uint8_t out_bit = (_mm_extract_epi8(current_key, 0) & 0x01);
// output_mask.get_ith_bit(0) ^ m_select_bits.get_ith_bit(m_gen_inp_size+m_bob_out_ix);
//get_Input_Parity(m_gen_inp_size+m_bob_out_ix);
m_bob_out.set_ith_bit(m_bob_out_ix, out_bit );
m_bob_out_ix++;
}
void GarbledCircuit::generate_Gate(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
__m128i key1 = *reinterpret_cast<__m128i*>(get_wire_key(m_st, current_gate->wire1));
__m128i key2 = *reinterpret_cast<__m128i*>(get_wire_key(m_st, current_gate->wire2));
total_gates++;
clock_gettime(CLOCK_REALTIME, &garble_start);
#ifdef FREE_XOR
if(current_gate->truth_table == 0x06){ // if XOR gate
xor_gates++;
clock_gettime(CLOCK_REALTIME, &xor_start);
xor_Gate(key1, key2, current_key);
clock_gettime(CLOCK_REALTIME, &xor_end);
xor_time += ( xor_end.tv_sec - xor_start.tv_sec )
+ ( xor_end.tv_nsec - xor_start.tv_nsec )
/ BILN;
} else if (current_gate->truth_table == 0x01 || current_gate->truth_table == 0x07) {
//fprintf(stderr,"%i\n",current_gate->truth_table);
half_gates++;
clock_gettime(CLOCK_REALTIME, &half_start);
if(current_gate->truth_table == 0x01){ // AND Gate
genHalfGatePair(current_key, key1, key2, m_garbling_bufr, 0, 0, 0);
send_half_gate(m_garbling_bufr);
}
else if(current_gate->truth_table == 0x07){ // OR Gate
genHalfGatePair(current_key, key1, key2, m_garbling_bufr, 1, 1, 1);
send_half_gate(m_garbling_bufr);
}
clock_gettime(CLOCK_REALTIME, &half_end);
hg_time += ( half_end.tv_sec - half_start.tv_sec )
+ ( half_end.tv_nsec - half_start.tv_nsec )
/ BILN;
} else {
#endif
//fprintf(stderr,"%i\n",current_gate->truth_table);
// here (most likely) we have a NOT gate or an XNOR gate
// the compiler's optimizer should do its best to remove them
// but since they can't be garbled with half gates, we garble with GRR
// NOT or XNOR gates, however, might be a bit cryptographically dangerous
// we also use this method for output gates
other_gates++;
clock_gettime(CLOCK_REALTIME, &og_start);
genStandardGate(current_key, key1, key2, garbling_bufr, current_gate->truth_table);
send_full_gate(garbling_bufr);
clock_gettime(CLOCK_REALTIME, &og_end);
og_time += ( og_end.tv_sec - og_start.tv_sec )
+ ( og_end.tv_nsec - og_start.tv_nsec )
/ BILN;
#ifdef FREE_XOR
}
#endif
clock_gettime(CLOCK_REALTIME, &garble_end);
garble_time += ( garble_end.tv_sec - garble_start.tv_sec )
+ ( garble_end.tv_nsec - garble_start.tv_nsec )
/ BILN;
}
void GarbledCircuit::evaluate_Gate(PCFGate* current_gate, __m128i ¤t_key, Bytes & garbling_bufr){
__m128i key1 = *reinterpret_cast<__m128i*>(get_wire_key(m_st, current_gate->wire1));
__m128i key2 = *reinterpret_cast<__m128i*>(get_wire_key(m_st, current_gate->wire2));
total_gates++;
clock_gettime(CLOCK_REALTIME, &garble_start);
#ifdef FREE_XOR
if (current_gate->truth_table == 0x06)
{
xor_gates++;
clock_gettime(CLOCK_REALTIME, &xor_start);
xor_Gate(key1, key2, current_key);
clock_gettime(CLOCK_REALTIME, &xor_end);
xor_time += ( xor_end.tv_sec - xor_start.tv_sec )
+ ( xor_end.tv_nsec - xor_start.tv_nsec )
/ BILN;
} else if(current_gate->truth_table == 0x01 || current_gate->truth_table == 0x07) {
half_gates++;
clock_gettime(CLOCK_REALTIME, &half_start);
if(current_gate->truth_table == 0x01){ // AND Gate
// fprintf(stdout,"AND GATE!\n");
read_half_gate(garbling_bufr);
//garbling_bufr = read_half_gate();
evlHalfGatePair(current_key, key1,key2, garbling_bufr);
}
else if(current_gate->truth_table == 0x07){ // OR gate
// fprintf(stdout,"OR GATE!\n");
//garbling_bufr = read_half_gate();
read_half_gate(garbling_bufr);
evlHalfGatePair(current_key, key1,key2, garbling_bufr);
}
clock_gettime(CLOCK_REALTIME, &half_end);
hg_time += ( half_end.tv_sec - half_start.tv_sec )
+ ( half_end.tv_nsec - half_start.tv_nsec )
/ BILN;
}else {
#endif
other_gates++;
clock_gettime(CLOCK_REALTIME, &og_start);
// here (most likely) we have a NOT gate or an XNOR gate
// the compiler's optimizer should do its best to remove them
// but since they can't be garbled with half gates, we garble with GRR
// we also use this for output gates
read_full_gate(garbling_bufr);
//garbling_bufr = read_full_gate();
evlStandardGate(current_key, key1, key2, garbling_bufr);
clock_gettime(CLOCK_REALTIME, &og_end);
og_time += ( og_end.tv_sec - og_start.tv_sec )
+ ( og_end.tv_nsec - og_start.tv_nsec )
/ BILN;
#ifdef FREE_XOR
}
#endif
// current_key will be available to the calling function
clock_gettime(CLOCK_REALTIME, &garble_end);
garble_time += ( garble_end.tv_sec - garble_start.tv_sec )
+ ( garble_end.tv_nsec - garble_start.tv_nsec )
/ BILN;
}
void GarbledCircuit::genStandardGate(__m128i& current_key, __m128i & key1, __m128i & key2, Bytes & out_bufr, uint8_t truth_table){
// X and Y are input, Z is output
__m128i X[2], Y[2], Z[2];
__m128i garble_ciphertext;
__m128i garble_ciphertext1, garble_ciphertext2, garble_ciphertext3, garble_ciphertext4;
uint8_t semantic_bit;
uint8_t semantic_bit1, semantic_bit2, semantic_bit3, semantic_bit4;
//double start = MPI_Wtime();
// load the (zero-key) inputs from the PCF state container
X[0] = key1;
Y[0] = key2;
// and XOR-complements
X[1] = _mm_xor_si128(X[0], m_R); // X[1] = X[0] ^ R
Y[1] = _mm_xor_si128(Y[0], m_R); // Y[1] = Y[0] ^ R
// and get the permutation bits (tells if each zero-key has a 1 on the end)
const uint8_t perm_x = _mm_extract_epi8(X[0],0) & 0x01;
const uint8_t perm_y = _mm_extract_epi8(Y[0],0) & 0x01;
const uint8_t de_garbled_ix = (perm_y << 1)|perm_x; // wire1 + 2*wire2
// the last information for garbling
uint32_t j1;
j1 = increment_index();
__m128i tweak;
tweak = _mm_set1_epi64x(j1);
// now run the key derivation function using the keys and the gate index
__m128i key1_1 = _mm_loadu_si128(X+perm_x);
__m128i key2_1 = _mm_loadu_si128(Y+perm_y);
__m128i key1_2 = _mm_loadu_si128(X+1-perm_x);;
__m128i key2_2 = _mm_loadu_si128(Y+perm_y);
__m128i key1_3 = _mm_loadu_si128(X+perm_x);
__m128i key2_3 = _mm_loadu_si128(Y+1-perm_y);
__m128i key1_4 = _mm_loadu_si128(X+1-perm_x);
__m128i key2_4 = _mm_loadu_si128(Y+1-perm_y);
H_Pi256(garble_ciphertext1, key1_1, key2_1, tweak, m_clear_mask, m_fixed_key);
H_Pi256(garble_ciphertext2, key1_2, key2_2, tweak, m_clear_mask, m_fixed_key);
H_Pi256(garble_ciphertext3, key1_3, key2_3, tweak, m_clear_mask, m_fixed_key);
H_Pi256(garble_ciphertext4, key1_4, key2_4, tweak, m_clear_mask, m_fixed_key);
semantic_bit1 = (truth_table >> (3-de_garbled_ix)) & 0x01;
semantic_bit2 = (truth_table>>(3-(0x01^de_garbled_ix)))&0x01;
semantic_bit3 = (truth_table>>(3-(0x02^de_garbled_ix)))&0x01;
semantic_bit4 = (truth_table>>(3-(0x03^de_garbled_ix)))&0x01;
_mm_store_si128(Z+semantic_bit1, garble_ciphertext1);
Z[1 - semantic_bit1] = _mm_xor_si128(Z[semantic_bit1], m_R);
current_key = _mm_loadu_si128(Z);
garble_ciphertext2 = _mm_xor_si128(garble_ciphertext2, Z[semantic_bit2]);
garble_ciphertext3 = _mm_xor_si128(garble_ciphertext3, Z[semantic_bit3]);
garble_ciphertext4 = _mm_xor_si128(garble_ciphertext4, Z[semantic_bit4]);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&out_bufr[0]),garble_ciphertext2);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&out_bufr[Env::key_size_in_bytes()]),garble_ciphertext3);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&out_bufr[2*Env::key_size_in_bytes()]),garble_ciphertext4);
// current_key holds our output key, and it will be available to our calling function
// the calling function will also be able to send the information in out_bufr
//benchmark_time += MPI_Wtime() - start;
}
void GarbledCircuit::evlStandardGate(__m128i& current_key, __m128i & key1, __m128i & key2, Bytes & in_bufr){
__m128i garble_key[2], aes_plaintext, garble_ciphertext;
Bytes tmp;
__m128i a;
Bytes::const_iterator it;
//double start = MPI_Wtime();
aes_plaintext = _mm_set1_epi64x(m_gate_index);
garble_key[0] = key1;
garble_key[1] = key2;
const uint8_t perm_x = _mm_extract_epi8(garble_key[0], 0) & 0x01;
const uint8_t perm_y = _mm_extract_epi8(garble_key[1], 0) & 0x01;
#ifndef AESNI
KDF256((uint8_t*)&aes_plaintext, (uint8_t*)&garble_ciphertext, (uint8_t*)garble_key);
garble_ciphertext = _mm_and_si128(garble_ciphertext, m_clear_mask);
#else
uint32_t j1;
j1 = increment_index();
__m128i tweak;
tweak = _mm_set1_epi64x(j1);
// __m128i key1_in = garble_key[0];
// __m128i key2_in = garble_key[1];
//H_Pi256(garble_ciphertext, key1_in, key2_in, tweak, m_clear_mask, m_fixed_key);
H_Pi256(garble_ciphertext, garble_key[0], garble_key[1], tweak, m_clear_mask, m_fixed_key);
#endif
uint8_t garbled_ix = (perm_y<<1)|perm_x;
#ifdef GRR
if (garbled_ix == 0) {
current_key = _mm_load_si128(&garble_ciphertext);
}
else
{
it = in_bufr.begin() + (garbled_ix-1)*Env::key_size_in_bytes();
tmp.assign(it, it+Env::key_size_in_bytes());
tmp.resize(16, 0);
a = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
current_key = _mm_xor_si128(garble_ciphertext, a);
}
#else
it = in_bufr.begin() + (garbled_ix)*Env::key_size_in_bytes();
tmp.assign(it, it+Env::key_size_in_bytes());
tmp.resize(16, 0);
current_key = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
current_key = _mm_xor_si128(current_key, garble_ciphertext);
#endif
// current key holds our output key, and it will be available to the calling function
//benchmark_time += MPI_Wtime() - start;
}
void GarbledCircuit::genHalfGatePair(__m128i& out_key, __m128i & key1, __m128i & key2, Bytes & out_bufr, byte a1, byte a2, byte a3){
// this function implements half-gate generation by
// Zahur, Rosulek, and Evans
assert(a1==0||a1==1);
assert(a2==0||a2==1);
assert(a3==0||a3==1);
//double start = MPI_Wtime();
const uint8_t perm_x = _mm_extract_epi8(key1,0) & 0x01;
const uint8_t perm_y = _mm_extract_epi8(key2,0) & 0x01;
__m128i Wa0, Wb0,Wa1,Wb1; // incoming wire keys
__m128i Wg, We; // half gate wire keys
// Tg and Te are the transmitted variables for the Generator and Evaluator, respectively
__m128i Tg, Te;
// Ha and Hb will contain the results of applying the KDF
__m128i Ha0, Ha1, Hb0, Hb1;
// __m128i tmp; // temporarily stores the output of H that will be used again
//Bytes tmp_bufr; // transfers keys to output buffer
uint32_t j1, j2;
j1 = increment_index();
j2 = increment_index();
__m128i j1_128, j2_128;
j1_128 = _mm_set1_epi64x(j1);
j2_128 = _mm_set1_epi64x(j2);
Wa0 = key1;
Wb0 = key2;
__m128i key1x = _mm_xor_si128(key1,m_R);
Wa1 = _mm_xor_si128(Wa0,m_R);
Wb1 = _mm_xor_si128(Wb0,m_R);
__m128i H_Wa0j1, H_Wa1j1, H_Wb0j2, H_Wb1j2;
H_Pi(H_Wa0j1, Wa0, j1_128, m_clear_mask,m_fixed_key);
H_Pi(H_Wa1j1, Wa1, j1_128, m_clear_mask,m_fixed_key);
H_Pi(H_Wb0j2, Wb0, j2_128, m_clear_mask,m_fixed_key);
H_Pi(H_Wb1j2, Wb1, j2_128, m_clear_mask,m_fixed_key);
// first half gate
Tg = _mm_xor_si128(H_Wa0j1, H_Wa1j1);
if(perm_y != a2){
Tg = _mm_xor_si128(Tg,m_R);
}
Wg = perm_x? H_Wa1j1 : H_Wa0j1;
if(((perm_x != a1) && (perm_y != a2)) != a3){
Wg = _mm_xor_si128(Wg, m_R);
}
// second half gate
We = perm_y ? H_Wb1j2 : H_Wb0j2;
Te = _mm_xor_si128(H_Wb0j2,H_Wb1j2);
Te = _mm_xor_si128(Te, a1? key1x :key1);
// add Tg,Te to output buffer
// std::fill(out_bufr.begin(),out_bufr.end(),0);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&out_bufr[0]),Tg);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&out_bufr[Env::key_size_in_bytes()]),Te);
// combine half gates:
out_key = _mm_xor_si128(Wg,We);
//benchmark_time += MPI_Wtime() - start;
}
void GarbledCircuit::evlHalfGatePair(__m128i ¤t_key, __m128i & key1, __m128i & key2, Bytes & in_bufr){
//assert(in_bufr.size() == 2*Env::key_size_in_bytes());
//double start = MPI_Wtime();
// get the select bits
byte sa,sb;
sa = _mm_extract_epi8(key1,0) & 0x01;
sb = _mm_extract_epi8(key2,0) & 0x01;
// get the counter values
uint32_t j1, j2;
j1 = increment_index();
j2 = increment_index();
__m128i j1_128, j2_128;
j1_128 = _mm_set1_epi64x(j1);
j2_128 = _mm_set1_epi64x(j2);
// fprintf(stdout,"Half Gate In Buffer: %s\n",in_bufr.to_hex().c_str());
Bytes tmp_bufr;
__m128i Tg, Te;
// TG is always sent first, and then TE
// where TG is the single row transmitted for the Generator's half-gate
// and TE is the single row transmitted for the Evaluator's half-gate
Tg = _mm_loadu_si128(reinterpret_cast<__m128i*>(&in_bufr[0]));
Te = _mm_loadu_si128(reinterpret_cast<__m128i*>(&in_bufr[0]+Env::key_size_in_bytes()));
Tg = _mm_and_si128(Tg,m_clear_mask);
Te = _mm_and_si128(Te,m_clear_mask);
__m128i Wa,Wb;
Wa = key1;
Wb = key2;
__m128i H_Waj1,H_Wbj2; // output of hashes
H_Pi(H_Waj1, Wa, j1_128, m_clear_mask, m_fixed_key);
H_Pi(H_Wbj2, Wb, j2_128, m_clear_mask, m_fixed_key);
__m128i Wg, We,tmp,tmpwe;
__m128i xorTeKey1;
Wg = H_Waj1;
if(sa){
Wg = _mm_xor_si128(H_Waj1,Tg);
}
We = H_Wbj2;
xorTeKey1 = _mm_xor_si128(Te, key1);
if(sb){
We = _mm_xor_si128(H_Wbj2,xorTeKey1);
}
current_key = _mm_xor_si128(Wg,We);
//benchmark_time += MPI_Wtime() - start;
}
void GarbledCircuit::clear_garbling_bufr(){
m_garbling_bufr.clear();
//std::fill(m_garbling_bufr.begin(),m_garbling_bufr.end(),0);
}
// this function computes the 2-uhf matrix given by matrix
// including output gates
// collaboratively with Gen
// Evl does not learn the parity of the outputs though
// either i need to do output gates differently or
// Eval needs that info from Gen
void GarbledCircuit::gen_next_hash_row(Bytes & row, Bytes & hash_bufr){
if(m_hash_out.size()*8 <= m_hash_row_idx){
m_hash_out.resize((m_hash_out.size()+1)*2,0);
}
// starter value for our row's key
__m128i row_key;
row_key = _mm_set_epi64x(0,0);
Bytes next_key;
__m128i next_key_128;
__m128i output_key;
for(int i = 0; i < m_gen_inputs->size()/2; i++){
// should be approximately same size as row*8
next_key = get_Gen_Key(i,get_Input_Parity(i));
//next_key = get_Gen_Input(i);
save_Key_to_128bit(next_key, next_key_128);
if(row.get_ith_bit(i)==1){
row_key = _mm_xor_si128(row_key, next_key_128);
}
}
hash_bufr.clear();
// we use 5 for output keys
genStandardGate(output_key, row_key, row_key, hash_bufr, 5);
// now get output bit
// we probably need to garble our output gate for this
if(_mm_extract_epi8(output_key,0)&0x01 == 1 ){
m_hash_out.set_ith_bit(m_hash_row_idx,1);
}
m_hash_row_idx++;
}
void GarbledCircuit::evl_next_hash_row(Bytes & row, Bytes & in_bufr){
if(m_hash_out.size()*8 <= m_hash_row_idx){
m_hash_out.resize((m_hash_out.size()+1)*2,0);
}
__m128i row_key;
row_key = _mm_set_epi64x(0,0);
Bytes next_key;
__m128i next_key_128;
//assert(m_gen_inputs->size()>=row.size()*8);
for(int i = 0; i < m_gen_inputs->size(); i++){
// should be approximately same size as row*8
next_key = get_Gen_Input(i);
save_Key_to_128bit(next_key, next_key_128);
if(row.get_ith_bit(i)==1){
row_key = _mm_xor_si128(row_key, next_key_128);
}
}
__m128i output_key;
evlStandardGate(output_key, row_key, row_key, in_bufr);
in_bufr.clear();
// now get output bit
// we probably need to garble our output gate for this
if(_mm_extract_epi8(output_key,0)&0x01 == 1 ){
m_hash_out.set_ith_bit(m_hash_row_idx,1);
}
m_hash_row_idx++;
}
void evaluate_K_Probe_Matrix(std::vector<Bytes> &matrix){
// here, Eval derives keys with the proper semantics
// to use as her inputs
}
void generate_K_Probe_Matrix(std::vector<Bytes> &matrix){
// here, Gen derives keys for Eval with the proper semantics
// that will be her "new" input keys
}
Bytes GarbledCircuit::get_alice_out(){
// fprintf(stdout,"benchmark time: %f\n",benchmark_time);
//fprintf(stdout,"benchmark time2: %f\n",btime2);
fprintf(stdout,"xor gates : %i \t xor time : %f\n",xor_gates,xor_time);
fprintf(stdout,"half gates : %i \t hgate time: %f\n",half_gates,hg_time);
fprintf(stdout,"other gates: %i \t other time: %f\n",other_gates,og_time);
fprintf(stdout,"total gates: %i \t total time: %f\n",total_gates,garble_time);
fprintf(stdout,"num copies : %i \t copy time : %f\n",num_copies, copy_time);
fprintf(stdout,"num buffers: %i \tbuffer time: %f\n",num_buffers, buffer_time);
fprintf(stdout,"num b cpy : %i \t b_cpy time: %f\n",num_b_cpy, b_cpy_time);
fprintf(stdout,"num comm : %i \t comm time: %f\n",num_comms, comm_time);
//fprintf(stdout,"num send : %i \t send time: %f\n",num_sends, send_time);
return m_alice_out;
}
Bytes GarbledCircuit::get_bob_out(){
// fprintf(stdout,"benchmark time: %f\n",benchmark_time);
fprintf(stdout,"xor gates : %i \t xor time : %f\n",xor_gates,xor_time);
fprintf(stdout,"half gates : %i \t hgate time: %f\n",half_gates,hg_time);
fprintf(stdout,"other gates: %i \t other time: %f\n",other_gates,og_time);
fprintf(stdout,"total gates: %i \t total time: %f\n",total_gates,garble_time);
fprintf(stdout,"num copies : %i \t copy time : %f\n",num_copies, copy_time);
fprintf(stdout,"num buffers: %i \tbuffer time: %f\n",num_buffers, buffer_time);
fprintf(stdout,"num b cpy : %i \t b_cpy time: %f\n",num_b_cpy, b_cpy_time);
fprintf(stdout,"num comm : %i \t comm time: %f\n",num_comms, comm_time);
//fprintf(stdout,"num send : %i \t send time: %f\n",num_sends, send_time);
return m_bob_out;
}
Bytes GarbledCircuit::get_hash_out(){
return m_hash_out;
}
void GarbledCircuit::trim_output_buffers(){
if(m_alice_out_ix>0)
m_alice_out.resize(m_alice_out_ix/8,0);
if(m_bob_out_ix>0)
m_bob_out.resize(m_bob_out_ix/8,0);
}
Bytes GarbledCircuit::get_Gen_Output_Label(uint32_t idx){
return m_gen_output_labels[idx];
}
void GarbledCircuit::send_half_gate(const Bytes &buf){
//clock_t start_t;
//start_t = clock();
// std::cout << "enqueue half gate " << std::endl << buf.to_hex() << std::endl;
num_comms++;
clock_gettime(CLOCK_REALTIME, &comm_start);
// Env::remote()->write_2_ciphertexts(buf);
enqueue_messages(buf,2);
//m_comm_time += (double) (clock() - start_t)/CLOCKS_PER_SEC;
clock_gettime(CLOCK_REALTIME, &comm_end);
comm_time += ( comm_end.tv_sec - comm_start.tv_sec )
+ ( comm_end.tv_nsec - comm_start.tv_nsec )
/ BILN;
}
void GarbledCircuit::send_full_gate(const Bytes &buf){
//clock_t start_t;
//start_t = clock();
//std::cout << "send full gate " << std::endl << buf.to_hex() << std::endl;
#ifdef GRR
num_comms++;
clock_gettime(CLOCK_REALTIME, &comm_start);
enqueue_messages(buf,3);
//Env::remote()->write_3_ciphertexts(buf);
clock_gettime(CLOCK_REALTIME, &comm_end);
comm_time += ( comm_end.tv_sec - comm_start.tv_sec )
+ ( comm_end.tv_nsec - comm_start.tv_nsec )
/ BILN;
#else
enqueue_messages(buf,4);
//Env::remote()->write_4_ciphertexts(buf);
#endif
// std::cout << "enqueue full gate " << std::endl << buf.to_hex() << std::endl;
// m_comm_time += (double) (clock() - start_t)/CLOCKS_PER_SEC;
}
void GarbledCircuit::read_half_gate(Bytes & buf){
//clock_t start_t;
//start_t = clock();
num_comms++;
clock_gettime(CLOCK_REALTIME, &comm_start);
//Bytes ret = Env::remote()->read_2_ciphertexts();
retrieve_ciphertexts(buf,2);
clock_gettime(CLOCK_REALTIME, &comm_end);
comm_time += ( comm_end.tv_sec - comm_start.tv_sec )
+ ( comm_end.tv_nsec - comm_start.tv_nsec )
/ BILN;
// std::cout << "read half gate " << std::endl << ret.to_hex() << std::endl;
// return ret;
//m_comm_time += (double) (clock() - start_t)/CLOCKS_PER_SEC;
}
void GarbledCircuit::read_full_gate(Bytes & buf){
//clock_t start_t;
// start_t = clock();
#ifdef GRR
num_comms++;
clock_gettime(CLOCK_REALTIME, &comm_start);
retrieve_ciphertexts(buf,3);
//Bytes ret = retrieve_ciphertexts(3);
//return Env::remote()->read_3_ciphertexts();
clock_gettime(CLOCK_REALTIME, &comm_end);
comm_time += ( comm_end.tv_sec - comm_start.tv_sec )
+ ( comm_end.tv_nsec - comm_start.tv_nsec )
/ BILN;
#else
retrieve_ciphertexts(buf,4);
//Bytes ret = retrieve_ciphertexts(4);
//return Env::remote()->read_4_ciphertexts();
#endif
//std::cout << "read full gate " << std::endl << ret.to_hex() << std::endl;
//return ret;
// m_comm_time += (double) (clock() - start_t)/CLOCKS_PER_SEC;
}
void GarbledCircuit::enqueue_messages(const Bytes & source, uint32_t num){
if(num + m_messages_waiting < m_message_limit){
add_messages_to_queue(source,num);
} else if(num + m_messages_waiting == m_message_limit) {
add_messages_to_queue(source,num);
send_buffer();
} else {
int send_early = m_message_limit - m_messages_waiting;
add_messages_to_queue(source, send_early);
send_buffer();
m_message_queue.insert(m_message_queue.begin(),
source.begin() + send_early*Env::key_size_in_bytes(),
source.begin() + send_early*Env::key_size_in_bytes()
+ (num - send_early)*Env::key_size_in_bytes());
m_messages_waiting = (num - send_early);
}
}
void GarbledCircuit::add_messages_to_queue(const Bytes & src, uint32_t num){
m_message_queue.insert(m_message_queue.begin()+m_messages_waiting*Env::key_size_in_bytes(),src.begin(),src.begin()+num*Env::key_size_in_bytes());
m_messages_waiting += num;
}
void GarbledCircuit::send_buffer(){
// this is also like a flush
//std::cout << "buffer send " << std::endl << m_message_queue.to_hex() << std::endl;
Env::remote()->write_n_ciphertexts(m_message_queue, m_message_limit);
m_messages_waiting = 0;
// std::fill(m_message_queue.begin(),m_message_queue.end(),0);
//std::cout << "sent" << std::endl;
}
void GarbledCircuit::retrieve_ciphertexts(Bytes & buf, uint32_t num_ctexts){
//Bytes ret;
//m_ciphertext_buff.clear();
if( num_ctexts < m_messages_waiting ){
// get num messages from the queue
// advance the queue index / reduce the number waiting
buf.insert(buf.begin(),
m_message_queue.begin() + m_queue_index*Env::key_size_in_bytes(),
m_message_queue.begin() + m_queue_index*Env::key_size_in_bytes() + num_ctexts*Env::key_size_in_bytes());
m_queue_index += num_ctexts;
m_messages_waiting -= num_ctexts;
//assert(m_queue_index + m_messages_waiting == m_message_limit);
// return m_ciphertext_buff;
} else if (num_ctexts == m_messages_waiting ){
// get the last messages
// reset the queue index/ reset the number waiting
// retrieve the next set of messages
assert(num_ctexts + m_queue_index == m_message_limit);
buf.insert(buf.begin(),
m_message_queue.begin() + m_queue_index*Env::key_size_in_bytes(),
m_message_queue.begin() + m_queue_index*Env::key_size_in_bytes() + num_ctexts*Env::key_size_in_bytes());
// fprintf(stdout,"case 2\n");
retrieve_buffer();
// assert(m_queue_index + m_messages_waiting == m_message_limit);
// return m_ciphertext_buff;
} else{ // num_ctexts > m_messages_waiting
// get the last ones left
// reset the queue index/ reset the number waiting
// get the remaining ones we need and update appropriately
uint32_t get_early = m_messages_waiting;
uint32_t get_later = num_ctexts - get_early;
if(get_early > 0){ // should always be true for this case
buf.insert(buf.begin(),
m_message_queue.begin() + m_queue_index*Env::key_size_in_bytes(),
m_message_queue.begin() + m_queue_index*Env::key_size_in_bytes() + get_early*Env::key_size_in_bytes());
// std::cout << "partial ciphertext" << m_ciphertext_buff.to_hex() << std::endl;
// fprintf(stdout,"partial copy\n");
}
// fprintf(stdout,"case 3\n");
retrieve_buffer();
buf.insert(buf.begin() + get_early*Env::key_size_in_bytes(),
m_message_queue.begin(),
m_message_queue.begin() + get_later*Env::key_size_in_bytes());
m_messages_waiting -= get_later;
m_queue_index += get_later;
//assert(m_queue_index + m_messages_waiting == m_message_limit);
// return m_ciphertext_buff;
}
}
void GarbledCircuit::retrieve_buffer(){
// resets the queue index/ the number waiting
// retrieves the next batch of messages from the wire
// std::fill(m_message_queue.begin(),m_message_queue.end(),0);
m_queue_index = 0;
m_messages_waiting = m_message_limit;
Env::remote()->read_n_ciphertexts(m_message_queue,m_message_limit);
// std::cout << "buffer retrieve " << std::endl << m_message_queue.to_hex() << std::endl;
}
#endif
| 29.003094 | 257 | 0.693081 | [
"object",
"vector"
] |
7377609c63cf88654501c8366c31edd03bb50ced | 1,755 | cpp | C++ | src/2021/day07.cpp | BruJu/AdventOfCode | a9161649882429bc1f995424544ce4cdafb69caa | [
"WTFPL",
"MIT"
] | 1 | 2020-12-11T13:37:06.000Z | 2020-12-11T13:37:06.000Z | src/2021/day07.cpp | BruJu/AdventOfCode2020 | a9161649882429bc1f995424544ce4cdafb69caa | [
"WTFPL",
"MIT"
] | null | null | null | src/2021/day07.cpp | BruJu/AdventOfCode2020 | a9161649882429bc1f995424544ce4cdafb69caa | [
"WTFPL",
"MIT"
] | null | null | null | #include "../advent_of_code.hpp"
#include <algorithm>
#include <optional>
#include <numeric>
// https://adventofcode.com/2021/day/7
// At this point, string_to_ints should come with the framework
std::vector<int> string_to_ints(const std::string & s, char separator);
constexpr static long long int compute_for_b(long long int value) {
long long int sum = 0;
while (value != 0) {
sum += value;
--value;
}
return sum;
}
Output day_2021_07(const std::vector<std::string> & lines, const DayExtraInfo &) {
auto crabs = string_to_ints(lines[0], ',');
// std::sort(crabs.begin(), crabs.end()); // Not sure if sorting is efficient or not
std::optional<long long int> part_a = std::nullopt;
std::optional<long long int> part_b = std::nullopt;
const auto double_it = std::minmax_element(crabs.begin(), crabs.end());
const auto min = *(double_it.first);
const auto max = *(double_it.second);
// Prepare cached values for part B
// This decrease the runtime from 482ms to 3ms
std::vector<long long int> cache_for_b(max - min + 1);
for (int i = 0; i <= (max - min); ++i) {
cache_for_b[i] = compute_for_b(i);
}
// Ok let's go. As C++ is a fast language, and the input is
// very small we can just bruteforce this problem.
for (auto i = min; i <= max; ++i) {
long long int local_answer = 0;
long long int local_answer_b = 0;
for (const auto crab : crabs) {
auto diff = crab - i;
if (diff < 0) diff = -diff;
local_answer += diff;
local_answer_b += cache_for_b[diff];
}
part_a = part_a ? std::min(*part_a, local_answer) : local_answer;
part_b = part_b ? std::min(*part_b, local_answer_b) : local_answer_b;
}
return Output(part_a.value(), part_b.value());
}
| 30.258621 | 86 | 0.655271 | [
"vector"
] |
7379e9ad451539135a708c6df06693346256cf2b | 371 | cpp | C++ | Traffic Lights (0124).cpp | michaelarakel/acmp-solutions | 56b853805854d0f0c0131c59c7a48e207c35b15f | [
"Unlicense"
] | 1 | 2021-09-22T12:14:59.000Z | 2021-09-22T12:14:59.000Z | Traffic Lights (0124).cpp | michaelarakel/acmp-solutions | 56b853805854d0f0c0131c59c7a48e207c35b15f | [
"Unlicense"
] | null | null | null | Traffic Lights (0124).cpp | michaelarakel/acmp-solutions | 56b853805854d0f0c0131c59c7a48e207c35b15f | [
"Unlicense"
] | null | null | null | #include <fstream>
#include <vector>
using namespace std;
int main ()
{
ifstream cin ("INPUT.TXT");
ofstream cout ("OUTPUT.TXT");
int n, m;
cin >> n >> m;
vector <int> v(n);
for (int i = 0; i < m; ++i)
{
int node1, node2;
cin >> node1 >> node2;
++v[node1 - 1];
++v[node2 - 1];
}
for (int i = 0; i < n; ++i)
cout << v[i] << " ";
} | 16.863636 | 31 | 0.485175 | [
"vector"
] |
737a76b32286446b0dcd9c5eb9877dcb1b71b432 | 1,003 | cpp | C++ | problems/leet/318-maximum-product-of-word-lengths/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/leet/318-maximum-product-of-word-lengths/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/leet/318-maximum-product-of-word-lengths/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// *****
struct type_t {
int mask = 0, size = 0;
};
bool cmp(const type_t &lhs, const type_t &rhs) {
return lhs.size > rhs.size;
}
class Solution {
public:
int maxProduct(vector<string> &words) {
int W = words.size();
if (W == 0)
return 0;
vector<type_t> masks(W);
int best = 0;
for (int i = 0; i < W; ++i) {
int mask = 0;
for (char c : words[i]) {
mask |= 1 << (c - 'a');
}
masks[i].mask = mask;
masks[i].size = words[i].size();
}
sort(masks.begin(), masks.end(), cmp);
for (int i = 0; i + 1 < W; ++i) {
if (masks[i].size * masks[i].size <= best)
break;
for (int j = i + 1; j < W; ++j) {
if (masks[i].size * masks[j].size <= best)
break;
if ((masks[i].mask & masks[j].mask) == 0) {
best = masks[i].size * masks[j].size;
}
}
}
return best;
}
};
// *****
int main() {
return 0;
}
| 17 | 51 | 0.4666 | [
"vector"
] |
7384d3123c94c40af31f37dc2d4e4c8f3d6b26b1 | 1,150 | hpp | C++ | FlicsFacts/Model/sortedmovieresponsesmodel.hpp | pgulotta/FlicsFacts | 02eee54c96c84aa54c3d1a2f2d831e36f6a9aa0f | [
"MIT"
] | null | null | null | FlicsFacts/Model/sortedmovieresponsesmodel.hpp | pgulotta/FlicsFacts | 02eee54c96c84aa54c3d1a2f2d831e36f6a9aa0f | [
"MIT"
] | null | null | null | FlicsFacts/Model/sortedmovieresponsesmodel.hpp | pgulotta/FlicsFacts | 02eee54c96c84aa54c3d1a2f2d831e36f6a9aa0f | [
"MIT"
] | null | null | null | #pragma once
#include "../FlicsFacts/fam/qqmlobjectlistmodel.hpp"
#include "../FlicsFacts/Model/movieresponse.hpp"
#include <QSortFilterProxyModel>
class SortedMovieResponsesModel final : public QSortFilterProxyModel
{
Q_OBJECT
public:
SortedMovieResponsesModel(QQmlObjectListModel<MovieResponse>* movieResponses, QObject *parent ) : QSortFilterProxyModel(parent) {
// qDebug() << " SortedMovieResponsesModel() called";
setDynamicSortFilter(false);
setSourceModel(movieResponses);
}
// virtual ~SortedMovieResponsesModel() {
// qDebug() << "~SortedMovieResponsesModel() called";
// }
void sortlByTitle()
{
sort(0, Qt::AscendingOrder);
}
protected:
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override
{
MovieResponse * leftMovieResponse = qobject_cast< MovieResponse*>(qvariant_cast<QObject *>( left.data(Qt::UserRole)));
MovieResponse * rightMovieResponse = qobject_cast< MovieResponse*>(qvariant_cast<QObject *>( right.data(Qt::UserRole)));
return leftMovieResponse->title() < rightMovieResponse->title();
}
};
| 31.944444 | 135 | 0.708696 | [
"model"
] |
738547cf03ab700e65883742c251b987ef5c56c6 | 4,915 | hpp | C++ | tools/i2c/i2c.hpp | openbmc/phosphor-power | b85b9dded072889faf937e29af32b2600dcc8d64 | [
"Apache-2.0"
] | 7 | 2019-10-04T01:19:49.000Z | 2021-06-02T23:11:19.000Z | tools/i2c/i2c.hpp | openbmc/phosphor-power | b85b9dded072889faf937e29af32b2600dcc8d64 | [
"Apache-2.0"
] | 9 | 2019-10-23T14:22:03.000Z | 2022-03-22T20:39:05.000Z | tools/i2c/i2c.hpp | openbmc/phosphor-power | b85b9dded072889faf937e29af32b2600dcc8d64 | [
"Apache-2.0"
] | 11 | 2019-10-04T01:20:01.000Z | 2022-03-03T06:08:16.000Z | #pragma once
#include "i2c_interface.hpp"
namespace i2c
{
class I2CDevice : public I2CInterface
{
private:
I2CDevice() = delete;
/** @brief Constructor
*
* Construct I2CDevice object from the bus id and device address
*
* Automatically opens the I2CDevice if initialState is OPEN.
*
* @param[in] busId - The i2c bus ID
* @param[in] devAddr - The device address of the I2C device
* @param[in] initialState - Initial state of the I2CDevice object
*/
explicit I2CDevice(uint8_t busId, uint8_t devAddr,
InitialState initialState = InitialState::OPEN) :
busId(busId),
devAddr(devAddr)
{
busStr = "/dev/i2c-" + std::to_string(busId);
if (initialState == InitialState::OPEN)
{
open();
}
}
/** @brief Invalid file descriptor */
static constexpr int INVALID_FD = -1;
/** @brief Empty adapter functionality value with no bit flags set */
static constexpr unsigned long NO_FUNCS = 0;
/** @brief The I2C bus ID */
uint8_t busId;
/** @brief The i2c device address in the bus */
uint8_t devAddr;
/** @brief The file descriptor of the opened i2c device */
int fd = INVALID_FD;
/** @brief The i2c bus path in /dev */
std::string busStr;
/** @brief Cached I2C adapter functionality value */
unsigned long cachedFuncs = NO_FUNCS;
/** @brief Check that device interface is open
*
* @throw I2CException if device is not open
*/
void checkIsOpen() const
{
if (!isOpen())
{
throw I2CException("Device not open", busStr, devAddr);
}
}
/** @brief Close device without throwing an exception if an error occurs */
void closeWithoutException() noexcept
{
try
{
close();
}
catch (...)
{}
}
/** @brief Get I2C adapter functionality
*
* Caches the adapter functionality value since it shouldn't change after
* opening the device.
*
* @throw I2CException on error
* @return Adapter functionality value
*/
unsigned long getFuncs();
/** @brief Check i2c adapter read functionality
*
* Check if the i2c adapter has the functionality specified by the SMBus
* transaction type
*
* @param[in] type - The SMBus transaction type defined in linux/i2c.h
*
* @throw I2CException if the function is not supported
*/
void checkReadFuncs(int type);
/** @brief Check i2c adapter write functionality
*
* Check if the i2c adapter has the functionality specified by the SMBus
* transaction type
*
* @param[in] type - The SMBus transaction type defined in linux/i2c.h
*
* @throw I2CException if the function is not supported
*/
void checkWriteFuncs(int type);
public:
/** @copydoc I2CInterface::~I2CInterface() */
~I2CDevice()
{
if (isOpen())
{
// Note: destructors must not throw exceptions
closeWithoutException();
}
}
/** @copydoc I2CInterface::open() */
void open();
/** @copydoc I2CInterface::isOpen() */
bool isOpen() const
{
return (fd != INVALID_FD);
}
/** @copydoc I2CInterface::close() */
void close();
/** @copydoc I2CInterface::read(uint8_t&) */
void read(uint8_t& data) override;
/** @copydoc I2CInterface::read(uint8_t,uint8_t&) */
void read(uint8_t addr, uint8_t& data) override;
/** @copydoc I2CInterface::read(uint8_t,uint16_t&) */
void read(uint8_t addr, uint16_t& data) override;
/** @copydoc I2CInterface::read(uint8_t,uint8_t&,uint8_t*,Mode) */
void read(uint8_t addr, uint8_t& size, uint8_t* data,
Mode mode = Mode::SMBUS) override;
/** @copydoc I2CInterface::write(uint8_t) */
void write(uint8_t data) override;
/** @copydoc I2CInterface::write(uint8_t,uint8_t) */
void write(uint8_t addr, uint8_t data) override;
/** @copydoc I2CInterface::write(uint8_t,uint16_t) */
void write(uint8_t addr, uint16_t data) override;
/** @copydoc I2CInterface::write(uint8_t,uint8_t,const uint8_t*,Mode) */
void write(uint8_t addr, uint8_t size, const uint8_t* data,
Mode mode = Mode::SMBUS) override;
/** @brief Create an I2CInterface instance
*
* Automatically opens the I2CInterface if initialState is OPEN.
*
* @param[in] busId - The i2c bus ID
* @param[in] devAddr - The device address of the i2c
* @param[in] initialState - Initial state of the I2CInterface object
*
* @return The unique_ptr holding the I2CInterface
*/
static std::unique_ptr<I2CInterface>
create(uint8_t busId, uint8_t devAddr,
InitialState initialState = InitialState::OPEN);
};
} // namespace i2c
| 27.926136 | 79 | 0.616684 | [
"object"
] |
738553f5f8cb5362b9e39f1c9524733d87527bb5 | 7,308 | hpp | C++ | src/modules/convex/algo/igd.hpp | pandeyh/incubator-madlib | c69515081d26b63089677fcccccd3393a0dc59dd | [
"Apache-2.0"
] | 1 | 2019-02-01T17:58:05.000Z | 2019-02-01T17:58:05.000Z | src/modules/convex/algo/igd.hpp | Acidburn0zzz/madlib | 59c7afdbcb2b561cd43d6d57bed03d0bc0fa122e | [
"Apache-2.0"
] | 1 | 2018-09-06T05:50:17.000Z | 2018-09-06T05:50:17.000Z | src/modules/convex/algo/igd.hpp | Acidburn0zzz/madlib | 59c7afdbcb2b561cd43d6d57bed03d0bc0fa122e | [
"Apache-2.0"
] | 1 | 2019-09-03T20:50:13.000Z | 2019-09-03T20:50:13.000Z | /* ----------------------------------------------------------------------- *//**
*
* @file igd.hpp
*
* Generic implementaion of incremental gradient descent, in the fashion of
* user-definied aggregates. They should be called by actually database
* functions, after arguments are properly parsed.
*
*//* ----------------------------------------------------------------------- */
#include <dbconnector/dbconnector.hpp>
#ifndef MADLIB_MODULES_CONVEX_ALGO_IGD_HPP_
#define MADLIB_MODULES_CONVEX_ALGO_IGD_HPP_
namespace madlib {
namespace modules {
namespace convex {
// use Eigen
using namespace madlib::dbal::eigen_integration;
// The reason for using ConstState instead of const State to reduce the
// template type list: flexibility to high-level for mutability control
// More: cast<ConstState>(MutableState) may not always work
template <class State, class ConstState, class Task>
class IGD {
public:
typedef State state_type;
typedef ConstState const_state_type;
typedef typename Task::tuple_type tuple_type;
typedef typename Task::model_type model_type;
static void transition(state_type &state, const tuple_type &tuple);
static void merge(state_type &state, const_state_type &otherState);
static void transitionInMiniBatch(state_type &state, const tuple_type &tuple);
static void mergeInPlace(state_type &state, const_state_type &otherState);
static void final(state_type &state);
};
template <class State, class ConstState, class Task>
void
IGD<State, ConstState, Task>::transition(state_type &state,
const tuple_type &tuple) {
// The reason for update model inside a Task:: function instead of
// returning the gradient and do it here: the gradient is a sparse
// representation of the model (which is dense), returning the gradient
// forces the algo to be aware of one more template type
// -- Task::sparse_model_type, which we do not explicit define
// apply to the model directly
Task::gradientInPlace(
state.algo.incrModel,
tuple.indVar,
tuple.depVar,
state.task.stepsize * tuple.weight);
}
template <class State, class ConstState, class Task>
void
IGD<State, ConstState, Task>::merge(state_type &state,
const_state_type &otherState) {
// Having zero checking here to reduce dependency to the caller.
// This can be removed if it affects performance in the future,
// with the expectation that callers should do the zero checking.
if (state.algo.numRows == 0) {
state.algo.incrModel = otherState.algo.incrModel;
return;
} else if (otherState.algo.numRows == 0) {
return;
}
// The reason of this weird algorithm instead of an intuitive one
// -- (w1 * m1 + w2 * m2) / (w1 + w2): we have only one mutable state,
// therefore, (m1 * w1 / w2 + m2) * w2 / (w1 + w2).
// Order: 111111111 22222 3333333333333333
// model averaging, weighted by rows seen
double totalNumRows = static_cast<double>(state.algo.numRows + otherState.algo.numRows);
state.algo.incrModel *= static_cast<double>(state.algo.numRows) /
static_cast<double>(otherState.algo.numRows);
state.algo.incrModel += otherState.algo.incrModel;
state.algo.incrModel *= static_cast<double>(otherState.algo.numRows) /
static_cast<double>(totalNumRows);
}
/**
* @brief Update the transition state in mini-batches
*
* Note: We assume that
* 1. Task defines a model_eigen_type
* 2. A batch of tuple.indVar is a Matrix
* 3. A batch of tuple.depVar is a ColumnVector
* 4. Task defines a getLossAndUpdateModel method
*
*/
template <class State, class ConstState, class Task>
void
IGD<State, ConstState, Task>::transitionInMiniBatch(
state_type &state,
const tuple_type &tuple) {
madlib_assert(tuple.indVar.rows() == tuple.depVar.rows(),
std::runtime_error("Invalid data. Independent and dependent "
"batches don't have same number of rows."));
uint16_t batch_size = state.batchSize;
uint16_t n_epochs = state.nEpochs;
// n_rows/n_ind_cols are the rows/cols in a transition tuple.
Index n_rows = tuple.indVar.rows();
size_t n_batches = n_rows < batch_size ? 1 :
size_t(n_rows / batch_size) + size_t(n_rows % batch_size > 0);
double max_loss = 0.0;
for (int curr_epoch=0; curr_epoch < n_epochs; curr_epoch++) {
double loss = 0.0;
/*
Randomizing the input data before every iteration is good for
minibatch gradient descent convergence. Since we don't do that,
we are randomizing the order in which every batch is visited in
a buffer. Note that this still does not randomize rows within
a batch.
*/
std::vector<size_t> random_curr_batch(n_batches, 0);
for(size_t i=0; i < n_batches; i++) {
random_curr_batch[i] = i;
}
std::random_shuffle(&random_curr_batch[0], &random_curr_batch[n_batches]);
for (size_t i = 0; i < n_batches; i++) {
size_t curr_batch = random_curr_batch[i];
Index curr_batch_row_index = static_cast<Index>(curr_batch * batch_size);
Matrix X_batch;
Matrix Y_batch;
if (curr_batch == n_batches-1) {
// last batch
X_batch = tuple.indVar.bottomRows(n_rows - curr_batch_row_index);
Y_batch = tuple.depVar.bottomRows(n_rows - curr_batch_row_index);
} else {
X_batch = tuple.indVar.block(curr_batch_row_index, 0,
batch_size, tuple.indVar.cols());
Y_batch = tuple.depVar.block(curr_batch_row_index, 0,
batch_size, tuple.depVar.cols());
}
loss += Task::getLossAndUpdateModel(
state.model, X_batch, Y_batch, state.stepsize);
}
if (max_loss < loss) max_loss = loss;
}
// Be pessimistic and report the maximum loss
state.loss += max_loss;
return;
}
template <class State, class ConstState, class Task>
void
IGD<State, ConstState, Task>::mergeInPlace(state_type &state,
const_state_type &otherState) {
// avoid division by zero
if (state.numRows == 0) {
state.model = otherState.model;
return;
} else if (otherState.numRows == 0) {
return;
}
// model averaging, weighted by rows seen
double leftRows = static_cast<double>(state.numRows + state.numRows);
double rightRows = static_cast<double>(otherState.numRows + otherState.numRows);
double totalNumRows = leftRows + rightRows;
state.model *= leftRows / rightRows;
state.model += otherState.model;
state.model *= rightRows / totalNumRows;
}
template <class State, class ConstState, class Task>
void
IGD<State, ConstState, Task>::final(state_type &state) {
// The reason that we have to keep the task.model untouched in transition
// funtion: loss computation needs the model from last iteration cleanly
state.task.model = state.algo.incrModel;
}
} // namespace convex
} // namespace modules
} // namespace madlib
#endif
| 36.723618 | 92 | 0.647373 | [
"vector",
"model"
] |
7386c59eaa3fca48370024d591fe63135ae80096 | 5,839 | cc | C++ | src/compile_charsmap_main.cc | marian-nmt/sentencepiece | c307b874deb5ea896db8f93506e173353e66d4d3 | [
"Apache-2.0"
] | null | null | null | src/compile_charsmap_main.cc | marian-nmt/sentencepiece | c307b874deb5ea896db8f93506e173353e66d4d3 | [
"Apache-2.0"
] | 5 | 2018-11-26T16:42:10.000Z | 2021-08-02T10:51:04.000Z | src/compile_charsmap_main.cc | marian-nmt/sentencepiece | c307b874deb5ea896db8f93506e173353e66d4d3 | [
"Apache-2.0"
] | 8 | 2020-09-03T10:46:11.000Z | 2021-05-21T07:36:18.000Z | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#include <functional>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "builder.h"
#include "filesystem.h"
#include "init.h"
#include "sentencepiece_processor.h"
#include "third_party/absl/flags/flag.h"
#include "third_party/absl/strings/string_view.h"
using sentencepiece::normalizer::Builder;
ABSL_FLAG(bool, output_precompiled_header, false,
"make normalization_rule.h file");
namespace sentencepiece {
namespace {
std::string ToHexUInt64Array(
const std::vector<std::pair<std::string, std::string>> &data,
std::vector<size_t> *offset) {
std::stringstream os;
os.setf(std::ios_base::hex, std::ios_base::basefield);
os.setf(std::ios_base::uppercase);
os.setf(std::ios_base::right);
os.fill('0');
os.unsetf(std::ios_base::showbase);
size_t num = 0;
for (const auto &p : data) {
const char *begin = p.second.data();
const char *end = p.second.data() + p.second.size();
offset->push_back(num);
while (begin < end) {
unsigned long long int n = 0;
unsigned char *buf = reinterpret_cast<unsigned char *>(&n);
const size_t size = std::min<size_t>(end - begin, sizeof(n));
for (size_t i = 0; i < size; ++i) {
buf[i] = static_cast<unsigned char>(begin[i]);
}
begin += sizeof(n);
os << "0x" << std::setw(2 * sizeof(n)) << n << ", ";
if (++num % 8 == 0) {
os << "\n";
}
}
}
return os.str();
}
std::string ToHexData(absl::string_view data) {
const char *begin = data.data();
const char *end = data.data() + data.size();
constexpr char kHex[] = "0123456789ABCDEF";
constexpr size_t kNumOfBytesOnOneLine = 20;
size_t output_count = 0;
std::stringstream os;
while (begin < end) {
const size_t bucket_size =
std::min<size_t>(end - begin, kNumOfBytesOnOneLine -
output_count % kNumOfBytesOnOneLine);
if (output_count % kNumOfBytesOnOneLine == 0 && bucket_size > 0) {
os << "\"";
}
for (size_t i = 0; i < bucket_size; ++i) {
os << "\\x" << kHex[(*begin & 0xF0) >> 4] << kHex[(*begin & 0x0F) >> 0];
++begin;
}
output_count += bucket_size;
if (output_count % kNumOfBytesOnOneLine == 0 && bucket_size > 0 &&
begin < end) {
os << "\"\n";
}
}
os << "\"\n";
return os.str();
}
std::string MakeHeader(
const std::vector<std::pair<std::string, std::string>> &data) {
constexpr char kHeader[] =
R"(#ifndef NORMALIZATION_RULE_H_
#define NORMALIZATION_RULE_H_
#include <cstdio>
namespace sentencepiece {
namespace {
struct BinaryBlob {
const char *name;
size_t size;
const char *data;
};
)";
constexpr char kFooter[] = R"(
} // namespace
} // namespace sentencepiece
#endif // NORMALIZATION_RULE_H_
)";
std::stringstream os;
os << kHeader;
os << "#if defined(_WIN32) && !defined(__CYGWIN__)\n";
os << "constexpr unsigned long long int kNormalizationRules_blob_uint64[] = "
"{\n";
std::vector<size_t> offset;
os << ToHexUInt64Array(data, &offset);
CHECK_EQ(offset.size(), data.size());
os << "};\n\n";
os << "const BinaryBlob kNormalizationRules_blob[] = {\n";
for (size_t i = 0; i < data.size(); ++i) {
os << "{ \"" << data[i].first << "\", " << data[i].second.size() << ", ";
os << "reinterpret_cast<const char *>(kNormalizationRules_blob_uint64 + "
<< offset[i] << ") },\n";
}
os << "};\n";
os << "#else\n";
os << "constexpr BinaryBlob kNormalizationRules_blob[] = {\n";
for (size_t i = 0; i < data.size(); ++i) {
os << "{ \"" << data[i].first << "\", " << data[i].second.size() << ", ";
os << ToHexData(data[i].second) << "},\n";
}
os << "};\n";
os << "#endif\n";
os << "constexpr size_t kNormalizationRules_size = " << data.size() << ";\n";
os << kFooter;
return os.str();
}
} // namespace
} // namespace sentencepiece
int main(int argc, char **argv) {
sentencepiece::ParseCommandLineFlags(argv[0], &argc, &argv, true);
const std::vector<std::pair<
std::string,
std::function<sentencepiece::util::Status(Builder::CharsMap *)>>>
kRuleList = {{"nfkc", Builder::BuildNFKCMap},
{"nmt_nfkc", Builder::BuildNmtNFKCMap},
{"nfkc_cf", Builder::BuildNFKC_CFMap},
{"nmt_nfkc_cf", Builder::BuildNmtNFKC_CFMap},
{"case_uncaser", Builder::BuildUncaserMap},
{"case_recaser", Builder::BuildRecaserMap}};
std::vector<std::pair<std::string, std::string>> data;
for (const auto &p : kRuleList) {
Builder::CharsMap normalized_map;
CHECK_OK(p.second(&normalized_map));
// Write Header.
std::string index;
CHECK_OK(Builder::CompileCharsMap(normalized_map, &index));
data.emplace_back(p.first, index);
// Write TSV file.
CHECK_OK(Builder::SaveCharsMap(p.first + ".tsv", normalized_map));
}
if (absl::GetFlag(FLAGS_output_precompiled_header)) {
constexpr char kPrecompiledHeaderFileName[] = "normalization_rule.h";
auto output =
sentencepiece::filesystem::NewWritableFile(kPrecompiledHeaderFileName);
CHECK_OK(output->status());
output->Write(sentencepiece::MakeHeader(data));
}
return 0;
}
| 29.94359 | 79 | 0.622024 | [
"vector"
] |
73880fa4c3ce1ea3b616c34c7e5fdb9a34db5a46 | 6,773 | cc | C++ | extras/mgps-70mai/70mai.cc | mzdun/dashcam-gps | 7611a08792cac98c4fd1260111e3fc0e632e982b | [
"MIT"
] | 6 | 2020-02-14T00:46:16.000Z | 2021-04-07T09:29:06.000Z | extras/mgps-70mai/70mai.cc | mzdun/dashcam-gps | 7611a08792cac98c4fd1260111e3fc0e632e982b | [
"MIT"
] | 1 | 2020-06-09T10:55:43.000Z | 2020-06-18T11:39:59.000Z | extras/mgps-70mai/70mai.cc | mzdun/dashcam-gps | 7611a08792cac98c4fd1260111e3fc0e632e982b | [
"MIT"
] | 2 | 2020-06-17T13:20:22.000Z | 2021-04-11T10:18:03.000Z | #include <charconv>
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wsign-compare"
#endif
#include <ctre.hpp>
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#include <70mai.hh>
#include <filesystem>
namespace fs = std::filesystem;
namespace mgps::plugin::isom::mai {
namespace {
static constexpr auto filenames = ctll::fixed_string{
"^"
"([A-Za-z]{2})" // NO, EV, PA
"([0-9]{4})([0-9]{2})([0-9]{2})" // YYYYMMDD
"-"
"([0-9]{2})([0-9]{2})([0-9]{2})" // HHMMSS
"-.*$"};
template <typename Number>
bool from_chars(std::string_view chars, Number& value) {
auto const end = chars.data() + chars.size();
auto const result = std::from_chars(chars.data(), end, value);
return result.ec == std::errc{} && result.ptr == end;
}
track::NESW NESW(char c) {
switch (c) {
case 'N':
case 'n':
return track::NESW::N;
case 'E':
case 'e':
return track::NESW::E;
case 'S':
case 's':
return track::NESW::S;
case 'W':
case 'w':
return track::NESW::W;
default:
break;
}
using Int = std::underlying_type_t<track::NESW>;
return static_cast<track::NESW>(std::numeric_limits<Int>::max());
}
track::coordinate make_coord(uint32_t deg_min_1000, char direction) {
auto const full_degrees =
(deg_min_1000 / 100'000ull) * track::coordinate::precision::den;
auto const minutes_fraction = (deg_min_1000 % 100'000ull) *
track::coordinate::precision::den /
60'000;
return {full_degrees + minutes_fraction, NESW(direction)};
}
struct seek_to {
uint64_t pos;
storage& stg;
~seek_to() { stg.seek(pos); }
};
bool next_point(storage& data,
gps_point& pt,
std::chrono::seconds expected) {
seek_to end{data.tell() + 36, data};
if (data.eof()) return false;
auto const has_record = data.get<uint32_t>();
if (!has_record) return false;
if (data.eof()) return false;
auto const has_gps = data.get<uint32_t>();
if (data.eof()) return false;
auto const seconds = std::chrono::seconds{data.get<uint32_t>()};
if (!has_gps || seconds != expected) {
pt = gps_point{};
return true;
}
if (data.eof()) return false;
auto const metres_per_hour = speed_in_metres{data.get<uint32_t>()};
if (data.eof()) return false;
auto const lat_dir = data.get<char>();
if (data.eof()) return false;
auto const latitude = make_coord(data.get<uint32_t>(), lat_dir);
if (data.eof()) return false;
auto const lon_dir = data.get<char>();
if (data.eof()) return false;
auto const longitude = make_coord(data.get<uint32_t>(), lon_dir);
if (!latitude.valid() || !longitude.valid()) return false;
pt.lat = latitude;
pt.lon = longitude;
pt.pos = seconds;
pt.metres_per_hour = metres_per_hour;
pt.valid = true;
return true;
}
namespace loaders {
// duration
LEAF_BOX_READER(mvhd_box, duration_type) {
range_storage bits{&full, box};
bits.seek(0);
auto const version = bits.get<std::uint8_t>();
bits.get<std::uint8_t>();
bits.get<std::uint8_t>();
bits.get<std::uint8_t>();
if (bits.eof()) return false;
auto const short_ints = version == 0;
if (!short_ints && version > 1) {
data() = duration_type{};
return false;
}
if (short_ints) {
bits.get<std::uint32_t>();
bits.get<std::uint32_t>();
} else {
bits.get<std::uint64_t>();
bits.get<std::uint64_t>();
}
if (bits.eof()) return false;
data().timescale = bits.get_u32();
if (bits.eof()) return false;
if (short_ints) {
data().length = bits.get_u32();
} else {
data().length = bits.get_u64();
};
return true;
}
TREE_BOX_READER(moov_box, duration_type) {
switch (box.type) {
case box_type::mvhd:
return read_box<mvhd_box>(full, box, data());
default:
break;
}
return true;
}
} // namespace loaders
} // namespace
clip_filename_info get_filename_info(std::string_view filename) {
auto const pos = filename.find_last_of(fs::path::preferred_separator);
if (pos != std::string_view::npos) filename = filename.substr(pos + 1);
auto parts = ctre::match<filenames>(filename);
if (!parts) return {};
auto const clip_type = [](std::string_view type) {
#define UP(C) std::toupper(static_cast<unsigned char>(C))
#define TYPE_IS(L1, L2) ((UP(type[0]) == L1) && (UP(type[1]) == L2))
if (TYPE_IS('N', 'O')) return clip::normal;
if (TYPE_IS('E', 'V')) return clip::emergency;
if (TYPE_IS('P', 'A')) return clip::parking;
#undef TYPE_IS
#undef UP
return clip::other;
}(parts.get<1>().to_view());
unsigned uY{}, uM{}, uD{}, h{}, m{}, s{};
if (!from_chars(parts.get<2>().to_view(), uY)) return {};
if (!from_chars(parts.get<3>().to_view(), uM)) return {};
if (!from_chars(parts.get<4>().to_view(), uD)) return {};
if (!from_chars(parts.get<5>().to_view(), h)) return {};
if (!from_chars(parts.get<6>().to_view(), m)) return {};
if (!from_chars(parts.get<7>().to_view(), s)) return {};
using namespace date;
using namespace std::chrono;
auto const Y = year{static_cast<int>(uY)};
auto const M = static_cast<int>(uM);
auto const D = static_cast<int>(uD);
auto const date = Y / M / D;
if (!date.ok() || h > 23 || m > 59 || s > 59) return {};
using re_days = local_time<
ch::duration<ch::milliseconds::rep, date::days::period> >;
auto const local_date = re_days{local_days{date}.time_since_epoch()};
auto const time_of_day = hours{h} + minutes{m} + seconds{s};
return {clip_type, local_date + time_of_day};
}
bool read_GPS_box(storage& full,
box_info const& box,
std::vector<gps_point>& out) {
std::vector<gps_point> points(1);
if (box.type != GPS_box) return false;
range_storage bits{&full, box};
std::chrono::seconds expected{};
while (next_point(bits, points.back(), expected)) {
++expected;
if (!points.back().valid) continue;
points.push_back({});
}
if (!points.empty() && !points.back().valid) points.pop_back();
out = std::move(points);
return true;
}
bool read_moov_mhdr_duration(storage& full,
box_info const& box,
std::chrono::milliseconds& out) {
if (box.type != box_type::moov) return false;
duration_type duration;
if (!read_box<loaders::moov_box>(full, box, duration)) return false;
out = duration.to_chrono();
return true;
}
} // namespace mgps::plugin::isom::mai
| 28.220833 | 73 | 0.608445 | [
"vector"
] |
738a8fc9139d9a57c638f0b3a4c8c0165b02aa35 | 147,586 | cpp | C++ | src/TimeStepper/Optimizer.cpp | vincentkslim/IPC | eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98 | [
"MIT"
] | null | null | null | src/TimeStepper/Optimizer.cpp | vincentkslim/IPC | eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98 | [
"MIT"
] | null | null | null | src/TimeStepper/Optimizer.cpp | vincentkslim/IPC | eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98 | [
"MIT"
] | null | null | null | //
// Optimizer.cpp
// IPC
//
// Created by Minchen Li on 8/31/17.
//
#include "Optimizer.hpp"
#include "SelfCollisionHandler.hpp"
#ifdef LINSYSSOLVER_USE_CHOLMOD
#include "CHOLMODSolver.hpp"
#elif defined(LINSYSSOLVER_USE_AMGCL)
#include "AMGCLSolver.hpp"
#else
#include "EigenLibSolver.hpp"
#endif
#include <igl/writeDMAT.h>
#include "IglUtils.hpp"
#include "BarrierFunctions.hpp"
#include "Timer.hpp"
#include "CCDUtils.hpp"
#include <igl/avg_edge_length.h>
#include <igl/face_areas.h>
#include <igl/edge_lengths.h>
#include <igl/writeOBJ.h>
#include <igl/readOBJ.h>
#ifdef USE_TBB
#include <tbb/tbb.h>
#endif
#include <spdlog/spdlog.h>
#include <fstream>
#include <iostream>
#include <string>
#include <numeric>
#include <sys/stat.h> // for mkdir
// #define SAVE_EXTREME_LINESEARCH_CCD
// #define EXPORT_FRICTION_DATA
extern const std::string outputFolderPath;
extern std::ofstream logFile;
extern Timer timer, timer_step, timer_temp, timer_temp2, timer_temp3, timer_mt;
extern Eigen::MatrixXi SF;
extern std::vector<int> sTri2Tet;
extern std::vector<bool> isSurfNode;
extern std::vector<int> tetIndToSurf;
extern std::vector<int> surfIndToTet;
extern Eigen::MatrixXd V_surf;
extern Eigen::MatrixXi F_surf;
extern std::vector<bool> isCENode;
extern std::vector<int> tetIndToCE;
extern std::vector<int> CEIndToTet;
extern Eigen::MatrixXd V_CE;
extern Eigen::MatrixXi F_CE;
extern std::vector<int> compVAccSize;
extern std::vector<int> compFAccSize;
extern int numOfCCDFail;
namespace IPC {
#ifdef EXPORT_FRICTION_DATA
static bool should_save_friction_data = true;
template <int dim>
void save_friction_data(
const Mesh<dim>& mesh,
const std::vector<MMCVID>& mmcvids,
const Eigen::VectorXd& lambda,
const std::vector<Eigen::Vector2d>& coords,
const std::vector<Eigen::Matrix<double, 3, 2>>& tangent_bases,
double dHat_squared,
double barrier_stiffness,
double epsv_times_h_squared,
double kappa)
{
if (!should_save_friction_data) return;
return;
static int output_counter = 0;
std::string out_prefix = fmt::format("cube_cube_{:d}", output_counter++);
// Save the meshes
mesh.saveSurfaceMesh(fmt::format("{}_V0.obj", out_prefix), /*use_V_prev=*/true);
mesh.saveSurfaceMesh(fmt::format("{}_V1.obj", out_prefix), /*use_V_prev=*/false);
// Save the MMCVIDs
Eigen::MatrixXi mmcvids_matrix(mmcvids.size(), 4);
for (int i = 0; i < mmcvids.size(); i++) {
for (int j = 0; j < 4; j++) {
mmcvids_matrix(i, j) = mmcvids[i][j];
}
}
igl::writeDMAT(fmt::format("{}_mmcvids.dmat", out_prefix), mmcvids_matrix);
// Save the parameters
Eigen::Vector4d params;
params << dHat_squared, barrier_stiffness, epsv_times_h_squared, kappa;
igl::writeDMAT(fmt::format("{}_params.dmat", out_prefix), params);
// Save the normal force magnitudes
igl::writeDMAT(fmt::format("{}_lambda.dmat", out_prefix), lambda);
// Save the closes point coordinates
Eigen::MatrixXd coords_matrix(coords.size(), 2);
for (int i = 0; i < coords_matrix.rows(); i++) {
coords_matrix.row(i) = coords[i];
}
igl::writeDMAT(fmt::format("{}_coords.dmat", out_prefix), coords_matrix);
// Save the tangent bases
Eigen::MatrixXd tangent_bases_matrix(3 * tangent_bases.size(), 2);
for (int i = 0; i < tangent_bases.size(); i++) {
tangent_bases_matrix.middleRows(3 * i, 3) = tangent_bases[i];
}
igl::writeDMAT(fmt::format("{}_bases.dmat", out_prefix), tangent_bases_matrix);
// Compute the potential
double Ef;
SelfCollisionHandler<dim>::computeFrictionEnergy(
mesh.V, mesh.V_prev, mmcvids, lambda, coords, tangent_bases, Ef,
epsv_times_h_squared, kappa);
std::vector<double> energy = { { Ef } };
igl::writeDMAT(fmt::format("{}_energy.dmat", out_prefix), energy);
// Compute the gradient
Eigen::VectorXd friction_grad = Eigen::VectorXd::Zero(mesh.V.size());
SelfCollisionHandler<dim>::augmentFrictionGradient(
mesh.V, mesh.V_prev, mmcvids, lambda, coords, tangent_bases,
friction_grad, epsv_times_h_squared, kappa);
igl::writeDMAT(fmt::format("{}_grad.dmat", out_prefix), friction_grad);
// Compute the hessian
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* friction_linSysSolver = new EigenLibSolver<Eigen::VectorXi, Eigen::VectorXd>();
std::vector<std::set<int>> vNeighbor_IP_new = mesh.vNeighbor;
SelfCollisionHandler<dim>::augmentConnectivity(mesh, mmcvids, vNeighbor_IP_new);
friction_linSysSolver->set_pattern(vNeighbor_IP_new, mesh.fixedVert);
friction_linSysSolver->analyze_pattern();
friction_linSysSolver->setZero();
SelfCollisionHandler<dim>::augmentFrictionHessian(
mesh, mesh.V_prev, mmcvids, lambda, coords, tangent_bases,
friction_linSysSolver, epsv_times_h_squared, kappa, /*projectDBC=*/true);
Eigen::SparseMatrix<double> friction_hessian;
friction_linSysSolver->getCoeffMtr(friction_hessian);
igl::writeDMAT(fmt::format("{}_hess.dmat", out_prefix), Eigen::MatrixXd(friction_hessian));
}
#endif
template <int dim>
Optimizer<dim>::Optimizer(const Mesh<dim>& p_data0,
const std::vector<Energy<dim>*>& p_energyTerms, const std::vector<double>& p_energyParams,
bool p_mute,
const Eigen::MatrixXd& UV_bnds, const Eigen::MatrixXi& E, const Eigen::VectorXi& bnd,
const Config& p_animConfig)
: data0(p_data0), energyTerms(p_energyTerms), energyParams(p_energyParams), animConfig(p_animConfig), OSQPSolver(false)
{
assert(energyTerms.size() == energyParams.size());
gradient_ET.resize(energyTerms.size());
energyVal_ET.resize(energyTerms.size());
mute = p_mute;
if (!mute) {
file_iterStats.open(outputFolderPath + "iterStats.txt");
}
if (!data0.checkInversion()) {
spdlog::error("element inverted in the initial mesh!");
// exit(-1);
}
else {
spdlog::info("no element inversion detected!");
}
globalIterNum = 0;
relGL2Tol = 1.0e-8;
innerIterAmt = 0;
// TODO: Renable the Fischer-Burmeister check
fbNormTol = std::numeric_limits<double>::infinity(); // 1.0e-6;
bboxDiagSize2 = data0.matSpaceBBoxSize2(dim);
dTolRel = 1.0e-9;
if (animConfig.tuning.size() > 3) {
dTolRel = animConfig.tuning[3];
}
dTol = dTolRel * dTolRel;
if (!animConfig.useAbsParameters) {
dTol *= bboxDiagSize2;
}
rho_DBC = 0.0;
gravity.setZero();
if (animConfig.withGravity) {
gravity[1] = -9.80665;
}
setTime(10.0, 0.025);
spdlog::info("dt and tol initialized");
#ifdef LINSYSSOLVER_USE_CHOLMOD
linSysSolver = new CHOLMODSolver<Eigen::VectorXi, Eigen::VectorXd>();
dampingMtr = new CHOLMODSolver<Eigen::VectorXi, Eigen::VectorXd>();
#elif defined(LINSYSSOLVER_USE_AMGCL)
linSysSolver = new AMGCLSolver<Eigen::VectorXi, Eigen::VectorXd>();
dampingMtr = new AMGCLSolver<Eigen::VectorXi, Eigen::VectorXd>();
#else
linSysSolver = new EigenLibSolver<Eigen::VectorXi, Eigen::VectorXd>();
dampingMtr = new EigenLibSolver<Eigen::VectorXi, Eigen::VectorXd>();
#endif
setAnimScriptType(animConfig.animScriptType, animConfig.meshSeqFolderPath);
solveWithQP = (animConfig.isConstrained && (animConfig.constraintSolverType == CST_QP));
solveWithSQP = (animConfig.isConstrained && (animConfig.constraintSolverType == CST_SQP));
solveIP = (animConfig.isConstrained && (animConfig.constraintSolverType == CST_IP));
if (solveWithQP || solveWithSQP || solveIP) {
activeSet.resize(animConfig.collisionObjects.size());
activeSet_next.resize(animConfig.collisionObjects.size());
activeSet_lastH.resize(animConfig.collisionObjects.size());
lambda_lastH.resize(animConfig.collisionObjects.size());
MMActiveSet.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
MMActiveSet_next.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
MMActiveSet_CCD.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
paraEEMMCVIDSet.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
paraEEeIeJSet.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
buildConstraintStartIndsWithMM(activeSet, MMActiveSet, constraintStartInds);
MMActiveSet_lastH.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
MMLambda_lastH.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
MMDistCoord.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
MMTanBasis.resize(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
n_collPairs_sum.setZero(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
n_collPairs_max.setZero(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
n_convCollPairs_sum.setZero(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
n_convCollPairs_max.setZero(animConfig.meshCollisionObjects.size() + animConfig.isSelfCollision);
}
n_collPairs_total_max = n_convCollPairs_total_max = 0;
solveFric = false;
for (const auto& coI : animConfig.collisionObjects) {
if (coI->friction > 0.0) {
solveFric = true;
break;
}
}
for (const auto& coI : animConfig.meshCollisionObjects) {
if (coI->friction > 0.0) {
solveFric = true;
break;
}
}
if (animConfig.selfFric > 0.0) {
solveFric = true;
}
beta_NM = animConfig.beta;
gamma_NM = animConfig.gamma;
result = data0;
animScripter.initAnimScript(result, animConfig.collisionObjects,
animConfig.meshCollisionObjects, animConfig.DBCTimeRange, animConfig.NBCTimeRange);
result.saveBCNodes(outputFolderPath + "/BC_0.txt");
// Initialize these to zero in case they are missing from the status file
velocity = Eigen::VectorXd::Zero(result.V.rows() * dim);
dx_Elastic = Eigen::MatrixXd::Zero(result.V.rows(), dim);
acceleration = Eigen::MatrixXd::Zero(result.V.rows(), dim);
if (animConfig.restart) {
std::ifstream in(animConfig.statusPath.c_str());
assert(in.is_open());
std::string line;
while (std::getline(in, line)) {
std::stringstream ss(line);
std::string token;
ss >> token;
if (token == "timestep") {
ss >> globalIterNum;
}
else if (token == "position") {
spdlog::info("read restart position");
int posRows, dim_in;
ss >> posRows >> dim_in;
assert(posRows <= result.V.rows());
assert(dim_in == result.V.cols());
for (int vI = 0; vI < posRows; ++vI) {
in >> result.V(vI, 0) >> result.V(vI, 1);
if constexpr (dim == 3) {
in >> result.V(vI, 2);
}
}
}
else if (token == "velocity") {
spdlog::info("read restart velocity");
int velDim;
ss >> velDim;
assert(velDim <= result.V.rows() * dim);
velocity.setZero(result.V.rows() * dim);
for (int velI = 0; velI < velDim; ++velI) {
in >> velocity[velI];
}
}
else if (token == "acceleration") {
spdlog::info("read restart acceleration");
int accRows, dim_in;
ss >> accRows >> dim_in;
assert(accRows <= result.V.rows());
assert(dim_in == result.V.cols());
acceleration.setZero(result.V.rows(), dim);
for (int vI = 0; vI < accRows; ++vI) {
in >> acceleration(vI, 0) >> acceleration(vI, 1);
if constexpr (dim == 3) {
in >> acceleration(vI, 2);
}
}
}
else if (token == "dx_Elastic") {
spdlog::info("read restart dx_Elastic");
int dxERows, dim_in;
ss >> dxERows >> dim_in;
assert(dxERows <= result.V.rows());
assert(dim_in == dim);
dx_Elastic.setZero(result.V.rows(), dim);
for (int vI = 0; vI < dxERows; ++vI) {
in >> dx_Elastic(vI, 0) >> dx_Elastic(vI, 1);
if constexpr (dim == 3) {
in >> dx_Elastic(vI, 2);
}
}
}
}
in.close();
}
else {
animScripter.initVelocity(result, animConfig.scriptParams, velocity);
}
result.V_prev = result.V;
computeXTilta();
svd.resize(result.F.rows());
F.resize(result.F.rows());
if (energyTerms[0]->getNeedElemInvSafeGuard()) {
if (!result.checkInversion()) {
spdlog::error("scripted motion causes element inversion, end process");
exit(-1);
}
}
if (solveIP) {
sh.build(result, result.avgEdgeLen / 3.0);
if (isIntersected(result, sh, result.V, animConfig)) {
spdlog::error("intersection detected in initial configuration!");
exit(-1);
}
}
spdlog::info("animScriptor set");
updateTargetGRes();
CN_MBC = std::sqrt(1.0e-4 * bboxDiagSize2 * dtSq);
spdlog::info("Newton's solver for Backward Euler constructed");
numOfLineSearch = 0;
dHatEps = 1.0e-3;
if (animConfig.tuning.size() > 1) {
dHatEps = animConfig.tuning[1];
}
dHat = dHatEps * dHatEps;
if (!animConfig.useAbsParameters) {
dHat *= bboxDiagSize2;
}
dHatTarget = 1.0e-6;
if (animConfig.tuning.size() > 2) {
dHatTarget = animConfig.tuning[2] * animConfig.tuning[2];
}
if (!animConfig.useAbsParameters) {
dHatTarget *= bboxDiagSize2;
}
fricDHatThres = dHat; // enable friction only when collision dHat is smaller than fricDHatThres if it's not enabled initially
fricDHat0 = 1.0e-6 * dtSq; // initial value of fricDHat
if (animConfig.tuning.size() > 4) {
fricDHat0 = animConfig.tuning[4] * animConfig.tuning[4] * dtSq;
}
fricDHatTarget = 1.0e-6 * dtSq;
if (animConfig.tuning.size() > 5) {
fricDHatTarget = animConfig.tuning[5] * animConfig.tuning[5] * dtSq;
}
if (!animConfig.useAbsParameters) {
fricDHat0 *= bboxDiagSize2;
fricDHatTarget *= bboxDiagSize2;
}
fricDHat = solveFric ? fricDHat0 : -1.0;
kappa = 0.0;
if (animConfig.tuning.size() > 0) {
kappa = animConfig.tuning[0];
upperBoundKappa(kappa);
}
if (kappa == 0.0) {
suggestKappa(kappa);
}
// output wire.poly for rendering
Eigen::MatrixXd V_surf(result.SVI.size(), 3);
std::unordered_map<int, int> vI2SVI;
for (int svI = 0; svI < result.SVI.size(); ++svI) {
vI2SVI[result.SVI[svI]] = svI;
V_surf.row(svI) = result.V.row(result.SVI[svI]);
}
Eigen::MatrixXi F_surf(result.SF.rows(), 3);
for (int sfI = 0; sfI < result.SF.rows(); ++sfI) {
F_surf(sfI, 0) = vI2SVI[result.SF(sfI, 0)];
F_surf(sfI, 1) = vI2SVI[result.SF(sfI, 1)];
F_surf(sfI, 2) = vI2SVI[result.SF(sfI, 2)];
}
FILE* out = fopen((outputFolderPath + "wire.poly").c_str(), "w");
assert(out);
fprintf(out, "POINTS\n");
for (int vI = 0; vI < V_surf.rows(); ++vI) {
fprintf(out, "%d: %le %le %le\n", vI + 1, V_surf(vI, 0),
V_surf(vI, 1), V_surf(vI, 2));
}
fprintf(out, "POLYS\n");
for (int fI = 0; fI < F_surf.rows(); ++fI) {
int indStart = fI * 3;
fprintf(out, "%d: %d %d\n", indStart + 1, F_surf(fI, 0) + 1, F_surf(fI, 1) + 1);
fprintf(out, "%d: %d %d\n", indStart + 2, F_surf(fI, 1) + 1, F_surf(fI, 2) + 1);
fprintf(out, "%d: %d %d\n", indStart + 3, F_surf(fI, 2) + 1, F_surf(fI, 0) + 1);
}
fprintf(out, "END\n");
fclose(out);
}
template <int dim>
Optimizer<dim>::~Optimizer(void)
{
if (file_iterStats.is_open()) {
file_iterStats.close();
}
if (file_sysE.is_open()) {
file_sysE.close();
}
if (file_sysM.is_open()) {
file_sysM.close();
}
if (file_sysL.is_open()) {
file_sysL.close();
}
delete linSysSolver;
delete dampingMtr;
}
template <int dim>
Mesh<dim>& Optimizer<dim>::getResult(void)
{
return result;
}
template <int dim>
int Optimizer<dim>::getIterNum(void) const
{
return globalIterNum;
}
template <int dim>
int Optimizer<dim>::getFrameAmt(void) const
{
return frameAmt;
}
template <int dim>
int Optimizer<dim>::getInnerIterAmt(void) const
{
return innerIterAmt;
}
template <int dim>
void Optimizer<dim>::setRelGL2Tol(double p_relTol)
{
assert(p_relTol > 0.0);
relGL2Tol = p_relTol * p_relTol;
updateTargetGRes();
logFile << globalIterNum << "th tol: " << targetGRes << std::endl;
}
template <int dim>
double Optimizer<dim>::getDt(void) const
{
return dt;
}
template <int dim>
void Optimizer<dim>::setAnimScriptType(AnimScriptType animScriptType,
const std::string& meshSeqFolderPath)
{
animScripter.setAnimScriptType(animScriptType);
if (animScriptType == AST_MESHSEQ_FROMFILE) {
animScripter.setMeshSeqFolderPath(meshSeqFolderPath);
}
}
template <int dim>
void Optimizer<dim>::setTime(double duration, double dt)
{
this->dt = dt;
dtSq = dt * dt;
frameAmt = std::ceil(duration / dt);
updateTargetGRes();
gravityDtSq = dtSq * gravity;
computeXTilta();
}
// void Optimizer<dim>::fixDirection(void)
// {
// assert(result.V.rows() == result.V_rest.rows());
//
// directionFix.clear();
// const Eigen::RowVector2d& v0 = result.V.row(0);
// int nbVI = *result.vNeighbor[0].begin();
// const Eigen::RowVector2d& vi = result.V.row(nbVI);
// Eigen::RowVector2d dif = vi - v0;
// if(std::abs(dif[0]) > std::abs(dif[1])) {
// double coef = dif[1] / dif[0];
// directionFix[0] = coef;
// directionFix[1] = -1.0;
// directionFix[nbVI * 2] = -coef;
// directionFix[nbVI * 2 + 1] = 1.0;
// }
// else {
// double coef = dif[0] / dif[1];
// directionFix[0] = -1.0;
// directionFix[1] = coef;
// directionFix[nbVI * 2] = 1.0;
// directionFix[nbVI * 2 + 1] = -coef;
// }
// }
template <int dim>
void Optimizer<dim>::precompute(void)
{
spdlog::info("precompute: start");
if (!mute) { timer_step.start(1); }
linSysSolver->set_pattern(result.vNeighbor, result.fixedVert);
if (animConfig.dampingStiff) {
dampingMtr->set_pattern(result.vNeighbor, result.fixedVert);
}
if (!mute) { timer_step.stop(); }
spdlog::info("precompute: sparse matrix allocated");
if (solveIP) {
computeConstraintSets(result);
}
computePrecondMtr(result, true, linSysSolver, animConfig.dampingStiff);
spdlog::info("precompute: sparse matrix entry computed");
if (!mute) { timer_step.start(2); }
linSysSolver->analyze_pattern();
if (!mute) { timer_step.stop(); }
spdlog::info("precompute: pattern analyzed");
if (solveWithQP || solveWithSQP) {
precomputeQPObjective(linSysSolver, P_QP, elemPtr_P_QP);
}
computeEnergyVal(result, false, lastEnergyVal);
if (!mute) {
spdlog::info("E_initial = {:g}", lastEnergyVal);
}
std::vector<double> sysE;
std::vector<Eigen::Matrix<double, 1, dim>> sysM, sysL;
computeSystemEnergy(sysE, sysM, sysL);
file_sysE.open(outputFolderPath + "sysE.txt");
for (const auto& i : sysE) {
file_sysE << i << " ";
}
file_sysE << std::endl;
file_sysM.open(outputFolderPath + "sysM.txt");
for (const auto& i : sysM) {
file_sysM << i << " ";
}
file_sysM << std::endl;
file_sysL.open(outputFolderPath + "sysL.txt");
for (const auto& i : sysL) {
file_sysL << i << " ";
}
file_sysL << std::endl;
}
template <int dim>
int Optimizer<dim>::solve(int maxIter)
{
static bool lastPropagate = false;
int returnFlag = 0;
for (int iterI = 0; iterI < maxIter; iterI++) {
if (!mute) { timer.start(0); }
timer_step.start(11);
if (energyTerms[0]->getNeedElemInvSafeGuard()) {
if (!result.checkInversion()) {
spdlog::error("before scripted motion there's element inversion, end process");
exit(-1);
}
}
if (animScripter.stepAnimScript(result, sh,
animConfig.collisionObjects, animConfig.meshCollisionObjects,
animConfig.ccdMethod, dt, dHat, energyTerms, animConfig.isSelfCollision,
/*forceIntersectionLineSearch=*/solveIP)) {
result.saveBCNodes(outputFolderPath + "/BC_" + std::to_string(globalIterNum) + ".txt");
updatePrecondMtrAndFactorize();
}
#ifdef CHECK_ET_INTERSECTION
sh.build(result, result.avgEdgeLen / 3.0);
bool intersected = false;
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
intersected |= !animConfig.meshCollisionObjects[coI]->checkEdgeTriIntersection(result, sh);
}
if (animConfig.isSelfCollision) {
intersected |= !SelfCollisionHandler<dim>::checkEdgeTriIntersection(result, sh);
}
if (intersected) {
getchar();
}
#endif
if (energyTerms[0]->getNeedElemInvSafeGuard()) {
if (!result.checkInversion()) {
spdlog::error("scripted motion causes element inversion, end process");
exit(-1);
}
}
timer_step.stop();
if (globalIterNum >= frameAmt) {
// converged
if (!mute) { timer.stop(); }
return 1;
}
else {
if (solveIP) {
if (fullyImplicit_IP()) {
returnFlag = 2;
}
}
else {
if (fullyImplicit()) {
returnFlag = 2;
}
}
timer_step.start(11);
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrixXd;
switch (animConfig.timeIntegrationType) {
case TIT_BE: {
dx_Elastic = result.V - xTilta;
Eigen::VectorXd velocity_prev = velocity; // temporary storage
velocity = Eigen::Map<Eigen::VectorXd>(RowMatrixXd((result.V - result.V_prev).array() / dt).data(), velocity.rows());
acceleration = RowMatrixXd::Map(((velocity - velocity_prev) / dt).eval().data(), acceleration.rows(), acceleration.cols());
result.V_prev = result.V;
computeXTilta();
} break;
case TIT_NM:
dx_Elastic = result.V - xTilta;
velocity = velocity + dt * (1 - gamma_NM) * Eigen::Map<Eigen::MatrixXd>(RowMatrixXd(acceleration).data(), velocity.rows(), 1);
acceleration = (result.V - xTilta) / (dtSq * beta_NM);
acceleration.rowwise() += gravity.transpose();
velocity += dt * gamma_NM * Eigen::Map<Eigen::MatrixXd>(RowMatrixXd(acceleration).data(), velocity.rows(), 1);
result.V_prev = result.V;
computeXTilta();
break;
}
if (animConfig.dampingStiff) {
computeDampingMtr(result, false, dampingMtr); //TODO: projectDBC?
}
timer_step.stop();
}
globalIterNum++;
if (!mute) { timer.stop(); }
}
return returnFlag;
}
template <int dim>
void Optimizer<dim>::updatePrecondMtrAndFactorize(void)
{
if (!mute) {
spdlog::info("recompute proxy/Hessian matrix and factorize...");
}
if (!mute) { timer_step.start(1); }
linSysSolver->set_pattern(solveIP ? vNeighbor_IP : result.vNeighbor, result.fixedVert);
if (animConfig.dampingStiff) {
dampingMtr->set_pattern(solveIP ? vNeighbor_IP : result.vNeighbor, result.fixedVert);
}
if (!mute) { timer_step.start(2); }
linSysSolver->analyze_pattern();
if (!mute) { timer_step.start(3); }
computePrecondMtr(result, true, linSysSolver, animConfig.dampingStiff);
if (!mute) { timer_step.start(3); }
linSysSolver->factorize();
if (!mute) { timer_step.stop(); }
}
template <int dim>
void Optimizer<dim>::precomputeQPObjective(
const LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSys,
Eigen::SparseMatrix<double>& P,
std::vector<double*>& elemPtr_P) const
{
// Construct matrix sparsity pattern using triplet
std::vector<Eigen::Triplet<double>> coefs;
coefs.reserve(linSys->getNumNonzeros() * 2 - linSys->getNumRows());
for (int rowI = 0; rowI < linSys->getNumRows(); rowI++) {
for (const auto& colIter : linSys->getIJ2aI()[rowI]) {
coefs.emplace_back(rowI, colIter.first, 0.0);
if (rowI != colIter.first) {
coefs.emplace_back(colIter.first, rowI, 0.0);
}
}
}
P.resize(linSys->getNumRows(), linSys->getNumRows());
P.setZero();
P.reserve(coefs.size());
P.setFromTriplets(coefs.begin(), coefs.end());
// get matrix entry pointer for fast access
elemPtr_P.resize(0);
elemPtr_P.reserve(P.nonZeros());
for (int rowI = 0; rowI < linSys->getNumRows(); rowI++) {
for (const auto& colIter : linSys->getIJ2aI()[rowI]) {
elemPtr_P.emplace_back(&P.coeffRef(rowI, colIter.first));
if (rowI != colIter.first) {
elemPtr_P.emplace_back(&P.coeffRef(colIter.first, rowI));
}
}
}
}
template <int dim>
void Optimizer<dim>::updateQPObjective(
const LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSys,
const std::vector<double*>& elemPtr_P) const
{
// Update Hessian using entry pointers
int elemPtrI = 0;
for (int rowI = 0; rowI < linSys->getNumRows(); rowI++) {
for (const auto& colIter : linSys->getIJ2aI()[rowI]) {
assert(elemPtrI < elemPtr_P.size());
*elemPtr_P[elemPtrI++] = linSys->get_a()[colIter.second];
if (rowI != colIter.first) {
assert(elemPtrI < elemPtr_P.size());
*elemPtr_P[elemPtrI++] = linSys->get_a()[colIter.second];
}
}
}
}
template <int dim>
void Optimizer<dim>::computeQPInequalityConstraint(
const Mesh<dim>& mesh,
const std::vector<std::shared_ptr<CollisionObject<dim>>>& collisionObjects,
const std::vector<std::vector<int>>& activeSet,
const int num_vars,
std::vector<int>& constraintStartInds,
Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b) const
{
// construct constraint matrix and vector
std::vector<Eigen::Triplet<double>> A_triplet;
constraintStartInds.resize(1);
constraintStartInds[0] = 0;
for (int coI = 0; coI < collisionObjects.size(); ++coI) {
collisionObjects[coI]->updateConstraints_QP(
mesh, activeSet[coI], A_triplet, b);
constraintStartInds.emplace_back(b.size());
}
//TODO: use input argument
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
animConfig.meshCollisionObjects[coI]->updateConstraints_QP(
mesh, MMActiveSet[coI], animConfig.constraintType, A_triplet, b);
constraintStartInds.emplace_back(b.size());
}
if (animConfig.isSelfCollision) {
SelfCollisionHandler<dim>::updateConstraints_QP(
mesh, MMActiveSet.back(), animConfig.constraintType,
mesh_mmcvid_to_toi, A_triplet, b);
constraintStartInds.emplace_back(b.size());
}
// Offset the constraints to allow for solver tolerances.
b.array() += animConfig.constraintOffset;
int num_constraints = b.size();
A.resize(num_constraints, num_vars);
if (num_constraints > 0) {
A.setZero();
A.reserve(A_triplet.size());
A.setFromTriplets(A_triplet.begin(), A_triplet.end());
}
}
template <int dim>
bool Optimizer<dim>::solveQP(
const Mesh<dim>& mesh,
const std::vector<std::shared_ptr<CollisionObject<dim>>>& collisionObjects,
const std::vector<std::vector<int>>& activeSet,
const LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSys,
Eigen::SparseMatrix<double>& P,
const std::vector<double*>& elemPtr_P,
Eigen::VectorXd& gradient,
OSQP& OSQPSolver,
#ifdef USE_GUROBI
Eigen::GurobiSparse& gurobiQPSolver,
#endif
std::vector<int>& constraintStartInds,
Eigen::VectorXd& searchDir,
Eigen::VectorXd& dual,
QPSolverType qpSolverType) const
{
// minₓ ½xᵀQx + cᵀx
if (!solveWithQP) {
this->updateQPObjective(linSys, elemPtr_P);
}
// Ax ≥ b
Eigen::SparseMatrix<double> A;
Eigen::VectorXd b;
this->computeQPInequalityConstraint(
mesh, collisionObjects, activeSet, linSys->getNumRows(),
constraintStartInds, A, b);
switch (qpSolverType) {
case QPSolverType::QP_OSQP:
return solveQP_OSQP(
P, gradient, A, b, OSQPSolver, searchDir, dual);
case QPSolverType::QP_GUROBI:
#ifdef USE_GUROBI
return solveQP_Gurobi(
P, gradient, A, b, gurobiQPSolver, searchDir, dual);
#else
spdlog::error("Gurobi QP solve is disabled. Set IPC_WITH_GUROBI=ON in cmake to enable.");
throw "Gurobi QP solve is disabled. Set IPC_WITH_GUROBI=ON in cmake to enable.";
#endif
}
// std::string folderPath = outputFolderPath + std::to_string(globalIterNum) + "/";
// mkdir(folderPath.c_str(), 0777);
// IglUtils::writeSparseMatrixToFile(folderPath + "P" + std::to_string(innerIterAmt), Q, true);
// IglUtils::writeVectorToFile(folderPath + "q" + std::to_string(innerIterAmt), c);
// IglUtils::writeSparseMatrixToFile(folderPath + "A" + std::to_string(innerIterAmt), A, true);
// IglUtils::writeVectorToFile(folderPath + "l" + std::to_string(innerIterAmt), b);
// IglUtils::writeVectorToFile(folderPath + "primal" + std::to_string(innerIterAmt), x);
// IglUtils::writeVectorToFile(folderPath + "dual" + std::to_string(innerIterAmt), dual);
}
template <int dim>
bool Optimizer<dim>::solveQP_OSQP(
Eigen::SparseMatrix<double>& Q, Eigen::VectorXd& c,
Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b,
OSQP& QPSolver, Eigen::VectorXd& x, Eigen::VectorXd& dual) const
{
c_int num_vars = c_int(c.rows()), num_constraints = c_int(b.size());
Eigen::VectorXd u = Eigen::VectorXd::Constant(
num_constraints, std::numeric_limits<double>::infinity());
// setup QPSolver and solve
QPSolver.setup(
Q.valuePtr(), c_int(Q.nonZeros()), Q.innerIndexPtr(), Q.outerIndexPtr(),
c.data(),
A.valuePtr(), c_int(A.nonZeros()),
A.innerIndexPtr(), A.outerIndexPtr(),
b.data(), u.data(),
num_vars, num_constraints);
x.conservativeResize(num_vars);
c_int status = QPSolver.solve();
if ((status != -3) && (status != -4)) {
memcpy(x.data(), QPSolver.getPrimal(),
x.size() * sizeof(x[0]));
}
if (num_constraints > 0) {
dual.conservativeResize(num_constraints);
if ((status != -3) && (status != -4)) {
memcpy(dual.data(), QPSolver.getDual(),
dual.size() * sizeof(dual[0]));
}
}
return (status != -3) && (status != -4);
}
#ifdef USE_GUROBI
template <int dim>
bool Optimizer<dim>::solveQP_Gurobi(
const Eigen::SparseMatrix<double>& Q, const Eigen::VectorXd& c,
const Eigen::SparseMatrix<double>& A, const Eigen::VectorXd& b,
Eigen::GurobiSparse& QPSolver,
Eigen::VectorXd& x, Eigen::VectorXd& dual) const
{
int num_vars = c.rows(), num_constraints = b.size();
// setup QPSolver and solve
QPSolver.displayOutput(false);
QPSolver.problem(num_vars, /*nreq=*/0, num_constraints);
Eigen::SparseVector<double> inf = Eigen::VectorXd::Constant(
num_vars, std::numeric_limits<double>::infinity())
.sparseView();
bool success;
try {
success = QPSolver.solve(
/*Q=*/Q, /*C=*/c.sparseView(),
/*Aeq=*/Eigen::SparseMatrix<double>(), /*Beq=*/Eigen::SparseVector<double>(),
// We want Ax ≥ b, but Gurobi expects Ax ≤ b
/*Aineq=*/-A, /*Bineq=*/-b.sparseView(),
/*XL=*/-inf, /*XU=*/inf);
}
catch (GRBException e) {
spdlog::error("GRBException: {:s}", e.getMessage());
success = false;
}
x.conservativeResize(num_vars);
if (success) {
memcpy(x.data(), QPSolver.result().data(), x.size() * sizeof(x[0]));
}
else {
x.setZero();
}
if (num_constraints > 0) {
dual.conservativeResize(num_constraints);
if (success) {
memcpy(dual.data(), QPSolver.dual_ineq().data(),
dual.size() * sizeof(dual[0]));
}
}
return success;
}
#endif
template <int dim>
void Optimizer<dim>::computeQPResidual(const Mesh<dim>& mesh,
const std::vector<std::shared_ptr<CollisionObject<dim>>>& collisionObjects,
const std::vector<std::vector<int>>& activeSet,
const std::vector<int>& constraintStartInds,
const Eigen::VectorXd& gradient,
const Eigen::VectorXd& dual,
Eigen::VectorXd& grad_KKT,
Eigen::VectorXd& constraintVal,
Eigen::VectorXd& fb)
{
grad_KKT = gradient;
constraintVal.conservativeResize(0);
for (int coI = 0; coI < collisionObjects.size(); ++coI) {
int constraintAmtI = constraintStartInds[coI + 1] - constraintStartInds[coI];
if (constraintAmtI) {
collisionObjects[coI]->evaluateConstraintsQP(mesh, activeSet[coI], constraintVal);
collisionObjects[coI]->leftMultiplyConstraintJacobianTQP(mesh, activeSet[coI],
dual.segment(constraintStartInds[coI], constraintAmtI),
grad_KKT);
}
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
int constraintAmtI = constraintStartInds[coI + 1 + collisionObjects.size()] - constraintStartInds[coI + collisionObjects.size()];
if (constraintAmtI) {
animConfig.meshCollisionObjects[coI]->evaluateConstraintsQP(
mesh, MMActiveSet[coI], animConfig.constraintType, constraintVal);
animConfig.meshCollisionObjects[coI]->leftMultiplyConstraintJacobianTQP(
mesh, MMActiveSet[coI],
dual.segment(constraintStartInds[coI + collisionObjects.size()], constraintAmtI),
animConfig.constraintType,
grad_KKT);
}
}
if (animConfig.isSelfCollision) {
int constraintStartI = constraintStartInds[constraintStartInds.size() - 2];
int constraintAmtI = constraintStartInds.back() - constraintStartI;
if (constraintAmtI) {
SelfCollisionHandler<dim>::evaluateConstraintsQP(
mesh, MMActiveSet.back(), animConfig.constraintType,
mesh_mmcvid_to_toi, constraintVal);
SelfCollisionHandler<dim>::leftMultiplyConstraintJacobianTQP(
mesh, MMActiveSet.back(),
dual.segment(constraintStartI, constraintAmtI),
animConfig.constraintType, mesh_mmcvid_to_toi, grad_KKT);
}
}
fb.conservativeResize(constraintStartInds.back()); // Fischer-Burmeister measure for complementarity
for (int constraintI = 0; constraintI < constraintStartInds.back(); ++constraintI) {
const double dualI = -dual[constraintI]; // OSQP produce negative dual for >= constraints
const double& constraint = constraintVal[constraintI];
fb[constraintI] = (dualI + constraint - std::sqrt(dualI * dualI + constraint * constraint));
}
}
template <int dim>
void Optimizer<dim>::initX(int option, std::vector<std::vector<int>>& p_activeSet_next)
{
// global:
searchDir.conservativeResize(result.V.rows() * dim);
switch (option) {
case 0:
// already at last timestep config
searchDir.setZero();
break;
case 1: // explicit Euler
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir.segment<dim>(vI * dim) = dt * velocity.segment<dim>(vI * dim);
}
}
#ifdef USE_TBB
);
#endif
break;
case 2: // xHat
switch (animConfig.timeIntegrationType) {
case TIT_BE:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir.segment<dim>(vI * dim) = dt * velocity.segment<dim>(vI * dim) + gravityDtSq;
}
}
#ifdef USE_TBB
);
#endif
break;
case TIT_NM:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir.segment<dim>(vI * dim) = dt * velocity.segment<dim>(vI * dim) + gravityDtSq / 2.0;
}
}
#ifdef USE_TBB
);
#endif
break;
}
break;
case 3: { // Symplectic Euler
switch (animConfig.timeIntegrationType) {
case TIT_BE:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir.segment<dim>(vI * dim) = (dt * velocity.segment<dim>(vI * dim) + gravityDtSq + dx_Elastic.row(vI).transpose());
}
}
#ifdef USE_TBB
);
#endif
break;
case TIT_NM:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir.segment<dim>(vI * dim) = dt * velocity.segment<dim>(vI * dim) + gravityDtSq / 2.0 + dx_Elastic.row(vI).transpose() * 2.0;
}
}
#ifdef USE_TBB
);
#endif
break;
}
break;
}
case 4: { // uniformly accelerated motion approximation
switch (animConfig.timeIntegrationType) {
case TIT_BE:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir.segment<dim>(vI * dim) = (dt * velocity.segment<dim>(vI * dim) + (gravityDtSq + 0.5 * dx_Elastic.row(vI).transpose()));
}
}
#ifdef USE_TBB
);
#endif
break;
case TIT_NM:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir.segment<dim>(vI * dim) = dt * velocity.segment<dim>(vI * dim) + gravityDtSq / 2.0 + dx_Elastic.row(vI).transpose();
}
}
#ifdef USE_TBB
);
#endif
break;
}
break;
}
case 5: { // Jacobi
Eigen::VectorXd g;
computeGradient(result, true, g);
Eigen::VectorXi I, J;
Eigen::VectorXd V;
computePrecondMtr(result, false, linSysSolver);
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
searchDir.segment<dim>(vI * dim).setZero();
}
else {
searchDir[vI * dim] = -g[vI * dim] / linSysSolver->coeffMtr(vI * dim, vI * dim);
searchDir[vI * dim + 1] = -g[vI * dim + 1] / linSysSolver->coeffMtr(vI * dim + 1, vI * dim + 1);
searchDir[vI * dim + 2] = -g[vI * dim + 2] / linSysSolver->coeffMtr(vI * dim + 2, vI * dim + 2);
}
}
#ifdef USE_TBB
);
#endif
break;
}
default:
spdlog::warn("unkown primal initialization type, use last timestep instead");
break;
}
if (option) {
double stepSize = 1.0, slackness_a = 0.9, slackness_m = 0.8;
energyTerms[0]->filterStepSize(result, searchDir, stepSize);
if (solveWithQP || solveWithSQP) {
// Always clear the active set at the start of time-step
clearActiveSet();
updateActiveSet_QP();
}
else if (solveIP) {
for (int coI = 0; coI < animConfig.collisionObjects.size(); coI++) {
p_activeSet_next[coI].resize(0);
animConfig.collisionObjects[coI]->largestFeasibleStepSize(result, searchDir, slackness_a,
p_activeSet_next[coI], stepSize);
}
// always use full CCD for warm start
#ifdef USE_SH_LFSS
timer_temp3.start(11);
sh.build(result, searchDir, stepSize, result.avgEdgeLen / 3.0);
timer_temp3.stop();
#endif
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); coI++) {
MMActiveSet_next[coI].resize(0);
switch (animConfig.ccdMethod) {
case ccd::CCDMethod::FLOATING_POINT_ROOT_FINDER:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_CCD(
result, sh, searchDir, slackness_m, stepSize);
break;
case ccd::CCDMethod::TIGHT_INCLUSION:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_CCD_TightInclusion(
result, sh, searchDir, animConfig.ccdTolerance, stepSize);
break;
default:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_CCD_exact(
result, sh, searchDir, animConfig.ccdMethod, stepSize);
}
}
if (animConfig.isSelfCollision) {
MMActiveSet_next.back().resize(0);
std::vector<std::pair<int, int>> newCandidates;
switch (animConfig.ccdMethod) {
case ccd::CCDMethod::FLOATING_POINT_ROOT_FINDER:
SelfCollisionHandler<dim>::largestFeasibleStepSize_CCD(
result, sh, searchDir, slackness_m, newCandidates, stepSize);
break;
case ccd::CCDMethod::TIGHT_INCLUSION:
SelfCollisionHandler<dim>::largestFeasibleStepSize_CCD_TightInclusion(
result, sh, searchDir, animConfig.ccdTolerance, newCandidates, stepSize);
break;
default:
SelfCollisionHandler<dim>::largestFeasibleStepSize_CCD_exact(
result, sh, searchDir, animConfig.ccdMethod, stepSize);
}
}
if (stepSize == 0.0) {
spdlog::info("CCD gives 0 in initX()");
}
}
if (!(solveWithQP || solveWithSQP)) {
Eigen::MatrixXd V0 = result.V;
stepForward(V0, result, stepSize);
if (energyTerms[0]->getNeedElemInvSafeGuard()) {
while (!result.checkInversion(true)) {
logFile << "element inversion detected during warmStart, backtrack!" << std::endl;
stepSize /= 2.0;
stepForward(V0, result, stepSize);
}
}
if (solveIP) {
sh.build(result, result.avgEdgeLen / 3.0);
while (isIntersected(result, sh, V0, animConfig)) {
logFile << "intersection detected during warmStart, backtrack!" << std::endl;
stepSize /= 2.0;
stepForward(V0, result, stepSize);
sh.build(result, result.avgEdgeLen / 3.0);
}
}
}
#ifdef CHECK_ET_INTERSECTION
sh.build(result, result.avgEdgeLen / 3.0);
bool intersected = false;
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
intersected |= !animConfig.meshCollisionObjects[coI]->checkEdgeTriIntersection(result, sh);
}
if (animConfig.isSelfCollision) {
intersected |= !SelfCollisionHandler<dim>::checkEdgeTriIntersection(result, sh);
}
if (intersected) {
getchar();
}
#endif
spdlog::debug(
"timestep={:d} init_stepSize={:g}", globalIterNum, stepSize);
}
else if (solveWithQP || solveWithSQP || solveIP) {
clearActiveSet();
}
}
template <int dim>
void Optimizer<dim>::computeXTilta(void)
{
xTilta.conservativeResize(result.V.rows(), dim);
switch (animConfig.timeIntegrationType) {
case TIT_BE:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
xTilta.row(vI) = result.V_prev.row(vI);
}
else {
xTilta.row(vI) = (result.V_prev.row(vI) + (velocity.segment<dim>(vI * dim) * dt + gravityDtSq).transpose());
}
}
#ifdef USE_TBB
);
#endif
break;
case TIT_NM:
#ifdef USE_TBB
tbb::parallel_for(0, (int)result.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < result.V.rows(); vI++)
#endif
{
if (result.isFixedVert[vI]) {
xTilta.row(vI) = result.V_prev.row(vI);
}
else {
xTilta.row(vI) = (result.V_prev.row(vI) + (velocity.segment<dim>(vI * dim) * dt + beta_NM * gravityDtSq + (0.5 - beta_NM) * (dtSq * acceleration.row(vI).transpose())).transpose());
}
}
#ifdef USE_TBB
);
#endif
break;
}
}
template <int dim>
void Optimizer<dim>::clearActiveSet()
{
for (int coI = 0; coI < animConfig.collisionObjects.size(); coI++) {
activeSet_next[coI].clear();
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); coI++) {
MMActiveSet_next[coI].clear();
}
if (animConfig.isSelfCollision) {
MMActiveSet_next.back().clear();
}
}
template <int dim>
bool Optimizer<dim>::updateActiveSet_QP()
{
bool newConstraintsAdded = false;
// TODO: Explain this factor of two
const double eta = 2 * animConfig.constraintOffset;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
// TODO: Modify this function to check if the set changed
animConfig.collisionObjects[coI]->filterSearchDir_QP(
result, searchDir, activeSet_next[coI]);
activeSet[coI] = activeSet_next[coI];
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); coI++) {
newConstraintsAdded |= animConfig.meshCollisionObjects[coI]->updateActiveSet_QP(
result, searchDir, animConfig.constraintType,
MMActiveSet_next[coI], animConfig.ccdMethod, eta,
animConfig.ccdTolerance);
MMActiveSet[coI] = MMActiveSet_next[coI];
}
if (animConfig.isSelfCollision) {
newConstraintsAdded |= SelfCollisionHandler<dim>::updateActiveSet_QP(
result, searchDir, animConfig.constraintType,
MMActiveSet_next.back(), mesh_mmcvid_to_toi, animConfig.ccdMethod,
eta, animConfig.ccdTolerance);
MMActiveSet.back() = MMActiveSet_next.back();
}
return newConstraintsAdded;
}
template <int dim>
int Optimizer<dim>::countConstraints()
{
int constraintAmt = 0;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
constraintAmt += activeSet[coI].size();
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); coI++) {
constraintAmt += MMActiveSet[coI].size();
}
if (animConfig.isSelfCollision && MMActiveSet.size() > 0) {
constraintAmt += MMActiveSet.back().size();
}
return constraintAmt;
}
template <int dim>
bool Optimizer<dim>::fullyImplicit(void)
{
timer_step.start(10);
// initial warm start with inital guess search direction p₀
// and compute initial active set A_0 checking for collisions from x_t to x_t + p_0
initX(animConfig.warmStart, activeSet_next);
computeEnergyVal(result, true, lastEnergyVal);
computeGradient(result, false, gradient);
if (solveWithQP) {
// Compute the hessian once at the beginning of the optimization
computePrecondMtr(result, false, linSysSolver);
updateQPObjective(linSysSolver, elemPtr_P_QP);
}
timer_step.stop();
int constraintAmt = countConstraints();
spdlog::debug("after initX: E={:g} ||g||²={:g} targetGRes={:g} constraintAmt={:d}",
lastEnergyVal, gradient.squaredNorm(), targetGRes, constraintAmt);
file_iterStats << fmt::format("{:d} 0 {:g} {:g} 0\n",
globalIterNum, lastEnergyVal, gradient.squaredNorm());
// Termination criteria variables
Eigen::VectorXd fb;
double sqn_g = std::numeric_limits<double>::infinity(), sqn_g0;
int iterCap = 10000, curIterI = 0;
bool newConstraintsAdded = false;
double meshScale = (result.V.colwise().maxCoeff() - result.V.colwise().minCoeff()).maxCoeff();
do {
file_iterStats << globalIterNum << " ";
if (solve_oneStep()) {
spdlog::error(
"timestep={:d} iteration={:d} "
"msg=\"line search failed!!!\"",
globalIterNum, curIterI);
logFile << "\tline search with Armijo's rule failed!!!"
<< std::endl;
return true;
}
innerIterAmt++;
if (searchDir.norm() > 100 * meshScale) {
spdlog::warn(
"timestep={:d} iteration={:05d} msg=\"possible displacement blow-up\" meshScale={:g} searchDir.norm()={:g}",
globalIterNum, curIterI, meshScale, searchDir.norm());
result.saveSurfaceMesh("output/blowup_t" + std::to_string(globalIterNum) + "_i" + std::to_string(curIterI) + ".obj");
#ifdef EXIT_UPON_QP_FAIL
exit(2);
#endif
}
timer_step.start(10);
Eigen::VectorXd grad_KKT, constraintVal;
if (solveWithQP || solveWithSQP) {
computeQPResidual(result, animConfig.collisionObjects, activeSet,
constraintStartInds, gradient, dual_QP,
grad_KKT, constraintVal, fb);
// || H(xᵗ)dx + ∇E(xᵗ) + Cᵀλ ||²
if (solveWithQP) {
sqn_g = (P_QP * searchDir + grad_KKT).squaredNorm();
}
else {
sqn_g = grad_KKT.squaredNorm();
}
newConstraintsAdded = updateActiveSet_QP();
}
else {
sqn_g = gradient.squaredNorm();
}
if (curIterI == 0) {
sqn_g0 = sqn_g;
}
file_iterStats << fmt::format("{:g} {:g} {:d}\n",
lastEnergyVal, sqn_g, (constraintStartInds.empty() ? 0 : constraintStartInds.back()));
timer_step.stop();
constraintAmt = countConstraints();
double currentEnergyVal;
computeEnergyVal(result, true, currentEnergyVal);
spdlog::debug(
"timestep={:d} iteration={:05d} currentEnergyVal={:.6e} "
"gradient.squaredNorm()={:g} sqn_g={:.6e} fb.norm()={:.6e} "
"constraintAmt={:03d} newConstraintsAdded={}",
globalIterNum, curIterI, currentEnergyVal, gradient.squaredNorm(),
sqn_g, fb.norm(), constraintAmt, newConstraintsAdded);
if (++curIterI >= iterCap) {
spdlog::warn(
"timestep={:d} msg=\"optimization did not converge in at most {:d} iterations\" "
"sqn_g={:g} targetGRes={:g} fb.norm()={:g} fbNormTol={:g}",
globalIterNum, iterCap, sqn_g, targetGRes, fb.norm(), fbNormTol);
break;
}
double curEnergyVal;
computeEnergyVal(result, true, curEnergyVal);
if ((curEnergyVal - lastEnergyVal) / lastEnergyVal > 1e9 && curEnergyVal > 1e9) {
spdlog::warn(
"timestep={:d} iteration={:05d} msg=\"possible energy blow-up\" lastEnergyVal={:g} curEnergyVal={:g}",
globalIterNum, curIterI, lastEnergyVal, curEnergyVal);
result.saveSurfaceMesh("output/blowup_t" + std::to_string(globalIterNum) + "_i" + std::to_string(curIterI) + ".obj");
#ifdef EXIT_UPON_QP_FAIL
exit(2);
#endif
}
if ((sqn_g - sqn_g0) / sqn_g0 > 1e9 && sqn_g > 1e9) {
spdlog::warn(
"timestep={:d} iteration={:05d} msg=\"possible gradient blow-up\" sqn_g0={:g} sqn_g={:g}",
globalIterNum, curIterI, sqn_g0, sqn_g);
result.saveSurfaceMesh("output/blowup_t" + std::to_string(globalIterNum) + "_i" + std::to_string(curIterI) + ".obj");
#ifdef EXIT_UPON_QP_FAIL
exit(2);
#endif
}
} while ((animConfig.useActiveSetConvergence && newConstraintsAdded)
|| (sqn_g > targetGRes) || (solveWithSQP && (fb.norm() > fbNormTol)));
spdlog::info(
"timestep={:d} total_iterations={:d} sqn_g={:.6e} fb.norm()={:.6e} "
"dual_QP.maxCoeff()={:s} dual_QP.minCoeff()={:s}",
globalIterNum, curIterI, sqn_g, fb.norm(),
dual_QP.size() ? std::to_string(dual_QP.maxCoeff()) : "N/a",
dual_QP.size() ? std::to_string(dual_QP.minCoeff()) : "N/a");
sh.build(result, result.avgEdgeLen / 3.0);
bool isIntersecting = false;
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
if (!animConfig.meshCollisionObjects[coI]->checkEdgeTriIntersection(result, sh)) {
spdlog::error(
"timestep={:d} msg=\"intersecting state of the mesh and collision object {:d}\"",
globalIterNum, coI);
isIntersecting = true;
}
}
if (animConfig.isSelfCollision && !SelfCollisionHandler<dim>::checkEdgeTriIntersection(result, sh)) {
spdlog::error(
"timestep={:d} msg=\"self-intersecting state\"", globalIterNum);
isIntersecting = true;
}
if (isIntersecting) {
result.saveSurfaceMesh("output/intersecting_t" + std::to_string(globalIterNum) + ".obj");
#ifdef EXIT_UPON_QP_FAIL
exit(1);
#endif
}
logFile << "Timestep" << globalIterNum << " innerIterAmt = " << innerIterAmt << ", accumulated line search steps " << numOfLineSearch << std::endl;
std::vector<double> sysE;
std::vector<Eigen::Matrix<double, 1, dim>> sysM, sysL;
computeSystemEnergy(sysE, sysM, sysL);
for (const auto& i : sysE) {
file_sysE << i << " ";
}
file_sysE << std::endl;
for (const auto& i : sysM) {
file_sysM << i << " ";
}
file_sysM << std::endl;
for (const auto& i : sysL) {
file_sysL << i << " ";
}
file_sysL << std::endl;
return (curIterI >= iterCap);
}
template <int dim>
bool Optimizer<dim>::fullyImplicit_IP(void)
{
spdlog::info("Timestep {:d}:", globalIterNum);
for (auto& i : activeSet_lastH) {
i.resize(0);
}
for (auto& i : MMActiveSet_lastH) {
i.resize(0);
}
timer_step.start(10);
initX(animConfig.warmStart, activeSet_next);
timer_step.stop();
fricDHat = solveFric ? fricDHat0 : -1.0;
dHat = dHatEps * dHatEps;
if (!animConfig.useAbsParameters) {
dHat *= bboxDiagSize2;
}
computeConstraintSets(result);
kappa = 0.0;
if (animConfig.tuning.size() > 0) {
kappa = animConfig.tuning[0];
upperBoundKappa(kappa);
}
if (kappa == 0.0) {
suggestKappa(kappa);
}
#ifdef ADAPTIVE_KAPPA
initKappa(kappa);
#endif
timer_step.start(10);
Eigen::VectorXd constraintVal;
bool activeSetChanged = false;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
int startCI = constraintVal.size();
animConfig.collisionObjects[coI]->evaluateConstraints(result,
activeSet[coI], constraintVal);
if (animConfig.collisionObjects[coI]->friction > 0.0) {
lambda_lastH[coI].resize(constraintVal.size() - startCI);
//TODO: parallelize
for (int i = 0; i < lambda_lastH[coI].size(); ++i) {
compute_g_b(constraintVal[startCI + i], dHat, lambda_lastH[coI][i]);
lambda_lastH[coI][i] *= -kappa * 2.0 * std::sqrt(constraintVal[startCI + i]);
}
if (activeSet_lastH[coI] != activeSet[coI]) {
activeSetChanged = true;
activeSet_lastH[coI] = activeSet[coI];
}
}
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
animConfig.meshCollisionObjects[coI]->evaluateConstraints(result,
MMActiveSet[coI], constraintVal);
}
if (animConfig.isSelfCollision) {
int startCI = constraintVal.size();
SelfCollisionHandler<dim>::evaluateConstraints(result, MMActiveSet.back(), constraintVal);
if (animConfig.selfFric > 0.0) {
MMLambda_lastH.back().resize(constraintVal.size() - startCI);
//TODO: parallelize
for (int i = 0; i < MMLambda_lastH.back().size(); ++i) {
compute_g_b(constraintVal[startCI + i], dHat, MMLambda_lastH.back()[i]);
MMLambda_lastH.back()[i] *= -kappa * 2.0 * std::sqrt(constraintVal[startCI + i]);
if (MMActiveSet.back()[i][3] < -1) {
// PP or PE duplication
MMLambda_lastH.back()[i] *= -MMActiveSet.back()[i][3];
}
}
SelfCollisionHandler<dim>::computeDistCoordAndTanBasis(
result, MMActiveSet.back(), MMDistCoord.back(), MMTanBasis.back());
if (MMActiveSet_lastH.back() != MMActiveSet.back()) {
activeSetChanged = true;
MMActiveSet_lastH.back() = MMActiveSet.back();
}
}
}
timer_step.stop();
timer_step.start(10);
computeEnergyVal(result, true, lastEnergyVal); // for possible warmstart and pre-scripting Dirichlet boundary conditions
file_iterStats << globalIterNum << " 0.0 0" << std::endl;
// globaIterNum lineSearchStepSize constraintNum
timer_step.stop();
int fricIterI = 0;
while (true) {
initSubProb_IP();
solveSub_IP(kappa, activeSet_next, MMActiveSet_next);
++fricIterI;
timer_step.start(10);
Eigen::VectorXd constraintVal;
bool activeSetChanged = false;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
int startCI = constraintVal.size();
animConfig.collisionObjects[coI]->evaluateConstraints(result,
activeSet[coI], constraintVal);
if (animConfig.collisionObjects[coI]->friction > 0.0) {
lambda_lastH[coI].resize(constraintVal.size() - startCI);
//TODO: parallelize
for (int i = 0; i < lambda_lastH[coI].size(); ++i) {
compute_g_b(constraintVal[startCI + i], dHat, lambda_lastH[coI][i]);
lambda_lastH[coI][i] *= -kappa * 2.0 * std::sqrt(constraintVal[startCI + i]);
}
if (activeSet_lastH[coI] != activeSet[coI]) {
activeSetChanged = true;
activeSet_lastH[coI] = activeSet[coI];
}
}
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
animConfig.meshCollisionObjects[coI]->evaluateConstraints(result,
MMActiveSet[coI], constraintVal);
}
if (animConfig.isSelfCollision) {
int startCI = constraintVal.size();
SelfCollisionHandler<dim>::evaluateConstraints(result, MMActiveSet.back(), constraintVal);
if (animConfig.selfFric > 0.0) {
MMLambda_lastH.back().resize(constraintVal.size() - startCI);
//TODO: parallelize
for (int i = 0; i < MMLambda_lastH.back().size(); ++i) {
compute_g_b(constraintVal[startCI + i], dHat, MMLambda_lastH.back()[i]);
MMLambda_lastH.back()[i] *= -kappa * 2.0 * std::sqrt(constraintVal[startCI + i]);
if (MMActiveSet.back()[i][3] < -1) {
// PP or PE duplication
MMLambda_lastH.back()[i] *= -MMActiveSet.back()[i][3];
}
}
SelfCollisionHandler<dim>::computeDistCoordAndTanBasis(
result, MMActiveSet.back(), MMDistCoord.back(), MMTanBasis.back());
if (MMActiveSet_lastH.back() != MMActiveSet.back()) {
activeSetChanged = true;
MMActiveSet_lastH.back() = MMActiveSet.back();
}
}
}
timer_step.stop();
bool updateDHat = true, updateFricDHat = true;
if (constraintVal.size()) {
logFile << "d range: [" << constraintVal.minCoeff() << ", " << constraintVal.maxCoeff() << "]" << std::endl;
timer_step.start(10);
Eigen::VectorXd fb(constraintVal.size());
#ifdef USE_TBB
tbb::parallel_for(0, (int)fb.size(), 1, [&](int i)
#else
for (int i = 0; i < fb.size(); ++i)
#endif
{
double dualI;
compute_g_b(constraintVal[i], dHat, dualI);
dualI *= -kappa;
const double& constraint = constraintVal[i];
fb[i] = (dualI + constraint - std::sqrt(dualI * dualI + constraint * constraint));
}
#ifdef USE_TBB
);
#endif
double fbNorm = fb.norm();
spdlog::info("||fb|| = {:g}", fbNorm);
timer_step.stop();
if (constraintVal.maxCoeff() < fricDHatThres && fricDHat < 0.0) {
// setup friction homotopy
fricDHat = fricDHat0 * 2.0;
}
#ifdef USE_DISCRETE_CMS
if (constraintVal.maxCoeff() < dHatTarget) {
logFile << "Discrete complimentarity slackness condition satisfied" << std::endl;
updateDHat = false;
}
else if (constraintVal.minCoeff() < dTol) {
logFile << "Tiny distance fail-safe triggered" << std::endl;
break;
}
if (solveFric) {
// test on tangent space convergence
if (fricDHat <= fricDHatTarget) {
// compute gradient with updated tangent,
// if gradient still below CNTol,
// then friction tangent space has converged
#ifdef EXPORT_FRICTION_DATA
should_save_friction_data = false;
#endif
computeGradient(result, false, gradient, true);
#ifdef EXPORT_FRICTION_DATA
should_save_friction_data = true;
#endif
computePrecondMtr(result, false, linSysSolver, false, true);
if (!linSysSolver->factorize()) {
linSysSolver->precondition_diag(gradient, searchDir);
}
else {
Eigen::VectorXd minusG = -gradient;
linSysSolver->solve(minusG, searchDir);
}
if (searchDir.cwiseAbs().maxCoeff() < targetGRes) {
updateFricDHat = false;
}
if (animConfig.fricIterAmt > 0 && fricIterI >= animConfig.fricIterAmt) {
updateFricDHat = false;
}
}
}
else {
updateFricDHat = false;
}
#else // USE_DISCRETE_CMS
if (fbNorm < fbNormTol || constraintVal.minCoeff() < dTol) {
break;
}
#endif // USE_DISCRETE_CMS
}
else {
spdlog::info("no collision in this time step");
break;
}
// if (!updateDHat && !updateFricDHat && !activeSetChanged) {
if (!updateDHat && !updateFricDHat) {
break;
}
if constexpr (HOMOTOPY_VAR == 0) {
kappa *= 0.5;
spdlog::info("kappa decreased to {:g}", kappa);
}
else if (HOMOTOPY_VAR == 1) {
if (updateDHat) {
dHat *= 0.5;
if (dHat < dHatTarget) {
dHat = dHatTarget;
}
computeConstraintSets(result);
spdlog::info("dHat decreased to {:g}", dHat);
#ifdef ADAPTIVE_KAPPA
initKappa(kappa);
#endif
}
if (updateFricDHat && fricDHat > 0.0) {
fricDHat *= 0.5;
if (fricDHat < fricDHatTarget) {
fricDHat = fricDHatTarget;
}
}
}
else {
spdlog::error("needs to define HOMOTOPY_VAR to either 0 (kappa) or 1 (dHat)");
exit(-1);
}
}
for (int i = 0; i < MMActiveSet.size(); ++i) {
n_convCollPairs_sum[i] += MMActiveSet[i].size();
if (n_convCollPairs_max[i] < MMActiveSet[i].size()) {
n_convCollPairs_max[i] = MMActiveSet[i].size();
}
}
if (n_convCollPairs_total_max < constraintStartInds.back()) {
n_convCollPairs_total_max = constraintStartInds.back();
}
std::vector<double> sysE;
std::vector<Eigen::Matrix<double, 1, dim>> sysM, sysL;
computeSystemEnergy(sysE, sysM, sysL);
for (const auto& i : sysE) {
file_sysE << i << " ";
}
file_sysE << std::endl;
for (const auto& i : sysM) {
file_sysM << i << " ";
}
file_sysM << std::endl;
for (const auto& i : sysL) {
file_sysL << i << " ";
}
file_sysL << std::endl;
return false;
}
template <int dim>
bool Optimizer<dim>::solveSub_IP(double kappa, std::vector<std::vector<int>>& AHat,
std::vector<std::vector<MMCVID>>& MMAHat)
{
int iterCap = 10000, k = 0; // 10000 for running comparative schemes that can potentially not converge
m_projectDBC = true;
rho_DBC = 0.0;
double lastMove = animScripter.getCompletedStepSize();
for (; k < iterCap; ++k) {
// output constraints for debug
// Eigen::VectorXd constraintVal;
// for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
// animConfig.meshCollisionObjects[coI]->evaluateConstraints(result, MMActiveSet[coI], constraintVal);
// }
// if (animConfig.isSelfCollision) {
// SelfCollisionHandler<dim>::evaluateConstraints(result, MMActiveSet.back(), constraintVal);
// }
// std::cout << constraintStartInds.back() << " constraints:" << std::endl;
// int i = 0;
// for (const auto& coI : MMActiveSet) {
// for (const auto& cI : coI) {
// std::cout << cI[0] << " " << cI[1] << " " << cI[2] << " " << cI[3] << " " << constraintVal[i++] << std::endl;
// }
// std::cout << "-----------" << std::endl;
// }
// std::cout << "size = " << MMActiveSet.back().size() << std::endl;
// std::cout << "dHat = " << dHat << std::endl;
buildConstraintStartIndsWithMM(activeSet, MMActiveSet, constraintStartInds);
for (int i = 0; i < MMActiveSet.size(); ++i) {
n_collPairs_sum[i] += MMActiveSet[i].size();
if (n_collPairs_max[i] < MMActiveSet[i].size()) {
n_collPairs_max[i] = MMActiveSet[i].size();
}
}
if (n_collPairs_total_max < constraintStartInds.back()) {
n_collPairs_total_max = constraintStartInds.back();
}
// compute gradient
timer_step.start(12);
computeGradient(result, false, gradient, m_projectDBC);
timer_step.stop();
//TODO: constraint val can be computed and reused for E, g, H
spdlog::info("# constraint = {:d}", MMActiveSet.size() ? MMActiveSet.back().size() : 0);
spdlog::info("# paraEE = {:d}", paraEEMMCVIDSet.size() ? paraEEMMCVIDSet.back().size() : 0);
// check convergence
double gradSqNorm = gradient.squaredNorm();
double distToOpt_PN = searchDir.cwiseAbs().maxCoeff();
spdlog::info("kappa = {:g}, dHat = {:g}, eps_v = {:g}, subproblem ||g||^2 = {:g}", kappa, dHat, fricDHat, gradSqNorm);
spdlog::info("distToOpt_PN = {:g}, targetGRes = {:g}", distToOpt_PN, targetGRes);
bool gradVanish = (distToOpt_PN < targetGRes);
if (!useGD && k && gradVanish && (animScripter.getCompletedStepSize() > 1.0 - 1.0e-3)
&& (animScripter.getCOCompletedStepSize() > 1.0 - 1.0e-3)) {
// subproblem converged
logFile << k << " Newton-type iterations for kappa = " << kappa << ", dHat = " << dHat << std::endl;
return false;
}
innerIterAmt++;
computeSearchDir(k, m_projectDBC);
// largest feasible step size
timer_step.start(13);
double alpha = 1.0, slackness_a = 0.9, slackness_m = 0.8;
energyTerms[0]->filterStepSize(result, searchDir, alpha);
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
animConfig.collisionObjects[coI]->largestFeasibleStepSize(result, searchDir, slackness_a, AHat[coI], alpha);
}
#if (CFL_FOR_CCD == 0) // use full CCD
#ifdef USE_SH_LFSS
timer_temp3.start(11);
sh.build(result, searchDir, alpha, result.avgEdgeLen / 3.0);
timer_temp3.stop();
#endif
#endif
// full CCD or partial CCD
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
switch (animConfig.ccdMethod) {
case ccd::CCDMethod::FLOATING_POINT_ROOT_FINDER:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize(
result, sh, searchDir, slackness_m, MMActiveSet_CCD[coI], alpha);
break;
case ccd::CCDMethod::TIGHT_INCLUSION:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_TightInclusion(
result, sh, searchDir, animConfig.ccdTolerance, MMActiveSet_CCD[coI], alpha);
break;
default:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_exact(
result, sh, searchDir, animConfig.ccdMethod, MMActiveSet_CCD[coI], alpha);
break;
}
}
std::vector<std::pair<int, int>> newCandidates;
if (animConfig.isSelfCollision) {
switch (animConfig.ccdMethod) {
case ccd::CCDMethod::FLOATING_POINT_ROOT_FINDER:
SelfCollisionHandler<dim>::largestFeasibleStepSize(
result, sh, searchDir, slackness_m, MMActiveSet_CCD.back(), newCandidates, alpha);
break;
case ccd::CCDMethod::TIGHT_INCLUSION:
SelfCollisionHandler<dim>::largestFeasibleStepSize_TightInclusion(
result, sh, searchDir, animConfig.ccdTolerance, MMActiveSet_CCD.back(), newCandidates, alpha);
break;
default:
SelfCollisionHandler<dim>::largestFeasibleStepSize_exact(
result, sh, searchDir, animConfig.ccdMethod, MMActiveSet_CCD.back(), alpha);
break;
}
}
#if (CFL_FOR_CCD != 0) // CFL for CCD acceleration
if (MMActiveSet_CCD.size()) { // if there is mesh-mesh collision (CO or selfCollision)
Eigen::VectorXd pMag(result.SVI.size());
for (int i = 0; i < pMag.size(); ++i) {
pMag[i] = searchDir.template segment<dim>(result.SVI[i] * dim).norm();
}
double alpha_CFL = std::sqrt(dHat) / (pMag.maxCoeff() * 2.0);
spdlog::info("partial CCD {:g}, CFL {:g}", alpha, alpha_CFL);
if constexpr (CFL_FOR_CCD == 1) {
alpha = std::min(alpha, alpha_CFL);
spdlog::info("take the smaller one {:g}", alpha);
}
else if (CFL_FOR_CCD == 2) {
if ((!k && alpha > alpha_CFL) || alpha > 2.0 * alpha_CFL) {
// full CCD
#ifdef USE_SH_LFSS
timer_temp3.start(11);
sh.build(result, searchDir, alpha, result.avgEdgeLen / 3.0);
timer_temp3.stop();
#endif
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
switch (animConfig.ccdMethod) {
case ccd::CCDMethod::FLOATING_POINT_ROOT_FINDER:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_CCD(
result, sh, searchDir, slackness_m, alpha);
break;
case ccd::CCDMethod::TIGHT_INCLUSION:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_CCD_TightInclusion(
result, sh, searchDir, animConfig.ccdTolerance, alpha);
break;
default:
animConfig.meshCollisionObjects[coI]->largestFeasibleStepSize_CCD_exact(
result, sh, searchDir, animConfig.ccdMethod, alpha);
}
}
if (animConfig.isSelfCollision) {
switch (animConfig.ccdMethod) {
case ccd::CCDMethod::FLOATING_POINT_ROOT_FINDER:
SelfCollisionHandler<dim>::largestFeasibleStepSize_CCD(
result, sh, searchDir, slackness_m, newCandidates, alpha);
break;
case ccd::CCDMethod::TIGHT_INCLUSION:
SelfCollisionHandler<dim>::largestFeasibleStepSize_CCD_TightInclusion(
result, sh, searchDir, animConfig.ccdTolerance, newCandidates, alpha);
break;
default:
SelfCollisionHandler<dim>::largestFeasibleStepSize_CCD_exact(
result, sh, searchDir, animConfig.ccdMethod, alpha);
}
}
if (alpha < alpha_CFL) {
alpha = alpha_CFL;
spdlog::info("take a full CCD instead but failed, take CFL {:g}", alpha);
}
else {
spdlog::info("take a full CCD instead {:g}", alpha);
}
}
else {
alpha = std::min(alpha, alpha_CFL);
spdlog::info("take the smaller one {:g}", alpha);
}
}
}
#endif
// double largestFeasibleStepSize = alpha;
if (alpha == 0.0) {
spdlog::error("CCD gives 0 step size");
exit(-1);
alpha = 1.0; // fail-safe, let safe-guard in line search find the stepsize
}
else {
spdlog::info("stepsize={:g}", alpha);
}
timer_step.stop();
file_iterStats << globalIterNum << " ";
// Eigen::MatrixXd Vlast = result.V;
double alpha_feasible = alpha;
#ifdef SAVE_EXTREME_LINESEARCH_CCD
if (alpha_feasible < 0.25) {
static int count = 0;
Eigen::MatrixXd V0 = result.V;
result.saveSurfaceMesh(fmt::format("{}lineSearch-{:05d}-t0.obj", outputFolderPath, count));
stepForward(V0, result, alpha_feasible);
result.saveSurfaceMesh(fmt::format("{}lineSearch-{:05d}-tα={:g}.obj", outputFolderPath, count, alpha_feasible));
stepForward(V0, result, 1);
result.saveSurfaceMesh(fmt::format("{}lineSearch-{:05d}-t1.obj", outputFolderPath, count));
result.V = V0;
count++;
}
#endif
lineSearch(alpha);
if (alpha_feasible < 1.0e-8) {
logFile << "tiny feasible step size " << alpha_feasible << " " << alpha << std::endl;
}
else if (alpha < 1.0e-8) {
logFile << "tiny step size after armijo " << alpha_feasible << " " << alpha << std::endl;
}
#ifdef LINSYSSOLVER_USE_AMGCL
if (alpha < 1.0e-8) { // only for debugging tiny step size issue
// output system in AMGCL format
// Eigen::VectorXd minusG = -gradient;
// dynamic_cast<AMGCLSolver<Eigen::VectorXi, Eigen::VectorXd>*>(linSysSolver)->write_AMGCL("Stiff", minusG);
// exit(-1);
#else
if (false) {
#endif
// tiny step size issue
// if (useGD) {
// MMCVID i = paraEEMMCVIDSet.back()[0];
// for (int j = 0; j < 4; ++j) {
// printf("%.20le %.20le %.20le\n",
// Vlast(i[j], 0), Vlast(i[j], 1), Vlast(i[j], 2));
// }
// for (int j = 0; j < 4; ++j) {
// printf("%.20le %.20le %.20le\n",
// searchDir[i[j] * dim], searchDir[i[j] * dim + 1], searchDir[i[j] * dim + 2]);
// }
// FILE* out = fopen((outputFolderPath + "E.txt").c_str(), "w");
// for (int i = -1000; i < 1000; ++i) {
// stepForward(Vlast, result, i / 1000.0 * largestFeasibleStepSize);
// double E;
// computeConstraintSets(result);
// computeEnergyVal(result, true, E);
// fprintf(out, "%.20le %.20le %.20le %.20le %.20le %.20le\n", i / 1000.0 * largestFeasibleStepSize,
// energies[0], energies[1], energies[2], energies[3], E);
// if (i == -1) {
// for (int j = -999; j < 0; ++j) {
// stepForward(Vlast, result, j / 1000000.0 * largestFeasibleStepSize);
// double E;
// computeConstraintSets(result);
// computeEnergyVal(result, true, E);
// fprintf(out, "%.20le %.20le %.20le %.20le %.20le %.20le\n", j / 1000000.0 * largestFeasibleStepSize,
// energies[0], energies[1], energies[2], energies[3], E);
// if (j > -15) {
// std::cout << "j=" << j << std::endl;
// for (const auto& i : MMActiveSet.back()) {
// std::cout << i[0] << " " << i[1] << " " << i[2] << " " << i[3] << std::endl;
// }
// }
// }
// }
// else if (i == 0) {
// for (int j = 1; j < 1000; ++j) {
// stepForward(Vlast, result, j / 1000000.0 * largestFeasibleStepSize);
// double E;
// computeConstraintSets(result);
// computeEnergyVal(result, true, E);
// fprintf(out, "%.20le %.20le %.20le %.20le %.20le %.20le\n", j / 1000000.0 * largestFeasibleStepSize,
// energies[0], energies[1], energies[2], energies[3], E);
// if (j < 15) {
// std::cout << "j=" << j << std::endl;
// for (const auto& i : MMActiveSet.back()) {
// std::cout << i[0] << " " << i[1] << " " << i[2] << " " << i[3] << std::endl;
// }
// }
// }
// }
// }
// fclose(out);
// exit(0);
// }
saveStatus("tinyStepSize");
useGD = true;
// // kappa *= 1.1;
// if constexpr (dim == 3) {
// spdlog::info("check EE pairs:");
// for (const auto cI : MMActiveSet.back()) {
// if (cI[0] >= 0) { // EE
// const Eigen::Matrix<double, 1, dim> e01 = result.V.row(cI[1]) - result.V.row(cI[0]);
// const Eigen::Matrix<double, 1, dim> e23 = result.V.row(cI[3]) - result.V.row(cI[2]);
// double sine = std::sqrt(e01.cross(e23).squaredNorm() / (e01.squaredNorm() * e23.squaredNorm()));
// if (sine < 0.02) {
// spdlog::info("{:d}-{:d} {:d}-{:d} sine = {:g}", cI[0], cI[1], cI[2], cI[3], sine);
// }
// }
// }
// spdlog::info("cosine p g = {:g}", searchDir.dot(gradient) / std::sqrt(searchDir.squaredNorm() * gradient.squaredNorm()));
// }
}
else {
useGD = false;
}
#ifdef CHECK_ET_INTERSECTION
bool intersected = false;
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
intersected |= !animConfig.meshCollisionObjects[coI]->checkEdgeTriIntersection(result, sh);
}
if (animConfig.isSelfCollision) {
intersected |= !SelfCollisionHandler<dim>::checkEdgeTriIntersection(result, sh);
}
if (intersected) {
getchar();
}
#endif
postLineSearch(alpha);
file_iterStats << constraintStartInds.back() << std::endl;
if (m_projectDBC) {
if (animScripter.getCompletedStepSize() < 1.0 - 1.0e-3) {
// setup KKT solving option
m_projectDBC = false;
rho_DBC = 1.0e6;
spdlog::info("setup penalty solve");
}
}
else {
double completedStepSize = animScripter.computeCompletedStepSize(result);
spdlog::info("completed step size of MBC = {:g}", completedStepSize);
if (completedStepSize > 1.0 - 1.0e-3) {
m_projectDBC = true;
spdlog::info("penalty solve finished");
}
else {
if (completedStepSize < lastMove && rho_DBC < 1.0e8) {
rho_DBC *= 2.0;
spdlog::info("set rho_DBC to {:g}", rho_DBC);
}
else {
bool safeToPull = (searchDir.cwiseAbs().maxCoeff() < CN_MBC);
if (safeToPull) {
if (completedStepSize < 0.99 && rho_DBC < 1.0e8) {
rho_DBC *= 2.0;
spdlog::info("set rho_DBC to {:g}", rho_DBC);
}
else {
animScripter.updateLambda(result, rho_DBC);
//TODO: use second order dual update
spdlog::info("MBC lambda updated with rho_DBC = {:g}", rho_DBC);
}
}
}
}
}
}
if (k >= iterCap) {
logFile << "iteration cap reached for IP subproblem solve!!!" << std::endl;
exit(0); // for stopping comparative schemes that can potentially not converge
}
return true;
}
template <int dim>
void Optimizer<dim>::upperBoundKappa(double& kappa)
{
double H_b;
compute_H_b(1.0e-16 * bboxDiagSize2, dHat, H_b);
double kappaMax = 100 * animConfig.kappaMinMultiplier * result.avgNodeMass(dim) / (4.0e-16 * bboxDiagSize2 * H_b);
if (kappa > kappaMax) {
kappa = kappaMax;
logFile << "upper bounded kappa to " << kappaMax << " at dHat = " << dHat << std::endl;
}
}
template <int dim>
void Optimizer<dim>::suggestKappa(double& kappa)
{
double H_b;
compute_H_b(1.0e-16 * bboxDiagSize2, dHat, H_b);
kappa = animConfig.kappaMinMultiplier * result.avgNodeMass(dim) / (4.0e-16 * bboxDiagSize2 * H_b);
}
template <int dim>
void Optimizer<dim>::initKappa(double& kappa)
{
//TODO: optimize implementation and pipeline
buildConstraintStartIndsWithMM(activeSet, MMActiveSet, constraintStartInds);
if (constraintStartInds.back()) {
Eigen::VectorXd g_E;
solveIP = false;
computeGradient(result, true, g_E);
solveIP = true;
Eigen::VectorXd constraintVal, g_c;
g_c.setZero(g_E.size());
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
animConfig.collisionObjects[coI]->evaluateConstraints(result, activeSet[coI], constraintVal);
int startCI = constraintStartInds[coI];
for (int cI = startCI; cI < constraintStartInds[coI + 1]; ++cI) {
compute_g_b(constraintVal[cI], dHat, constraintVal[cI]);
}
animConfig.collisionObjects[coI]->leftMultiplyConstraintJacobianT(result, activeSet[coI],
constraintVal.segment(startCI, activeSet[coI].size()), g_c);
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
animConfig.meshCollisionObjects[coI]->evaluateConstraints(result, MMActiveSet[coI], constraintVal);
int startCI = constraintStartInds[coI + animConfig.collisionObjects.size()];
for (int cI = startCI; cI < constraintStartInds[coI + 1 + animConfig.collisionObjects.size()]; ++cI) {
compute_g_b(constraintVal[cI], dHat, constraintVal[cI]);
}
animConfig.meshCollisionObjects[coI]->leftMultiplyConstraintJacobianT(result, MMActiveSet[coI],
constraintVal.segment(startCI, MMActiveSet[coI].size()), g_c);
}
if (animConfig.isSelfCollision) {
SelfCollisionHandler<dim>::evaluateConstraints(result, MMActiveSet.back(), constraintVal);
int startCI = constraintStartInds[animConfig.meshCollisionObjects.size() + animConfig.collisionObjects.size()];
for (int cI = startCI; cI < constraintVal.size(); ++cI) {
compute_g_b(constraintVal[cI], dHat, constraintVal[cI]);
}
SelfCollisionHandler<dim>::leftMultiplyConstraintJacobianT(result, MMActiveSet.back(),
constraintVal.segment(startCI, MMActiveSet.back().size()), g_c);
}
for (const auto& fixedVI : result.fixedVert) {
g_c.segment<dim>(fixedVI * dim).setZero();
}
// balance current gradient at constrained DOF
double minKappa = -g_c.dot(g_E) / g_c.squaredNorm();
if (minKappa > 0.0) {
kappa = minKappa;
}
suggestKappa(minKappa);
spdlog::info("kappa_min = {:g} kappa_max = {:g}", minKappa, 100 * minKappa);
if (kappa < minKappa) {
kappa = minKappa;
}
upperBoundKappa(kappa);
// minimize approximated next search direction
// Eigen::VectorXd HInvGc, HInvGE;
// linSysSolver->solve(g_c, HInvGc);
// linSysSolver->solve(g_E, HInvGE);
// kappa = HInvGE.dot(HInvGc) / HInvGc.squaredNorm();
// if(kappa < 0.0) {
// kappa = g_c.dot(g_E) / g_c.squaredNorm();
// }
// minimize approximated next search direction at constrained DOF
// Eigen::VectorXd HInvGc;
// linSysSolver->solve(g_c, HInvGc);
// kappa = g_E.dot(HInvGc) / g_c.dot(HInvGc);
// if(kappa < 0.0) {
// kappa = g_c.dot(g_E) / g_c.squaredNorm();
// }
spdlog::info("kappa initialized to {:g}", kappa);
}
else {
spdlog::info("no constraint detected, start with default kappa");
}
}
template <int dim>
void Optimizer<dim>::initSubProb_IP(void)
{
closeConstraintID.resize(0);
closeMConstraintID.resize(0);
closeConstraintVal.resize(0);
closeMConstraintVal.resize(0);
}
template <int dim>
void Optimizer<dim>::computeSearchDir(int k, bool projectDBC)
{
// compute matrix
computePrecondMtr(result, false, linSysSolver, false, projectDBC);
timer_step.start(3);
Eigen::VectorXd minusG = -gradient;
if (useGD || !linSysSolver->factorize()) {
if (!useGD) {
spdlog::warn("matrix not positive definite");
logFile << "matrix not positive definite" << std::endl;
}
// std::cout << "writing it to disk for debug..." << std::endl;
// IglUtils::writeSparseMatrixToFile(outputFolderPath + "H_IP", linSysSolver, true);
// std::cout << "writing complete, terminate program" << std::endl;
// exit(0);
spdlog::warn("use diagonal preconditioned -gradient direction");
logFile << "use diagonal preconditioned -gradient direction" << std::endl;
timer_step.start(4);
linSysSolver->precondition_diag(minusG, searchDir);
// searchDir = minusG;
timer_step.stop();
}
else {
// solve for searchDir
timer_step.start(4);
linSysSolver->solve(minusG, searchDir);
timer_step.stop();
}
}
template <int dim>
void Optimizer<dim>::postLineSearch(double alpha)
{
#ifdef ADAPTIVE_KAPPA
if (kappa == 0.0) {
initKappa(kappa);
}
else {
//TODO: avoid recomputation of constraint functions
bool updateKappa = false;
for (int i = 0; i < closeConstraintID.size(); ++i) {
double d;
animConfig.collisionObjects[closeConstraintID[i].first]->evaluateConstraint(result,
closeConstraintID[i].second, d);
if (d <= closeConstraintVal[i]) {
updateKappa = true;
break;
}
}
if (!updateKappa) {
for (int i = 0; i < closeMConstraintID.size(); ++i) {
double d;
if (closeMConstraintID[i].first < animConfig.meshCollisionObjects.size()) {
animConfig.meshCollisionObjects[closeMConstraintID[i].first]->evaluateConstraint(result,
closeMConstraintID[i].second, d);
}
else {
SelfCollisionHandler<dim>::evaluateConstraint(result, closeMConstraintID[i].second, d);
}
if (d <= closeMConstraintVal[i]) {
updateKappa = true;
break;
}
}
}
if (updateKappa) {
kappa *= 2.0;
upperBoundKappa(kappa);
}
#endif
#ifdef ADAPTIVE_KAPPA
closeConstraintID.resize(0);
closeMConstraintID.resize(0);
closeConstraintVal.resize(0);
closeMConstraintVal.resize(0);
Eigen::VectorXd constraintVal;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
int constraintValIndStart = constraintVal.size();
animConfig.collisionObjects[coI]->evaluateConstraints(result,
activeSet[coI], constraintVal);
for (int i = 0; i < activeSet[coI].size(); ++i) {
if (constraintVal[constraintValIndStart + i] < dTol) {
closeConstraintID.emplace_back(coI, activeSet[coI][i]);
closeConstraintVal.emplace_back(constraintVal[constraintValIndStart + i]);
}
}
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
int constraintValIndStart = constraintVal.size();
animConfig.meshCollisionObjects[coI]->evaluateConstraints(result,
MMActiveSet[coI], constraintVal);
for (int i = 0; i < MMActiveSet[coI].size(); ++i) {
// std::cout << MMActiveSet[coI][i][0] << " " << MMActiveSet[coI][i][1] << " " << MMActiveSet[coI][i][2] << " " << MMActiveSet[coI][i][3] << ", d=" << constraintVal[constraintValIndStart + i] << std::endl;
if (constraintVal[constraintValIndStart + i] < dTol) {
closeMConstraintID.emplace_back(coI, MMActiveSet[coI][i]);
closeMConstraintVal.emplace_back(constraintVal[constraintValIndStart + i]);
}
}
}
if (animConfig.isSelfCollision) {
int constraintValIndStart = constraintVal.size();
SelfCollisionHandler<dim>::evaluateConstraints(result, MMActiveSet.back(), constraintVal);
for (int i = 0; i < MMActiveSet.back().size(); ++i) {
// std::cout << MMActiveSet.back()[i][0] << " " << MMActiveSet.back()[i][1] << " " << MMActiveSet.back()[i][2] << " " << MMActiveSet.back()[i][3] << ", d=" << constraintVal[constraintValIndStart + i] << std::endl;
if (constraintVal[constraintValIndStart + i] < dTol) {
closeMConstraintID.emplace_back(MMActiveSet.size() - 1, MMActiveSet.back()[i]);
closeMConstraintVal.emplace_back(constraintVal[constraintValIndStart + i]);
}
}
}
if (constraintVal.size()) {
spdlog::info("min distance^2 = {:g}", constraintVal.minCoeff());
}
}
#endif
}
template <int dim>
void Optimizer<dim>::computeConstraintSets(const Mesh<dim>& data, bool rehash)
{
timer_step.start(14);
#ifndef CCD_FILTERED_CS
#ifdef USE_SH_CCS
if (rehash) {
timer_temp3.start(7);
sh.build(data, data.avgEdgeLen / 3.0);
timer_temp3.stop();
}
#endif
#endif
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
animConfig.collisionObjects[coI]->computeConstraintSet(data, dHat, activeSet[coI]);
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
animConfig.meshCollisionObjects[coI]->computeConstraintSet(data, sh, dHat, MMActiveSet[coI], paraEEMMCVIDSet[coI], paraEEeIeJSet[coI], CFL_FOR_CCD, MMActiveSet_CCD[coI]);
}
if (animConfig.isSelfCollision) {
SelfCollisionHandler<dim>::computeConstraintSet(data, sh, dHat, MMActiveSet.back(), paraEEMMCVIDSet.back(), paraEEeIeJSet.back(), CFL_FOR_CCD, MMActiveSet_CCD.back());
}
timer_step.stop();
}
template <int dim>
void Optimizer<dim>::buildConstraintStartInds(const std::vector<std::vector<int>>& activeSet,
std::vector<int>& constraintStartInds)
{
constraintStartInds.resize(1);
constraintStartInds[0] = 0;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
constraintStartInds.emplace_back(constraintStartInds.back() + activeSet[coI].size());
}
}
template <int dim>
void Optimizer<dim>::buildConstraintStartIndsWithMM(const std::vector<std::vector<int>>& activeSet,
const std::vector<std::vector<MMCVID>>& MMActiveSet,
std::vector<int>& constraintStartInds)
{
constraintStartInds.resize(1);
constraintStartInds[0] = 0;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
constraintStartInds.emplace_back(constraintStartInds.back() + activeSet[coI].size());
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
constraintStartInds.emplace_back(constraintStartInds.back() + MMActiveSet[coI].size());
}
if (animConfig.isSelfCollision) {
constraintStartInds.emplace_back(constraintStartInds.back() + MMActiveSet.back().size());
}
}
template <int dim>
bool Optimizer<dim>::solve_oneStep(void)
{
if (!solveWithQP) {
// for the changing hessian
// Update matrix entries
computePrecondMtr(result, false, linSysSolver);
try {
// Numerically factorizing Hessian/Proxy matrix
if (!mute) { timer_step.start(3); }
if (!solveWithSQP) {
linSysSolver->factorize();
// output factorization and exit
// linSysSolver->outputFactorization("/Users/mincli/Desktop/test/IPC/output/L");
// std::cout << "matrix written" << std::endl;
// exit(0);
}
if (!mute) { timer_step.stop(); }
}
catch (std::exception e) {
IglUtils::writeSparseMatrixToFile(outputFolderPath + "mtr_numFacFail",
linSysSolver, true);
spdlog::error("numerical factorization failed, matrix written into {}mtr_numFacFail", outputFolderPath);
exit(-1);
}
}
// Back solve
if (!mute) { timer_step.start(4); }
if (solveWithQP || solveWithSQP) {
#ifdef EXIT_UPON_QP_FAIL
bool prevQPsuccess = solveQPSuccess;
#endif
solveQPSuccess = solveQP(
result, animConfig.collisionObjects, activeSet,
linSysSolver, P_QP, elemPtr_P_QP, gradient,
OSQPSolver,
#ifdef USE_GUROBI
gurobiQPSolver,
#endif
constraintStartInds, searchDir, dual_QP,
animConfig.qpSolverType);
#ifdef USE_GUROBI
if (animConfig.qpSolverType == QP_GUROBI) {
if (solveQPSuccess) {
spdlog::debug(
"timestep={:d} Gurobi_status={:d} description=\"{:s}\"",
globalIterNum, gurobiQPSolver.status(), gurobiQPSolver.statusDescription());
}
else {
spdlog::error(
"timestep={:d} Gurobi_status={:d} description=\"{:s}\"",
globalIterNum, gurobiQPSolver.status(), gurobiQPSolver.statusDescription());
}
}
#endif
if (!solveQPSuccess) {
#ifdef EXIT_UPON_QP_FAIL
if (!prevQPsuccess) {
spdlog::error(
"timestep={:d} msg=\"unable to solve QP for two successive iterations; exiting\"",
globalIterNum);
exit(3);
}
#endif
spdlog::error("timestep={:d} msg=\"unable to solve QP; resetting active set\"", globalIterNum);
searchDir.setZero(gradient.size());
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
activeSet_next[coI].clear();
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
MMActiveSet_next[coI].clear();
}
if (animConfig.isSelfCollision) {
MMActiveSet_next.back().clear();
}
}
}
else {
Eigen::VectorXd minusG = -gradient;
linSysSolver->solve(minusG, searchDir);
}
if (!mute) { timer_step.stop(); }
double stepSize;
bool stopped;
if (solveWithQP || solveWithSQP) {
// stopped = lineSearch(stepSize);
stepSize = 1.0;
Eigen::MatrixXd resultV0 = result.V;
if (animConfig.energyType == ET_NH) {
// Line search to prevent element inversions
stopped = true; // Fail until a valid stepSize is found
energyTerms[0]->filterStepSize(result, searchDir, stepSize);
while (stepSize > 0) {
stepSize /= 2.0;
stepForward(resultV0, result, stepSize);
if (result.checkInversion(true)) {
// No inversions found
stopped = false;
break;
}
}
}
else {
stopped = false;
stepForward(resultV0, result, stepSize);
}
}
else {
stopped = lineSearch(stepSize); // Also takes the step
}
if (stopped) {
// IglUtils::writeSparseMatrixToFile(outputFolderPath + "precondMtr_stopped_" + std::to_string(globalIterNum), precondMtr);
// logFile << "descent step stopped at overallIter" << globalIterNum << " for no prominent energy decrease." << std::endl;
}
if (!solveWithQP) { // Do not update the gradient for a single QP
computeGradient(result, false, gradient);
}
return stopped;
}
template <int dim>
bool isIntersected(
const Mesh<dim>& mesh,
const SpatialHash<dim>& sh,
const Eigen::MatrixXd& V0,
const Config& p_animConfig)
{
#ifdef NO_CCD_FAILSAFE
return false;
#endif
for (const auto& obj : p_animConfig.collisionObjects) {
if (obj->isIntersected(mesh, V0)) {
logFile << "mesh intersects with analytical collision object" << std::endl;
return true;
}
}
for (int coI = 0; coI < p_animConfig.meshCollisionObjects.size(); ++coI) {
if (!p_animConfig.meshCollisionObjects[coI]->checkEdgeTriIntersectionIfAny(mesh, sh)) {
logFile << "mesh intersects with mesh collision object" << std::endl;
return true;
}
}
if (p_animConfig.isSelfCollision) {
if (!SelfCollisionHandler<dim>::checkEdgeTriIntersectionIfAny(mesh, sh)) {
logFile << "mesh intersects with itself" << std::endl;
return true;
}
}
return false;
}
template <int dim>
bool Optimizer<dim>::lineSearch(double& stepSize,
double armijoParam,
double lowerBound)
{
timer_step.start(5);
std::stringstream msg;
bool outputLineSearch = false;
if (outputLineSearch) {
result.saveAsMesh(outputFolderPath + ((dim == 2) ? "lineSearchBase.obj" : "lineSearchBase.msh"));
}
bool stopped = false;
if (!solveIP) {
initStepSize(result, stepSize);
}
else {
timer_step.start(9);
computeEnergyVal(result, false, lastEnergyVal); //TODO: only for updated constraints set and kappa
timer_step.start(5);
}
msg << "E_last = " << lastEnergyVal << " stepSize: " << stepSize << " -> ";
// const double m = searchDir.dot(gradient);
// const double c1m = 1.0e-4 * m;
double c1m = 0.0;
if (armijoParam > 0.0) {
c1m = armijoParam * searchDir.dot(gradient);
}
Eigen::MatrixXd resultV0 = result.V;
// Mesh<dim> temp = result; // TEST
if (outputLineSearch) {
Eigen::VectorXd energyValPerElem;
energyTerms[0]->getEnergyValPerElemBySVD(result, false, svd, F,
energyValPerElem, false);
IglUtils::writeVectorToFile(outputFolderPath + "E0.txt", energyValPerElem);
}
#ifdef OUTPUT_CCD_FAIL
bool output = false;
if (solveIP && animConfig.ccdMethod != ccd::CCDMethod::FLOATING_POINT_ROOT_FINDER) {
result.saveSurfaceMesh(outputFolderPath + "before" + std::to_string(numOfCCDFail) + ".obj");
output = true;
}
#endif
stepForward(resultV0, result, stepSize);
if (energyTerms[0]->getNeedElemInvSafeGuard()) {
while (!result.checkInversion(true)) {
logFile << "element inversion detected during line search, backtrack!" << std::endl;
stepSize /= 2.0;
stepForward(resultV0, result, stepSize);
}
msg << stepSize << "(safeGuard) -> ";
}
bool rehash = true;
if (solveIP) {
sh.build(result, result.avgEdgeLen / 3.0);
while (isIntersected(result, sh, resultV0, animConfig)) {
logFile << "intersection detected during line search, backtrack!" << std::endl;
#ifdef OUTPUT_CCD_FAIL
if (output) {
result.saveSurfaceMesh(outputFolderPath + "after" + std::to_string(numOfCCDFail) + ".obj");
++numOfCCDFail;
output = false;
}
#endif
stepSize /= 2.0;
stepForward(resultV0, result, stepSize);
sh.build(result, result.avgEdgeLen / 3.0);
}
msg << stepSize << "(safeGuard_IP) -> ";
rehash = false;
}
double testingE;
// Eigen::VectorXd testingG;
timer_step.stop();
if (solveIP) {
computeConstraintSets(result, rehash);
}
timer_step.start(9);
computeEnergyVal(result, 2, testingE);
timer_step.start(5);
// computeGradient(testingData, testingG);
if (outputLineSearch) {
Eigen::VectorXd energyValPerElem;
energyTerms[0]->getEnergyValPerElemBySVD(result, false, svd, F,
energyValPerElem, false);
IglUtils::writeVectorToFile(outputFolderPath + "E.txt", energyValPerElem);
}
#define ARMIJO_RULE
#ifdef ARMIJO_RULE
// while((testingE > lastEnergyVal + stepSize * c1m) ||
// (searchDir.dot(testingG) < c2m)) // Wolfe condition
// FILE* out = fopen((outputFolderPath + "Els.txt").c_str(), "w");
double LFStepSize = stepSize;
while ((testingE > lastEnergyVal + stepSize * c1m) && // Armijo condition
(stepSize > lowerBound)) {
// fprintf(out, "%.9le %.9le\n", stepSize, testingE);
if (stepSize == 1.0) {
// can try cubic interpolation here
stepSize /= 2.0;
}
else {
stepSize /= 2.0;
}
++numOfLineSearch;
if (stepSize == 0.0) {
stopped = true;
if (!mute) {
logFile << "testingE" << globalIterNum << " " << testingE << " > " << lastEnergyVal << " " << stepSize * c1m << std::endl;
// logFile << "testingG" << globalIterNum << " " << searchDir.dot(testingG) << " < " << c2m << std::endl;
}
break;
}
stepForward(resultV0, result, stepSize);
// while (isIntersected(result, resultV0, animConfig)) {
// stepSize /= 2.0;
// stepForward(resultV0, result, stepSize);
// }
msg << stepSize << " -> ";
timer_step.stop();
if (solveIP) {
computeConstraintSets(result);
}
timer_step.start(9);
computeEnergyVal(result, 2, testingE);
timer_step.start(5);
// computeGradient(testingData, testingG);
}
if (stepSize < LFStepSize && solveIP) {
bool needRecomputeCS = false;
while (isIntersected(result, sh, resultV0, animConfig)) {
logFile << "intersection detected after line search, backtrack!" << std::endl;
stepSize /= 2.0;
stepForward(resultV0, result, stepSize);
sh.build(result, result.avgEdgeLen / 3.0);
needRecomputeCS = true;
}
if (needRecomputeCS) {
computeConstraintSets(result, false);
}
}
#ifdef CHECK_RATIONAL_CCD_GLOBAL
Eigen::MatrixXd V_bk = result.V;
result.V = resultV0;
sh.build(result, searchDir, stepSize, result.avgEdgeLen / 3.0);
double stepSize_rational = stepSize;
SelfCollisionHandler<dim>::largestFeasibleStepSize_CCD_exact(result, sh, searchDir, ccd::CCDMethod::RATIONAL_ROOT_PARITY, stepSize_rational);
if (stepSize_rational != stepSize) {
std::cout << "rational CCD detects interpenetration but inexact didn't" << std::endl;
}
result.V = V_bk;
#endif
// fclose(out);
#endif
// // further search
// double stepSize_fs = stepSize / 2.0;
// stepForward(resultV0, result, stepSize_fs);
// double E_fs;
// timer_step.stop();
// computeConstraintSets(result);
// timer_step.start(9);
// computeEnergyVal(result, 2, E_fs);
// timer_step.start(5);
// while (E_fs < testingE) {
// testingE = E_fs;
// stepSize_fs /= 2.0;
// stepForward(resultV0, result, stepSize_fs);
// timer_step.stop();
// computeConstraintSets(result);
// timer_step.start(9);
// computeEnergyVal(result, 2, E_fs);
// timer_step.start(5);
// }
// stepForward(resultV0, result, stepSize_fs * 2.0);
// timer_step.stop();
// computeConstraintSets(result);
// timer_step.start(9);
// computeEnergyVal(result, 2, testingE);
// timer_step.start(5);
msg << stepSize << "(armijo) ";
// if (energyTerms[0]->getNeedElemInvSafeGuard()) {
// if (!result.checkInversion(true)) {
// logFile << "element inversion detected after line search, backtrack!" << std::endl;
// stepSize /= 2.0;
// stepForward(resultV0, result, stepSize);
// }
// }
// if (solveIP) {
// while (isIntersected(result, sh, resultV0, animConfig)) {
// logFile << "intersection detected after line search, backtrack!" << std::endl;
// stepSize /= 2.0;
// stepForward(resultV0, result, stepSize);
// sh.build(result, result.avgEdgeLen / 3.0);
// }
// }
// while((!result.checkInversion()) ||
// ((scaffolding) && (!scaffold.airMesh.checkInversion())))
// {
// assert(0 && "element inversion after armijo shouldn't happen!");
//
// stepSize /= 2.0;
// if(stepSize == 0.0) {
// assert(0 && "line search failed!");
// stopped = true;
// break;
// }
//
// stepForward(resultV0, scaffoldV0, result, scaffold, stepSize);
// computeEnergyVal(result, scaffold, testingE);
// }
//
// // projection method for collision handling
// for(int vI = 0; vI < result.V.rows(); vI++) {
// if(result.V(vI, 1) < 0.0) {
// result.V(vI, 1) = 0.0;
// }
// }
// computeEnergyVal(result, scaffold, true, testingE);
lastEnergyVal = testingE;
if (!mute) {
msg << stepSize << " (E = " << testingE << ")";
spdlog::info("{:s}", msg.str());
spdlog::info("stepLen = {:g}", (stepSize * searchDir).squaredNorm());
}
file_iterStats << stepSize << " ";
if (outputLineSearch) {
IglUtils::writeVectorToFile(outputFolderPath + "searchDir.txt",
searchDir);
exit(0);
}
timer_step.stop();
return stopped;
}
template <int dim>
void Optimizer<dim>::stepForward(const Eigen::MatrixXd& dataV0,
Mesh<dim>& data,
double stepSize) const
{
assert(dataV0.rows() == data.V.rows());
assert(data.V.rows() * dim == searchDir.size());
assert(data.V.rows() == result.V.rows());
#ifdef USE_TBB
tbb::parallel_for(0, (int)data.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < data.V.rows(); vI++)
#endif
{
data.V.row(vI) = dataV0.row(vI) + stepSize * searchDir.segment<dim>(vI * dim).transpose();
}
#ifdef USE_TBB
);
#endif
}
template <int dim>
void Optimizer<dim>::updateTargetGRes(void)
{
targetGRes = std::sqrt(relGL2Tol * bboxDiagSize2 * dtSq);
}
template <int dim>
void Optimizer<dim>::getFaceFieldForVis(Eigen::VectorXd& field)
{
// field = Eigen::VectorXd::Zero(result.F.rows());
field = result.u;
}
template <int dim>
void Optimizer<dim>::initStepSize(const Mesh<dim>& data, double& stepSize)
{
stepSize = 1.0;
for (int eI = 0; eI < energyTerms.size(); eI++) {
energyTerms[eI]->filterStepSize(data, searchDir, stepSize);
}
}
template <int dim>
void Optimizer<dim>::saveStatus(const std::string& appendStr)
{
std::string status_fname = fmt::format("{}status{:d}{}", outputFolderPath, globalIterNum, appendStr);
std::ofstream status(status_fname, std::ios::out);
if (status.is_open()) {
// status << std::hexfloat;
status << std::setprecision(std::numeric_limits<long double>::digits10 + 2);
status << "timestep " << globalIterNum << "\n\n";
status << "position " << result.V.rows() << " " << result.V.cols() << "\n";
for (int vI = 0; vI < result.V.rows(); ++vI) {
status << result.V(vI, 0) << " " << result.V(vI, 1);
if constexpr (dim == 3) {
status << " " << result.V(vI, 2);
}
status << "\n";
}
status << "\n";
status << "velocity " << velocity.size() << "\n";
for (int velI = 0; velI < velocity.size(); ++velI) {
status << velocity[velI] << "\n";
}
status << "\n";
status << "acceleration " << acceleration.rows() << " " << dim << "\n";
for (int accI = 0; accI < acceleration.rows(); ++accI) {
status << acceleration(accI, 0) << " " << acceleration(accI, 1);
if constexpr (dim == 3) {
status << " " << acceleration(accI, 2);
}
status << "\n";
}
status << "\n";
status << "dx_Elastic " << dx_Elastic.rows() << " " << dim << "\n";
for (int velI = 0; velI < dx_Elastic.rows(); ++velI) {
status << dx_Elastic(velI, 0) << " " << dx_Elastic(velI, 1);
if constexpr (dim == 3) {
status << " " << dx_Elastic(velI, 2);
}
status << "\n";
}
status.close();
}
else {
spdlog::error("Unable to create status file ({})!", status_fname);
}
// surface mesh, including codimensional surface CO
#ifdef USE_TBB
tbb::parallel_for(0, (int)V_surf.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < V_surf.rows(); ++vI)
#endif
{
V_surf.row(vI) = result.V.row(surfIndToTet[vI]);
}
#ifdef USE_TBB
);
#endif
igl::writeOBJ(outputFolderPath + std::to_string(globalIterNum) + ".obj", V_surf.rowwise() + invShift.transpose(), F_surf);
// codimensional segment CO
if (result.CE.rows()) {
#ifdef USE_TBB
tbb::parallel_for(0, (int)V_CE.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < V_CE.rows(); ++vI)
#endif
{
V_CE.row(vI) = result.V.row(CEIndToTet[vI]);
}
#ifdef USE_TBB
);
#endif
IglUtils::writeSEG(outputFolderPath + std::to_string(globalIterNum) + ".seg",
V_CE, F_CE);
}
// codimensional point CO
bool hasPointCO = false;
for (const auto& coDimI : result.componentCoDim) {
if (coDimI == 0) {
hasPointCO = true;
break;
}
}
if (hasPointCO) {
FILE* out = fopen((outputFolderPath + "pt" + std::to_string(globalIterNum) + ".obj").c_str(), "w");
for (int compI = 0; compI < result.componentCoDim.size(); ++compI) {
if (result.componentCoDim[compI] == 0) {
for (int vI = result.componentNodeRange[compI];
vI < result.componentNodeRange[compI + 1]; ++vI) {
fprintf(out, "v %le %le %le\n", result.V(vI, 0), result.V(vI, 1), result.V(vI, 2));
}
}
}
fclose(out);
}
}
template <int dim>
void Optimizer<dim>::outputCollStats(std::ostream& out)
{
for (int i = 0; i < n_collPairs_sum.size(); ++i) {
out << "avg # collision pairs / iter = " << n_collPairs_sum[i] / (innerIterAmt ? innerIterAmt : 1) << std::endl;
out << "max # collision pairs / iter = " << n_collPairs_max[i] << std::endl;
out << "avg # collision pairs / end of ts = " << n_convCollPairs_sum[i] / globalIterNum << std::endl;
out << "max # collision pairs / end of ts = " << n_convCollPairs_max[i] << std::endl;
out << std::endl;
}
out << "Total:" << std::endl;
out << "avg # collision pairs / iter = " << n_collPairs_sum.sum() / (innerIterAmt ? innerIterAmt : 1) << std::endl;
out << "max # collision pairs / iter = " << n_collPairs_total_max << std::endl;
out << "avg # collision pairs / end of ts = " << n_convCollPairs_sum.sum() / globalIterNum << std::endl;
out << "max # collision pairs / end of ts = " << n_convCollPairs_total_max << std::endl;
out << std::endl;
}
template <int dim>
void Optimizer<dim>::computeEnergyVal(const Mesh<dim>& data, int redoSVD, double& energyVal)
{
//TODO: write inertia and augmented Lagrangian term into energyTerms
// if(!mute) { timer_step.start(0); }
switch (animConfig.timeIntegrationType) {
case TIT_BE: {
energyTerms[0]->computeEnergyVal(data, redoSVD, svd, F,
dtSq * energyParams[0], energyVal_ET[0]);
energyVal = energyVal_ET[0];
for (int eI = 1; eI < energyTerms.size(); eI++) {
energyTerms[eI]->computeEnergyVal(data, redoSVD, svd, F,
dtSq * energyParams[eI], energyVal_ET[eI]);
energyVal += energyVal_ET[eI];
}
break;
}
case TIT_NM: {
energyTerms[0]->computeEnergyVal(data, redoSVD, svd, F, dtSq * beta_NM * energyParams[0], energyVal_ET[0]);
energyVal = energyVal_ET[0];
for (int eI = 1; eI < energyTerms.size(); eI++) {
energyTerms[eI]->computeEnergyVal(data, redoSVD, svd, F, dtSq * beta_NM * energyParams[eI], energyVal_ET[eI]);
energyVal += energyVal_ET[eI];
}
break;
}
}
Eigen::VectorXd energyVals(data.V.rows());
#ifdef USE_TBB
tbb::parallel_for(0, (int)data.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < data.V.rows(); vI++)
#endif
{
energyVals[vI] = ((data.V.row(vI) - xTilta.row(vI)).squaredNorm() * data.massMatrix.coeff(vI, vI) / 2.0);
}
#ifdef USE_TBB
);
#endif
energyVal += energyVals.sum();
if (animScripter.isNBCActive()) {
for (int NBCi = 0; NBCi < data.NeumannBCs.size(); NBCi++) {
const auto& NBC = data.NeumannBCs[NBCi];
for (const auto& vI : NBC.vertIds) {
if (!data.isFixedVert[vI] && animScripter.isNBCActive(data, NBCi)) {
energyVal -= dtSq * data.massMatrix.coeff(vI, vI) * data.V.row(vI).dot(NBC.force.transpose());
}
}
}
}
if (solveIP) {
Eigen::VectorXd constraintVals, bVals;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
int startCI = constraintVals.size();
animConfig.collisionObjects[coI]->evaluateConstraints(data, activeSet[coI], constraintVals);
bVals.conservativeResize(constraintVals.size());
for (int cI = startCI; cI < constraintVals.size(); ++cI) {
if (constraintVals[cI] <= 0.0) {
spdlog::error("constraintVal = {:g} when evaluating constraints", constraintVals[cI]);
exit(0);
}
else {
compute_b(constraintVals[cI], dHat, bVals[cI]);
}
}
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
int startCI = constraintVals.size();
animConfig.meshCollisionObjects[coI]->evaluateConstraints(data, MMActiveSet[coI], constraintVals);
bVals.conservativeResize(constraintVals.size());
for (int cI = startCI; cI < constraintVals.size(); ++cI) {
if (constraintVals[cI] <= 0.0) {
spdlog::error("constraintVal = {:g} when evaluating constraints", constraintVals[cI]);
exit(0);
}
else {
compute_b(constraintVals[cI], dHat, bVals[cI]);
int duplication = MMActiveSet[coI][cI - startCI][3];
if (duplication < -1) {
// PP or PE or EP, handle duplication
bVals[cI] *= -duplication;
}
}
}
animConfig.meshCollisionObjects[coI]->augmentParaEEEnergy(data, paraEEMMCVIDSet[coI], paraEEeIeJSet[coI],
constraintVals, bVals, dHat, 1.0);
}
if (animConfig.isSelfCollision) {
int startCI = constraintVals.size();
SelfCollisionHandler<dim>::evaluateConstraints(data, MMActiveSet.back(), constraintVals);
bVals.conservativeResize(constraintVals.size());
//TODO: parallelize
for (int cI = startCI; cI < constraintVals.size(); ++cI) {
if (constraintVals[cI] <= 0.0) {
spdlog::error("constraintVal = {:g} when evaluating constraints {:d} {:d} {:d} {:d}",
constraintVals[cI], MMActiveSet.back()[cI][0], MMActiveSet.back()[cI][1],
MMActiveSet.back()[cI][2], MMActiveSet.back()[cI][3]);
std::cout << data.V.row(MMActiveSet.back()[cI][0] >= 0 ? MMActiveSet.back()[cI][0] : (-MMActiveSet.back()[cI][0] - 1)) << std::endl;
std::cout << data.V.row(MMActiveSet.back()[cI][1] >= 0 ? MMActiveSet.back()[cI][1] : (-MMActiveSet.back()[cI][1] - 1)) << std::endl;
std::cout << data.V.row(MMActiveSet.back()[cI][2] >= 0 ? MMActiveSet.back()[cI][2] : (-MMActiveSet.back()[cI][2] - 1)) << std::endl;
std::cout << data.V.row(MMActiveSet.back()[cI][3] >= 0 ? MMActiveSet.back()[cI][3] : (-MMActiveSet.back()[cI][3] - 1)) << std::endl;
data.saveSurfaceMesh("debug.obj");
exit(0);
}
else {
compute_b(constraintVals[cI], dHat, bVals[cI]);
int duplication = MMActiveSet.back()[cI - startCI][3];
if (duplication < -1) {
// PP or PE, handle duplication
bVals[cI] *= -duplication;
}
}
}
startCI = constraintVals.size();
SelfCollisionHandler<dim>::evaluateConstraints(data, paraEEMMCVIDSet.back(), constraintVals);
bVals.conservativeResize(constraintVals.size());
for (int cI = startCI; cI < constraintVals.size(); ++cI) {
if (constraintVals[cI] <= 0.0) {
spdlog::error("constraintVal = {:g} when evaluating constraints {:d} {:d} {:d} {:d}",
constraintVals[cI], MMActiveSet.back()[cI][0], MMActiveSet.back()[cI][1],
MMActiveSet.back()[cI][2], MMActiveSet.back()[cI][3]);
std::cout << data.V.row(MMActiveSet.back()[cI][0] >= 0 ? MMActiveSet.back()[cI][0] : (-MMActiveSet.back()[cI][0] - 1)) << std::endl;
std::cout << data.V.row(MMActiveSet.back()[cI][1] >= 0 ? MMActiveSet.back()[cI][1] : (-MMActiveSet.back()[cI][1] - 1)) << std::endl;
std::cout << data.V.row(MMActiveSet.back()[cI][2] >= 0 ? MMActiveSet.back()[cI][2] : (-MMActiveSet.back()[cI][2] - 1)) << std::endl;
std::cout << data.V.row(MMActiveSet.back()[cI][3] >= 0 ? MMActiveSet.back()[cI][3] : (-MMActiveSet.back()[cI][3] - 1)) << std::endl;
data.saveSurfaceMesh("debug.obj");
exit(0);
}
else {
const MMCVID& MMCVIDI = paraEEMMCVIDSet.back()[cI - startCI];
double eps_x, e;
if (MMCVIDI[3] >= 0) {
// EE
compute_eps_x(data, MMCVIDI[0], MMCVIDI[1], MMCVIDI[2], MMCVIDI[3], eps_x);
compute_e(data.V.row(MMCVIDI[0]), data.V.row(MMCVIDI[1]), data.V.row(MMCVIDI[2]), data.V.row(MMCVIDI[3]), eps_x, e);
}
else {
// PP or PE
const std::pair<int, int>& eIeJ = paraEEeIeJSet.back()[cI - startCI];
const std::pair<int, int>& eI = data.SFEdges[eIeJ.first];
const std::pair<int, int>& eJ = data.SFEdges[eIeJ.second];
compute_eps_x(data, eI.first, eI.second, eJ.first, eJ.second, eps_x);
compute_e(data.V.row(eI.first), data.V.row(eI.second), data.V.row(eJ.first), data.V.row(eJ.second), eps_x, e);
}
compute_b(constraintVals[cI], dHat, bVals[cI]);
bVals[cI] *= e;
}
}
}
energyVal += kappa * bVals.sum();
// std::cout << ", E_c=" << kappa * bVals.sum();
// energies[1] = kappa * bVals.sum();
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
// friction
if (activeSet_lastH[coI].size() && fricDHat > 0.0 && animConfig.collisionObjects[coI]->friction > 0.0) {
double Ef;
animConfig.collisionObjects[coI]->computeFrictionEnergy(data.V, result.V_prev, activeSet_lastH[coI],
lambda_lastH[coI], Ef, fricDHat, 1.0);
energyVal += Ef;
// std::cout << ", E_f" << coI << "=" << Ef;
// energies[2] = Ef;
}
}
if (animConfig.isSelfCollision) {
if (MMActiveSet_lastH.back().size() && fricDHat > 0.0 && animConfig.selfFric > 0.0) {
double Ef;
SelfCollisionHandler<dim>::computeFrictionEnergy(data.V, result.V_prev, MMActiveSet_lastH.back(),
MMLambda_lastH.back(), MMDistCoord.back(), MMTanBasis.back(), Ef, fricDHat, animConfig.selfFric);
energyVal += Ef;
// std::cout << ", E_fs=" << Ef;
// energies[3] = Ef;
}
}
}
// std::cout << std::endl;
if (animConfig.dampingStiff > 0.0) {
Eigen::VectorXd displacement(data.V.rows() * dim), Adx;
#ifdef USE_TBB
tbb::parallel_for(0, (int)data.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < data.V.rows(); vI++)
#endif
{
displacement.segment<dim>(vI * dim) = (data.V.row(vI) - result.V_prev.row(vI)).transpose();
}
#ifdef USE_TBB
);
#endif
for (const auto& fixedVI : data.fixedVert) {
displacement.segment<dim>(fixedVI * dim).setZero();
}
dampingMtr->multiply(displacement, Adx);
energyVal += 0.5 * displacement.dot(Adx);
}
if (rho_DBC) {
animScripter.augmentMDBCEnergy(data, energyVal, rho_DBC);
}
// if(!mute) { timer_step.stop(); }
}
template <int dim>
void Optimizer<dim>::computeGradient(const Mesh<dim>& data,
bool redoSVD, Eigen::VectorXd& gradient, bool projectDBC)
{
// if(!mute) { timer_step.start(0); }
switch (animConfig.timeIntegrationType) {
case TIT_BE: {
energyTerms[0]->computeGradient(data, redoSVD, svd, F,
dtSq * energyParams[0], gradient_ET[0], projectDBC);
gradient = gradient_ET[0];
for (int eI = 1; eI < energyTerms.size(); eI++) {
energyTerms[eI]->computeGradient(data, redoSVD, svd, F,
dtSq * energyParams[eI], gradient_ET[eI], projectDBC);
gradient += gradient_ET[eI];
}
break;
}
case TIT_NM: {
energyTerms[0]->computeGradient(data, redoSVD, svd, F, dtSq * beta_NM * energyParams[0], gradient_ET[0], projectDBC);
gradient = gradient_ET[0];
for (int eI = 1; eI < energyTerms.size(); eI++) {
energyTerms[eI]->computeGradient(data, redoSVD, svd, F, dtSq * beta_NM * energyParams[eI], gradient_ET[eI], projectDBC);
gradient += gradient_ET[eI];
}
break;
}
}
#ifdef USE_TBB
tbb::parallel_for(0, (int)data.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < data.V.rows(); vI++)
#endif
{
if (!data.isFixedVert[vI] || !projectDBC) {
gradient.segment<dim>(vI * dim) += (data.massMatrix.coeff(vI, vI) * (data.V.row(vI) - xTilta.row(vI)).transpose());
}
}
#ifdef USE_TBB
);
#endif
if (animScripter.isNBCActive()) {
for (int NBCi = 0; NBCi < data.NeumannBCs.size(); NBCi++) {
const auto& NBC = data.NeumannBCs[NBCi];
for (const auto& vI : NBC.vertIds) {
if (!data.isFixedVert[vI] && animScripter.isNBCActive(data, NBCi)) {
gradient.template segment<dim>(vI * dim) -= dtSq * data.massMatrix.coeff(vI, vI) * NBC.force;
}
}
}
}
if (solveIP) {
Eigen::VectorXd constraintVal;
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
int startCI = constraintVal.size();
animConfig.collisionObjects[coI]->evaluateConstraints(data, activeSet[coI], constraintVal);
for (int cI = startCI; cI < constraintVal.size(); ++cI) {
compute_g_b(constraintVal[cI], dHat, constraintVal[cI]);
}
animConfig.collisionObjects[coI]->leftMultiplyConstraintJacobianT(data, activeSet[coI],
constraintVal.segment(startCI, activeSet[coI].size()), gradient, kappa);
// friction
if (activeSet_lastH[coI].size() && fricDHat > 0.0 && animConfig.collisionObjects[coI]->friction > 0.0) {
animConfig.collisionObjects[coI]->augmentFrictionGradient(data.V, result.V_prev, activeSet_lastH[coI],
lambda_lastH[coI], gradient, fricDHat, 1.0);
}
}
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
int startCI = constraintVal.size();
animConfig.meshCollisionObjects[coI]->evaluateConstraints(data, MMActiveSet[coI], constraintVal);
for (int cI = startCI; cI < constraintVal.size(); ++cI) {
compute_g_b(constraintVal[cI], dHat, constraintVal[cI]);
}
animConfig.meshCollisionObjects[coI]->leftMultiplyConstraintJacobianT(data, MMActiveSet[coI],
constraintVal.segment(startCI, MMActiveSet[coI].size()), gradient, kappa);
animConfig.meshCollisionObjects[coI]->augmentParaEEGradient(data,
paraEEMMCVIDSet[coI], paraEEeIeJSet[coI], gradient, dHat, kappa);
}
if (animConfig.isSelfCollision) {
int startCI = constraintVal.size();
SelfCollisionHandler<dim>::evaluateConstraints(data, MMActiveSet.back(), constraintVal);
for (int cI = startCI; cI < constraintVal.size(); ++cI) {
compute_g_b(constraintVal[cI], dHat, constraintVal[cI]);
}
SelfCollisionHandler<dim>::leftMultiplyConstraintJacobianT(data, MMActiveSet.back(),
constraintVal.segment(startCI, MMActiveSet.back().size()), gradient, kappa);
SelfCollisionHandler<dim>::augmentParaEEGradient(data,
paraEEMMCVIDSet.back(), paraEEeIeJSet.back(), gradient, dHat, kappa);
if (MMActiveSet_lastH.back().size() && fricDHat > 0.0 && animConfig.selfFric > 0.0) {
SelfCollisionHandler<dim>::augmentFrictionGradient(data.V, result.V_prev, MMActiveSet_lastH.back(),
MMLambda_lastH.back(), MMDistCoord.back(), MMTanBasis.back(), gradient, fricDHat, animConfig.selfFric);
#ifdef EXPORT_FRICTION_DATA
save_friction_data(
data, MMActiveSet_lastH.back(), MMLambda_lastH.back(),
MMDistCoord.back(), MMTanBasis.back(),
dHat, kappa, fricDHat, animConfig.selfFric);
#endif
}
}
if (projectDBC) {
for (const auto& fixedVI : data.fixedVert) {
gradient.segment<dim>(fixedVI * dim).setZero();
}
}
}
if (animConfig.dampingStiff > 0.0) {
Eigen::VectorXd displacement(data.V.rows() * dim), Adx;
#ifdef USE_TBB
tbb::parallel_for(0, (int)data.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < data.V.rows(); vI++)
#endif
{
displacement.segment<dim>(vI * dim) = (data.V.row(vI) - result.V_prev.row(vI)).transpose();
}
#ifdef USE_TBB
);
#endif
if (projectDBC) {
for (const auto& fixedVI : data.fixedVert) {
displacement.segment<dim>(fixedVI * dim).setZero();
}
}
dampingMtr->multiply(displacement, Adx);
gradient += Adx;
}
if (!projectDBC && rho_DBC) {
animScripter.augmentMDBCGradient(data, gradient, rho_DBC);
}
// if(!mute) { timer_step.stop(); }
}
template <int dim>
void Optimizer<dim>::computePrecondMtr(const Mesh<dim>& data,
bool redoSVD,
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* p_linSysSolver,
bool updateDamping, bool projectDBC)
{
if (!mute) { timer_step.start(0); }
if (solveIP) {
// figure out vNeighbor_IP in this iteration
timer_step.start(1);
if (animConfig.isSelfCollision && (MMActiveSet.back().size() + paraEEeIeJSet.back().size() + MMActiveSet_lastH.back().size())) {
// there is extra connectivity from self-contact
timer_mt.start(8);
std::vector<std::set<int>> vNeighbor_IP_new = data.vNeighbor;
SelfCollisionHandler<dim>::augmentConnectivity(data, MMActiveSet.back(), vNeighbor_IP_new);
SelfCollisionHandler<dim>::augmentConnectivity(data, paraEEMMCVIDSet.back(), paraEEeIeJSet.back(), vNeighbor_IP_new);
if (MMActiveSet_lastH.back().size() && fricDHat > 0.0 && animConfig.selfFric > 0.0) {
SelfCollisionHandler<dim>::augmentConnectivity(data, MMActiveSet_lastH.back(), vNeighbor_IP_new);
}
timer_mt.stop();
if (vNeighbor_IP_new != vNeighbor_IP) {
timer_mt.start(8);
vNeighbor_IP = vNeighbor_IP_new;
timer_mt.start(9);
p_linSysSolver->set_pattern(vNeighbor_IP, data.fixedVert);
timer_mt.stop();
timer_step.start(2);
p_linSysSolver->analyze_pattern();
timer_step.start(1);
}
}
else if (vNeighbor_IP != data.vNeighbor) {
// no extra connectivity in this iteration but there is in the last iteration
timer_mt.start(8);
vNeighbor_IP = data.vNeighbor;
timer_mt.start(9);
p_linSysSolver->set_pattern(vNeighbor_IP, data.fixedVert);
timer_mt.stop();
timer_step.start(2);
p_linSysSolver->analyze_pattern();
timer_step.start(1);
}
timer_step.start(0);
}
timer_mt.start(10);
if (updateDamping && animConfig.dampingStiff) {
computeDampingMtr(data, redoSVD, dampingMtr, projectDBC);
switch (animConfig.timeIntegrationType) {
case TIT_BE: {
p_linSysSolver->setCoeff(dampingMtr,
1.0 + dtSq * dt / animConfig.dampingStiff);
break;
}
case TIT_NM: {
p_linSysSolver->setCoeff(dampingMtr,
1.0 + dtSq * beta_NM * dt / animConfig.dampingStiff);
break;
}
}
}
else {
p_linSysSolver->setZero();
switch (animConfig.timeIntegrationType) {
case TIT_BE: {
for (int eI = 0; eI < energyTerms.size(); eI++) {
energyTerms[eI]->computeHessian(data, redoSVD, svd, F,
energyParams[eI] * dtSq,
p_linSysSolver, true, projectDBC);
}
break;
}
case TIT_NM: {
for (int eI = 0; eI < energyTerms.size(); eI++) {
energyTerms[eI]->computeHessian(data, redoSVD, svd, F, energyParams[eI] * dtSq * beta_NM, p_linSysSolver, true, projectDBC);
}
break;
}
}
}
timer_mt.start(11);
#ifdef USE_TBB
tbb::parallel_for(0, (int)data.V.rows(), 1, [&](int vI)
#else
for (int vI = 0; vI < data.V.rows(); vI++)
#endif
{
if (!data.isFixedVert[vI] || !projectDBC) {
double massI = data.massMatrix.coeff(vI, vI);
int ind0 = vI * dim;
int ind1 = ind0 + 1;
p_linSysSolver->addCoeff(ind0, ind0, massI);
p_linSysSolver->addCoeff(ind1, ind1, massI);
if constexpr (dim == 3) {
int ind2 = ind0 + 2;
p_linSysSolver->addCoeff(ind2, ind2, massI);
}
}
else {
// for Dirichlet boundary condition
int ind0 = vI * dim;
int ind1 = ind0 + 1;
p_linSysSolver->setCoeff(ind0, ind0, 1.0);
p_linSysSolver->setCoeff(ind1, ind1, 1.0);
if constexpr (dim == 3) {
int ind2 = ind0 + 2;
p_linSysSolver->setCoeff(ind2, ind2, 1.0);
}
}
}
#ifdef USE_TBB
);
#endif
timer_mt.stop();
if (solveIP) {
timer_mt.start(12);
for (int coI = 0; coI < animConfig.collisionObjects.size(); ++coI) {
animConfig.collisionObjects[coI]->augmentIPHessian(data,
activeSet[coI], p_linSysSolver, dHat, kappa, projectDBC);
// friction
if (activeSet_lastH[coI].size() && fricDHat > 0.0 && animConfig.collisionObjects[coI]->friction > 0.0) {
animConfig.collisionObjects[coI]->augmentFrictionHessian(data,
result.V_prev, activeSet_lastH[coI], lambda_lastH[coI],
p_linSysSolver, fricDHat, 1.0, projectDBC);
}
}
timer_mt.start(13);
for (int coI = 0; coI < animConfig.meshCollisionObjects.size(); ++coI) {
animConfig.meshCollisionObjects[coI]->augmentIPHessian(data, MMActiveSet[coI], p_linSysSolver, dHat, kappa, projectDBC);
animConfig.meshCollisionObjects[coI]->augmentParaEEHessian(data, paraEEMMCVIDSet[coI], paraEEeIeJSet[coI],
p_linSysSolver, dHat, kappa, projectDBC);
}
timer_mt.start(14);
if (animConfig.isSelfCollision) {
SelfCollisionHandler<dim>::augmentIPHessian(data, MMActiveSet.back(), p_linSysSolver, dHat, kappa, projectDBC);
SelfCollisionHandler<dim>::augmentParaEEHessian(data, paraEEMMCVIDSet.back(), paraEEeIeJSet.back(),
p_linSysSolver, dHat, kappa, projectDBC);
if (MMActiveSet_lastH.back().size() && fricDHat > 0.0 && animConfig.selfFric > 0.0) {
SelfCollisionHandler<dim>::augmentFrictionHessian(data, result.V_prev, MMActiveSet_lastH.back(),
MMLambda_lastH.back(), MMDistCoord.back(), MMTanBasis.back(),
p_linSysSolver, fricDHat, animConfig.selfFric, projectDBC);
}
}
timer_mt.stop();
}
if (animConfig.dampingStiff && (!updateDamping)) {
p_linSysSolver->addCoeff(dampingMtr, 1.0);
}
if (!projectDBC && rho_DBC) {
animScripter.augmentMDBCHessian(data, p_linSysSolver, rho_DBC);
}
if (!mute) { timer_step.stop(); }
// output matrix and exit
// IglUtils::writeSparseMatrixToFile("/Users/mincli/Desktop/IPC/output/A", p_linSysSolver, true);
// std::cout << "matrix written" << std::endl;
// exit(0);
}
template <int dim>
void Optimizer<dim>::computeDampingMtr(const Mesh<dim>& data,
bool redoSVD,
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* p_dampingMtr,
bool projectDBC)
{
p_dampingMtr->setZero();
for (int eI = 0; eI < energyTerms.size(); eI++) {
energyTerms[eI]->computeHessian(data, redoSVD, svd, F,
energyParams[eI] * animConfig.dampingStiff / dt,
p_dampingMtr, true, projectDBC);
}
}
template <int dim>
void Optimizer<dim>::setupDampingMtr(const Mesh<dim>& data,
bool redoSVD,
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* p_dampingMtr)
{
dampingMtr->set_pattern(data.vNeighbor, data.fixedVert);
computeDampingMtr(data, redoSVD, p_dampingMtr);
}
template <int dim>
void Optimizer<dim>::computeSystemEnergy(std::vector<double>& sysE,
std::vector<Eigen::Matrix<double, 1, dim>>& sysM,
std::vector<Eigen::Matrix<double, 1, dim>>& sysL)
{
Eigen::VectorXd energyValPerElem;
energyTerms[0]->getEnergyValPerElemBySVD(result, true, svd, F, energyValPerElem, false);
sysE.resize(compVAccSize.size());
sysM.resize(compVAccSize.size());
sysL.resize(compVAccSize.size());
for (int compI = 0; compI < compVAccSize.size(); ++compI) {
sysE[compI] = 0.0;
sysM[compI].setZero();
sysL[compI].setZero();
for (int fI = (compI ? compFAccSize[compI - 1] : 0); fI < compFAccSize[compI]; ++fI) {
sysE[compI] += energyValPerElem[fI];
}
for (int vI = (compI ? compVAccSize[compI - 1] : 0); vI < compVAccSize[compI]; ++vI) {
sysE[compI] += result.massMatrix.coeff(vI, vI) * ((result.V.row(vI) - result.V_prev.row(vI)).squaredNorm() / dtSq / 2.0 - gravity.dot(result.V.row(vI).transpose()));
Eigen::Matrix<double, 1, dim> p = result.massMatrix.coeff(vI, vI) / dt * (result.V.row(vI) - result.V_prev.row(vI));
sysM[compI] += p;
if constexpr (dim == 3) {
sysL[compI] += Eigen::Matrix<double, 1, dim>(result.V.row(vI)).cross(p);
}
else {
sysL[compI][0] += result.V(vI, 0) * p[1] - result.V(vI, 1) * p[0];
}
}
}
}
template <int dim>
void Optimizer<dim>::checkGradient(void)
{
spdlog::info("checking energy gradient computation...");
double energyVal0;
computeConstraintSets(result);
computeEnergyVal(result, true, energyVal0);
const double h = 1.0e-6 * igl::avg_edge_length(result.V, result.F);
Mesh<dim> perturbed = result;
Eigen::VectorXd gradient_finiteDiff;
gradient_finiteDiff.resize(result.V.rows() * dim);
for (int vI = 0; vI < result.V.rows(); vI++) {
for (int dimI = 0; dimI < dim; dimI++) {
perturbed.V = result.V;
perturbed.V(vI, dimI) += h;
double energyVal_perturbed;
computeConstraintSets(perturbed);
computeEnergyVal(perturbed, true, energyVal_perturbed);
gradient_finiteDiff[vI * dim + dimI] = (energyVal_perturbed - energyVal0) / h;
}
if (((vI + 1) % 100) == 0) {
spdlog::info("{:d}/{:d} vertices computed", vI + 1, result.V.rows());
}
}
for (const auto fixedVI : result.fixedVert) {
gradient_finiteDiff.segment<dim>(dim * fixedVI).setZero();
}
Eigen::VectorXd gradient_symbolic;
computeConstraintSets(result);
computeGradient(result, true, gradient_symbolic);
Eigen::VectorXd difVec = gradient_symbolic - gradient_finiteDiff;
const double dif_L2 = difVec.norm();
const double relErr = dif_L2 / gradient_finiteDiff.norm();
spdlog::info("L2 dist = {:g}, relErr = {:g}", dif_L2, relErr);
logFile << "check gradient:" << std::endl;
logFile << "g_symbolic =\n"
<< gradient_symbolic << std::endl;
logFile << "g_finiteDiff = \n"
<< gradient_finiteDiff << std::endl;
}
template <int dim>
void Optimizer<dim>::checkHessian(void)
{
//TODO: needs to turn off SPD projection
spdlog::info("checking hessian computation...");
Eigen::VectorXd gradient0;
computeConstraintSets(result);
computeGradient(result, true, gradient0);
const double h = 1.0e-6 * igl::avg_edge_length(result.V, result.F);
Mesh<dim> perturbed = result;
Eigen::SparseMatrix<double> hessian_finiteDiff;
hessian_finiteDiff.resize(result.V.rows() * dim, result.V.rows() * dim);
for (int vI = 0; vI < result.V.rows(); vI++) {
if (result.fixedVert.find(vI) != result.fixedVert.end()) {
hessian_finiteDiff.insert(vI * dim, vI * dim) = 1.0;
hessian_finiteDiff.insert(vI * dim + 1, vI * dim + 1) = 1.0;
if constexpr (dim == 3) {
hessian_finiteDiff.insert(vI * dim + 2, vI * dim + 2) = 1.0;
}
continue;
}
for (int dimI = 0; dimI < dim; dimI++) {
perturbed.V = result.V;
perturbed.V(vI, dimI) += h;
Eigen::VectorXd gradient_perturbed;
// computeConstraintSets(perturbed); // the transition is only C1 continuous
computeGradient(perturbed, true, gradient_perturbed);
Eigen::VectorXd hessian_colI = (gradient_perturbed - gradient0) / h;
int colI = vI * dim + dimI;
for (int rowI = 0; rowI < result.V.rows() * dim; rowI++) {
if ((result.fixedVert.find(rowI / dim) == result.fixedVert.end()) && (hessian_colI[rowI] != 0.0)) {
hessian_finiteDiff.insert(rowI, colI) = hessian_colI[rowI];
}
}
}
if (((vI + 1) % 100) == 0) {
spdlog::info("{:d}/{:d} vertices computed", vI + 1, result.V.rows());
}
}
Eigen::SparseMatrix<double> hessian_symbolicPK;
LinSysSolver<Eigen::VectorXi, Eigen::VectorXd>* linSysSolver;
#ifdef LINSYSSOLVER_USE_CHOLMOD
linSysSolver = new CHOLMODSolver<Eigen::VectorXi, Eigen::VectorXd>();
#elif defined(LINSYSSOLVER_USE_AMGCL)
linSysSolver = new AMGCLSolver<Eigen::VectorXi, Eigen::VectorXd>();
#else
linSysSolver = new EigenLibSolver<Eigen::VectorXi, Eigen::VectorXd>();
#endif
linSysSolver->set_pattern(result.vNeighbor, result.fixedVert);
computeConstraintSets(result);
computePrecondMtr(result, true, linSysSolver);
linSysSolver->getCoeffMtr(hessian_symbolicPK);
Eigen::SparseMatrix<double> difMtrPK = hessian_symbolicPK - hessian_finiteDiff;
const double difPK_L2 = difMtrPK.norm();
const double relErrPK = difPK_L2 / hessian_finiteDiff.norm();
spdlog::info("PK L2 dist = {:g}, relErr = {:g}", difPK_L2, relErrPK);
IglUtils::writeSparseMatrixToFile(outputFolderPath + "H_symbolicPK", hessian_symbolicPK, true);
IglUtils::writeSparseMatrixToFile(outputFolderPath + "H_finiteDiff", hessian_finiteDiff, true);
}
template class Optimizer<DIM>;
} // namespace IPC
| 38.29424 | 229 | 0.564728 | [
"mesh",
"object",
"vector"
] |
738e7021b61ee6ab0e04a7647c5dc4b1251d015f | 29,169 | cpp | C++ | code/ship/shield.cpp | EatThePath/fs2open.github.com | 4f7bad2a5c6779cd9f126b9e5c64a0528d193b9f | [
"Unlicense"
] | null | null | null | code/ship/shield.cpp | EatThePath/fs2open.github.com | 4f7bad2a5c6779cd9f126b9e5c64a0528d193b9f | [
"Unlicense"
] | 1 | 2022-02-09T04:41:29.000Z | 2022-03-18T21:59:49.000Z | code/ship/shield.cpp | EatThePath/fs2open.github.com | 4f7bad2a5c6779cd9f126b9e5c64a0528d193b9f | [
"Unlicense"
] | null | null | null | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
// Detail level effects (Detail.shield_effects)
// 0 Nothing rendered
// 1 An animating bitmap rendered per hit, not shrink-wrapped. Lasts half time. One per ship.
// 2 Animating bitmap per hit, not shrink-wrapped. Lasts full time. Unlimited.
// 3 Shrink-wrapped texture. Lasts half-time.
// 4 Shrink-wrapped texture. Lasts full-time.
#include "render/3d.h"
#include "model/model.h"
#include "freespace.h"
#include "mission/missionparse.h"
#include "network/multi.h"
#include "object/objectshield.h"
#include "ship/ship.h"
#include "species_defs/species_defs.h"
#include "tracing/Monitor.h"
#include "tracing/tracing.h"
#include "nebula/neb.h"
int Show_shield_mesh = 0;
// One unit in 3d means this in the shield hit texture map.
#define SHIELD_HIT_SCALE 0.15f // Note, larger constant means smaller effect
#define MAX_TRIS_PER_HIT 40 // Number of triangles per shield hit, maximum.
#define MAX_SHIELD_HITS 200 // Maximum number of active shield hits.
#define MAX_SHIELD_TRI_BUFFER (MAX_SHIELD_HITS*MAX_TRIS_PER_HIT) //(MAX_SHIELD_HITS*20) // Persistent buffer of triangle comprising all active shield hits.
#define SHIELD_HIT_DURATION (3*F1_0/4) // Duration, in milliseconds, of shield hit effect
#define SH_UNUSED -1 // Indicates an unused record in Shield_hits
#define SH_TYPE_1 1 // Indicates Shield_hits record is of type 1.
#define UV_MAX (63.95f/64.0f) // max allowed value until tmapper bugs fixed, 1/24/97
float Shield_scale = SHIELD_HIT_SCALE;
/**
* Structure which mimics the ::shield_tri structure in model.h.
*
* Since the global shield triangle array needs the vertex information, we will acutally
* store the information in this structure instead of the indices into the vertex list
*/
typedef struct gshield_tri {
int used; // Set if this triangle is currently in use.
int trinum; // a debug parameter
fix creation_time; // time at which created.
shield_vertex verts[4]; // Triangles, but at lower detail level, a square.
} gshield_tri;
typedef struct shield_hit {
int start_time; // start time of this object
int type; // type, probably the weapon type, to indicate the bitmap to use
int objnum; // Object index, needed to get current orientation, position.
int num_tris; // Number of Shield_tris comprising this shield.
int tri_list[MAX_TRIS_PER_HIT]; // Indices into Shield_tris, triangles for this shield hit.
ubyte rgb[3]; // rgb colors
matrix hit_orient; // hit rotation
vec3d hit_pos; // hit position
} shield_hit;
/**
* Stores point at which shield was hit.
* Gets processed in frame interval.
*/
typedef struct shield_point {
int objnum; // Object that was hit.
int shield_tri; // Triangle in shield mesh that took hit.
vec3d hit_point; // Point in global 3-space of hit.
} shield_point;
#define MAX_SHIELD_POINTS 100
shield_point Shield_points[MAX_SHIELD_POINTS];
int Num_shield_points;
int Num_multi_shield_points; // used by multiplayer clients
gshield_tri Global_tris[MAX_SHIELD_TRI_BUFFER]; // The persistent triangles, part of shield hits.
int Num_tris; // Number of triangles in current shield. Would be a local, but needed in numerous routines.
shield_hit Shield_hits[MAX_SHIELD_HITS];
int Shield_bitmaps_loaded = 0;
// This is a recursive function, so prototype it.
extern void create_shield_from_triangle(int trinum, matrix *orient, shield_info *shieldp, vec3d *tcp, vec3d *centerp, float radius, vec3d *rvec, vec3d *uvec);
void load_shield_hit_bitmap()
{
size_t i;
// Check if we've already allocated the shield effect bitmaps
if ( Shield_bitmaps_loaded )
return;
Shield_bitmaps_loaded = 1;
for (i = 0; i < Species_info.size(); i++ )
{
if (Species_info[i].shield_anim.filename[0] != '\0')
{
Species_info[i].shield_anim.first_frame = bm_load_animation(Species_info[i].shield_anim.filename, &Species_info[i].shield_anim.num_frames, nullptr, nullptr, nullptr, true);
Assertion((Species_info[i].shield_anim.first_frame >= 0), "Error while loading shield hit ani: %s for species: %s\n", Species_info[i].shield_anim.filename, Species_info[i].species_name);
}
}
}
void shield_hit_page_in()
{
size_t i;
if ( !Shield_bitmaps_loaded ) {
load_shield_hit_bitmap();
}
for (i = 0; i < Species_info.size(); i++) {
generic_anim *sa = &Species_info[i].shield_anim;
if ( sa->first_frame >= 0 ) {
bm_page_in_xparent_texture(sa->first_frame, sa->num_frames );
}
}
}
/**
* Initialize shield hit system.
*
* Called from game_level_init()
*/
void shield_hit_init()
{
int i;
for (i=0; i<MAX_SHIELD_HITS; i++) {
Shield_hits[i].type = SH_UNUSED;
Shield_hits[i].objnum = -1;
}
for (i=0; i<MAX_SHIELD_TRI_BUFFER; i++) {
Global_tris[i].used = 0;
Global_tris[i].creation_time = Missiontime;
}
Num_multi_shield_points = 0;
load_shield_hit_bitmap();
}
/**
* Release the storage allocated to store the shield effect.
*
* This doesn't need to do anything; the bitmap manager will release everything.
*/
void release_shield_hit_bitmap()
{
if ( !Shield_bitmaps_loaded )
return;
}
int Poly_count = 0;
/**
* De-initialize the shield hit system. Called from game_level_close().
*
* @todo We should probably not bother releasing the shield hit bitmaps every level.
*/
void shield_hit_close()
{
release_shield_hit_bitmap();
}
void shield_frame_init()
{
Poly_count = 0;
Num_shield_points = 0;
}
void create_low_detail_poly(int global_index, vec3d *tcp, vec3d *rightv, vec3d *upv)
{
float scale;
gshield_tri *trip;
trip = &Global_tris[global_index];
scale = vm_vec_mag(tcp) * 2.0f;
vm_vec_scale_add(&trip->verts[0].pos, tcp, rightv, -scale/2.0f);
vm_vec_scale_add2(&trip->verts[0].pos, upv, scale/2.0f);
vm_vec_scale_add(&trip->verts[1].pos, &trip->verts[0].pos, rightv, scale);
vm_vec_scale_add(&trip->verts[2].pos, &trip->verts[1].pos, upv, -scale);
vm_vec_scale_add(&trip->verts[3].pos, &trip->verts[2].pos, rightv, -scale);
// Set u, v coordinates.
// Note, this need only be done once, as it's common for all explosions.
trip->verts[0].u = 0.0f;
trip->verts[0].v = 0.0f;
trip->verts[1].u = 1.0f;
trip->verts[1].v = 0.0f;
trip->verts[2].u = 1.0f;
trip->verts[2].v = 1.0f;
trip->verts[3].u = 0.0f;
trip->verts[3].v = 1.0f;
}
/**
* Given a shield triangle, compute the uv coordinates at its vertices given
* the center point of the explosion texture, distance to center of shield and
* right and up vectors.
*
* For small distances (relative to radius), coordinates can be computed using
* distance. For larger values, should compute angle.
*/
void rs_compute_uvs(shield_tri *stp, shield_vertex *verts, vec3d *tcp, float /*radius*/, vec3d *rightv, vec3d *upv)
{
int i;
shield_vertex *sv;
for (i=0; i<3; i++) {
vec3d v2cp;
sv = &verts[stp->verts[i]];
vm_vec_sub(&v2cp, &sv->pos, tcp);
sv->u = vm_vec_dot(&v2cp, rightv) * Shield_scale + 0.5f;
sv->v = - vm_vec_dot(&v2cp, upv) * Shield_scale + 0.5f;
CLAMP(sv->u, 0.0f, UV_MAX);
CLAMP(sv->v, 0.0f, UV_MAX);
}
}
/**
* Free records in ::Global_tris previously used by Shield_hits[shnum].tri_list
*/
void free_global_tri_records(int shnum)
{
int i;
Assert((shnum >= 0) && (shnum < MAX_SHIELD_HITS));
for (i=0; i<Shield_hits[shnum].num_tris; i++){
Global_tris[Shield_hits[shnum].tri_list[i]].used = 0;
}
}
void shield_render_low_detail_bitmap(int texture, float alpha, gshield_tri *trip, matrix *orient, vec3d *pos, ubyte r, ubyte g, ubyte b)
{
int j;
vec3d pnt;
vertex verts[4];
memset(verts, 0, sizeof(verts));
for (j=0; j<4; j++ ) {
// Rotate point into world coordinates
vm_vec_unrotate(&pnt, &trip->verts[j].pos, orient);
vm_vec_add2(&pnt, pos);
// Pnt is now the x,y,z world coordinates of this vert.
g3_transfer_vertex(&verts[j], &pnt);
verts[j].texture_position.u = trip->verts[j].u;
verts[j].texture_position.v = trip->verts[j].v;
}
verts[0].r = r;
verts[0].g = g;
verts[0].b = b;
verts[1].r = r;
verts[1].g = g;
verts[1].b = b;
verts[2].r = r;
verts[2].g = g;
verts[2].b = b;
verts[3].r = r;
verts[3].g = g;
verts[3].b = b;
vec3d norm;
vm_vec_perp(&norm, &trip->verts[0].pos, &trip->verts[1].pos, &trip->verts[2].pos);
//vertex *vertlist[4];
vertex vertlist[4];
if ( vm_vec_dot(&norm, &trip->verts[1].pos ) < 0.0 ) {
vertlist[0] = verts[3];
vertlist[1] = verts[2];
vertlist[2] = verts[1];
vertlist[3] = verts[0];
//vertlist[0] = &verts[3];
//vertlist[1] = &verts[2];
//vertlist[2] = &verts[1];
//vertlist[3] = &verts[0];
//g3_draw_poly( 4, vertlist, TMAP_FLAG_TEXTURED | TMAP_FLAG_RGB | TMAP_FLAG_GOURAUD | TMAP_HTL_3D_UNLIT);
} else {
vertlist[0] = verts[0];
vertlist[1] = verts[1];
vertlist[2] = verts[2];
vertlist[3] = verts[3];
//vertlist[0] = &verts[0];
//vertlist[1] = &verts[1];
//vertlist[2] = &verts[2];
//vertlist[3] = &verts[3];
//g3_draw_poly( 4, vertlist, TMAP_FLAG_TEXTURED | TMAP_FLAG_RGB | TMAP_FLAG_GOURAUD | TMAP_HTL_3D_UNLIT);
}
material material_params;
material_set_unlit_emissive(&material_params, texture, alpha, 2.0f);
g3_render_primitives_colored_textured(&material_params, vertlist, 4, PRIM_TYPE_TRIFAN, false);
}
/**
* Render one triangle of a shield hit effect on one ship.
* Each frame, the triangle needs to be rotated into global coords.
*
* @param texture handle to desired bitmap to render with
* @param alpha alpha value for color blending
* @param trip pointer to triangle in global array
* @param orient orientation of object shield is associated with
* @param pos center point of object
* @param r Red colour
* @param g Green colour
* @param b Blue colour
*/
void shield_render_triangle(int texture, float alpha, gshield_tri *trip, matrix *orient, vec3d *pos, ubyte r, ubyte g, ubyte b)
{
int j;
vec3d pnt;
vertex verts[3];
memset(&verts, 0, sizeof(verts));
if (trip->trinum == -1)
return; // Means this is a quad, must have switched detail_level.
for (j=0; j<3; j++ ) {
// Rotate point into world coordinates
vm_vec_unrotate(&pnt, &trip->verts[j].pos, orient);
vm_vec_add2(&pnt, pos);
// Pnt is now the x,y,z world coordinates of this vert.
// For this example, I am just drawing a sphere at that point.
g3_transfer_vertex(&verts[j],&pnt);
verts[j].texture_position.u = trip->verts[j].u;
verts[j].texture_position.v = trip->verts[j].v;
Assert((trip->verts[j].u >= 0.0f) && (trip->verts[j].u <= UV_MAX));
Assert((trip->verts[j].v >= 0.0f) && (trip->verts[j].v <= UV_MAX));
}
verts[0].r = r;
verts[0].g = g;
verts[0].b = b;
verts[1].r = r;
verts[1].g = g;
verts[1].b = b;
verts[2].r = r;
verts[2].g = g;
verts[2].b = b;
vec3d norm;
Poly_count++;
vm_vec_perp(&norm, &verts[0].world, &verts[1].world, &verts[2].world);
material material_params;
material_set_unlit(&material_params, texture, alpha, true, true);
material_params.set_color_scale(2.0f);
if ( vm_vec_dot(&norm, &verts[1].world) >= 0.0 ) {
vertex vertlist[3];
vertlist[0] = verts[2];
vertlist[1] = verts[1];
vertlist[2] = verts[0];
g3_render_primitives_colored_textured(&material_params, vertlist, 3, PRIM_TYPE_TRIFAN, false);
} else {
g3_render_primitives_colored_textured(&material_params, verts, 3, PRIM_TYPE_TRIFAN, false);
}
}
void shield_render_decal(polymodel *pm, matrix *orient, vec3d *pos, matrix* hit_orient, vec3d *hit_pos, float hit_radius, int bitmap_id, color *clr)
{
if (!pm->shield.buffer_id.isValid() || pm->shield.buffer_n_verts < 3) {
return;
}
g3_start_instance_matrix(pos, orient, true);
shield_material material_info;
material_info.set_texture_map(TM_BASE_TYPE, bitmap_id);
material_info.set_color(*clr);
material_info.set_blend_mode(bm_has_alpha_channel(bitmap_id) ? ALPHA_BLEND_ALPHA_BLEND_ALPHA : ALPHA_BLEND_ADDITIVE);
material_info.set_depth_mode(ZBUFFER_TYPE_READ);
material_info.set_impact_radius(hit_radius);
material_info.set_impact_transform(*hit_orient, *hit_pos);
material_info.set_cull_mode(false);
gr_render_shield_impact(&material_info, PRIM_TYPE_TRIS, &pm->shield.layout, pm->shield.buffer_id, pm->shield.buffer_n_verts);
g3_done_instance(true);
}
MONITOR(NumShieldRend)
/**
* Render a shield mesh in the global array ::Shield_hits[]
*/
void render_shield(int shield_num)
{
vec3d *centerp;
matrix *orient;
object *objp;
ship *shipp;
ship_info *si;
if (Shield_hits[shield_num].type == SH_UNUSED) {
return;
}
Assert(Shield_hits[shield_num].objnum >= 0);
objp = &Objects[Shield_hits[shield_num].objnum];
if (objp->flags[Object::Object_Flags::No_shields]) {
return;
}
// If this object didn't get rendered, don't render its shields. In fact, make the shield hit go away.
if (!(objp->flags[Object::Object_Flags::Was_rendered])) {
Shield_hits[shield_num].type = SH_UNUSED;
return;
}
// At detail levels 1, 3, animations play at double speed to reduce load.
if ( (Detail.shield_effects == 1) || (Detail.shield_effects == 3) ) {
Shield_hits[shield_num].start_time -= Frametime;
}
MONITOR_INC(NumShieldRend,1);
shipp = &Ships[objp->instance];
si = &Ship_info[shipp->ship_info_index];
// objp, shipp, and si are now setup correctly
// If this ship is in its deathroll, make the shield hit effects go away faster.
if (shipp->flags[Ship::Ship_Flags::Dying]) {
Shield_hits[shield_num].start_time -= fl2f(2*flFrametime);
}
// Detail level stuff. When lots of shield hits, maybe make them go away faster.
if (Poly_count > 50) {
if (Shield_hits[shield_num].start_time + (SHIELD_HIT_DURATION*50)/Poly_count < Missiontime) {
Shield_hits[shield_num].type = SH_UNUSED;
free_global_tri_records(shield_num);
return;
}
} else if ((Shield_hits[shield_num].start_time + SHIELD_HIT_DURATION) < Missiontime) {
Shield_hits[shield_num].type = SH_UNUSED;
free_global_tri_records(shield_num);
return;
}
orient = &objp->orient;
centerp = &objp->pos;
int bitmap_id, frame_num;
// Do some sanity checking
Assert( (si->species >= 0) && (si->species < (int)Species_info.size()) );
generic_anim *sa = &Species_info[si->species].shield_anim;
polymodel *pm = model_get(si->model_num);
// don't try to draw if we don't have an ani
if ( sa->first_frame >= 0 )
{
frame_num = bm_get_anim_frame(sa->first_frame, f2fl(Missiontime - Shield_hits[shield_num].start_time), f2fl(SHIELD_HIT_DURATION));
bitmap_id = sa->first_frame + frame_num;
float alpha = 0.9999f;
if(The_mission.flags[Mission::Mission_Flags::Fullneb]){
alpha *= neb2_get_fog_visibility(centerp, NEB_FOG_VISIBILITY_MULT_SHIELD);
}
ubyte r, g, b;
r = (ubyte)(Shield_hits[shield_num].rgb[0] * alpha);
g = (ubyte)(Shield_hits[shield_num].rgb[1] * alpha);
b = (ubyte)(Shield_hits[shield_num].rgb[2] * alpha);
if ( bitmap_id <= -1 ) {
return;
}
if ( (Detail.shield_effects == 1) || (Detail.shield_effects == 2) ) {
shield_render_low_detail_bitmap(bitmap_id, alpha, &Global_tris[Shield_hits[shield_num].tri_list[0]], orient, centerp, r, g, b);
} else if ( Detail.shield_effects < 4 ) {
for ( int i = 0; i < Shield_hits[shield_num].num_tris; i++ ) {
shield_render_triangle(bitmap_id, alpha, &Global_tris[Shield_hits[shield_num].tri_list[i]], orient, centerp, r, g, b);
}
} else {
float hit_radius = pm->core_radius;
if ( si->is_big_or_huge() ) {
hit_radius = pm->core_radius * 0.5f;
}
color clr;
gr_init_alphacolor(&clr, r, g, b, fl2i(alpha * 255.0f));
shield_render_decal(pm, orient, centerp, &Shield_hits[shield_num].hit_orient, &Shield_hits[shield_num].hit_pos, hit_radius, bitmap_id, &clr);
}
}
}
/**
* Render all the shield hits in the global array Shield_hits[]
*
* This is a temporary function. Shield hit rendering will at least have to
* occur with the ship, perhaps even internal to the ship.
*/
void render_shields()
{
GR_DEBUG_SCOPE("Render Shields");
TRACE_SCOPE(tracing::DrawShields);
int i;
if (Detail.shield_effects == 0){
return; // No shield effect rendered at lowest detail level.
}
for (i=0; i<MAX_SHIELD_HITS; i++){
if (Shield_hits[i].type != SH_UNUSED){
render_shield(i);
}
}
gr_clear_states();
}
void create_tris_containing(vec3d *vp, matrix *orient, shield_info *shieldp, vec3d *tcp, vec3d *centerp, float radius, vec3d *rvec, vec3d *uvec)
{
int i, j;
shield_vertex *verts;
verts = shieldp->verts;
for (i=0; i<Num_tris; i++) {
if ( !shieldp->tris[i].used ) {
for (j=0; j<3; j++) {
vec3d v;
v = verts[shieldp->tris[i].verts[j]].pos;
if ((vp->xyz.x == v.xyz.x) && (vp->xyz.y == v.xyz.y) && (vp->xyz.z == v.xyz.z))
create_shield_from_triangle(i, orient, shieldp, tcp, centerp, radius, rvec, uvec);
}
}
}
}
void visit_children(int trinum, int vertex_index, matrix *orient, shield_info *shieldp, vec3d *tcp, vec3d *centerp, float radius, vec3d *rvec, vec3d *uvec)
{
shield_vertex *sv;
sv = &(shieldp->verts[shieldp->tris[trinum].verts[vertex_index]]);
if ( (sv->u > 0.0f) && (sv->u < UV_MAX) && (sv->v > 0.0f) && (sv->v < UV_MAX))
create_tris_containing(&sv->pos, orient, shieldp, tcp, centerp, radius, rvec, uvec);
}
int get_free_global_shield_index()
{
int gi = 0;
while ((gi < MAX_SHIELD_TRI_BUFFER) && (Global_tris[gi].used) && (Global_tris[gi].creation_time + SHIELD_HIT_DURATION > Missiontime)) {
gi++;
}
// If couldn't find one, choose a random one.
if (gi == MAX_SHIELD_TRI_BUFFER)
gi = (int) (frand() * MAX_SHIELD_TRI_BUFFER);
return gi;
}
int get_global_shield_tri()
{
int shnum;
// Find unused shield hit buffer
for (shnum=0; shnum<MAX_SHIELD_HITS; shnum++)
if (Shield_hits[shnum].type == SH_UNUSED)
break;
if (shnum == MAX_SHIELD_HITS) {
shnum = myrand() % MAX_SHIELD_HITS;
}
Assert((shnum >= 0) && (shnum < MAX_SHIELD_HITS));
return shnum;
}
void create_shield_from_triangle(int trinum, matrix *orient, shield_info *shieldp, vec3d *tcp, vec3d *centerp, float radius, vec3d *rvec, vec3d *uvec)
{
rs_compute_uvs( &shieldp->tris[trinum], shieldp->verts, tcp, radius, rvec, uvec);
shieldp->tris[trinum].used = 1;
visit_children(trinum, 0, orient, shieldp, tcp, centerp, radius, rvec, uvec);
visit_children(trinum, 1, orient, shieldp, tcp, centerp, radius, rvec, uvec);
visit_children(trinum, 2, orient, shieldp, tcp, centerp, radius, rvec, uvec);
}
/**
* Copy information from Current_tris to ::Global_tris, stuffing information
* in a slot in ::Shield_hits.
*
* The Global_tris array is not a shield_tri structure.
* We need to store vertex information in the global array since the vertex list
* will not be available to us when we actually use the array.
*/
void copy_shield_to_globals( int objnum, shield_info *shieldp, matrix *hit_orient, vec3d *hit_pos )
{
int i, j;
int gi = 0;
int count = 0; // Number of triangles in this shield hit.
int shnum; // shield hit number, index in Shield_hits.
shnum = get_global_shield_tri();
Shield_hits[shnum].type = SH_TYPE_1;
for (i = 0; i < shieldp->ntris; i++ ) {
if ( shieldp->tris[i].used ) {
while ( (gi < MAX_SHIELD_TRI_BUFFER) && (Global_tris[gi].used) && (Global_tris[gi].creation_time + SHIELD_HIT_DURATION > Missiontime)) {
gi++;
}
// If couldn't find one, choose a random one.
if (gi == MAX_SHIELD_TRI_BUFFER)
gi = (int) (frand() * MAX_SHIELD_TRI_BUFFER);
Global_tris[gi].used = shieldp->tris[i].used;
Global_tris[gi].trinum = i;
Global_tris[gi].creation_time = Missiontime;
// copy the pos/u/v elements of the shield_vertex structure into the shield vertex structure for this global triangle.
for (j = 0; j < 3; j++)
Global_tris[gi].verts[j] = shieldp->verts[shieldp->tris[i].verts[j]];
Shield_hits[shnum].tri_list[count++] = gi;
if (count >= MAX_TRIS_PER_HIT) {
if (Detail.shield_effects < 4) {
mprintf(("Warning: Too many triangles in shield hit.\n"));
}
break;
}
}
}
Shield_hits[shnum].num_tris = count;
Shield_hits[shnum].start_time = Missiontime;
Shield_hits[shnum].objnum = objnum;
Shield_hits[shnum].hit_orient = *hit_orient;
Shield_hits[shnum].hit_pos = *hit_pos;
Shield_hits[shnum].rgb[0] = 255;
Shield_hits[shnum].rgb[1] = 255;
Shield_hits[shnum].rgb[2] = 255;
if((objnum >= 0) && (objnum < MAX_OBJECTS) && (Objects[objnum].type == OBJ_SHIP) && (Objects[objnum].instance >= 0) && (Objects[objnum].instance < MAX_SHIPS) && (Ships[Objects[objnum].instance].ship_info_index >= 0) && (Ships[Objects[objnum].instance].ship_info_index < ship_info_size())){
ship_info *sip = &Ship_info[Ships[Objects[objnum].instance].ship_info_index];
Shield_hits[shnum].rgb[0] = sip->shield_color[0];
Shield_hits[shnum].rgb[1] = sip->shield_color[1];
Shield_hits[shnum].rgb[2] = sip->shield_color[2];
}
}
/**
* This function needs to be called by big ships which have shields. It should be able to be modified to deal with
* the large polygons we use for their shield meshes - unknownplayer
*
* At lower detail levels, shield hit effects are a single texture, applied to one enlarged triangle.
*/
void create_shield_low_detail(int objnum, int /*model_num*/, matrix * /*orient*/, vec3d * /*centerp*/, vec3d *tcp, int tr0, shield_info *shieldp)
{
matrix tom;
int gi;
int shnum;
shnum = get_global_shield_tri();
Shield_hits[shnum].type = SH_TYPE_1;
gi = get_free_global_shield_index();
Global_tris[gi].used = 1;
Global_tris[gi].trinum = -1; // This tells triangle renderer to not render in case detail_level was switched.
Global_tris[gi].creation_time = Missiontime;
Shield_hits[shnum].tri_list[0] = gi;
Shield_hits[shnum].num_tris = 1;
Shield_hits[shnum].start_time = Missiontime;
Shield_hits[shnum].objnum = objnum;
Shield_hits[shnum].rgb[0] = 255;
Shield_hits[shnum].rgb[1] = 255;
Shield_hits[shnum].rgb[2] = 255;
if((objnum >= 0) && (objnum < MAX_OBJECTS) && (Objects[objnum].type == OBJ_SHIP) && (Objects[objnum].instance >= 0) && (Objects[objnum].instance < MAX_SHIPS) && (Ships[Objects[objnum].instance].ship_info_index >= 0) && (Ships[Objects[objnum].instance].ship_info_index < ship_info_size())){
ship_info *sip = &Ship_info[Ships[Objects[objnum].instance].ship_info_index];
Shield_hits[shnum].rgb[0] = sip->shield_color[0];
Shield_hits[shnum].rgb[1] = sip->shield_color[1];
Shield_hits[shnum].rgb[2] = sip->shield_color[2];
}
vm_vector_2_matrix(&tom, &shieldp->tris[tr0].norm, NULL, NULL);
create_low_detail_poly(gi, tcp, &tom.vec.rvec, &tom.vec.uvec);
}
// Algorithm for shrink-wrapping a texture across a triangular mesh.
//
// - Given a point of intersection, tcp (local to objnum)
// - Vector to center of shield from tcp is v2c.
// - Using v2c, compute right and down vectors. These are the vectors of
// increasing u and v, respectively.
// - Triangle of intersection of tcp is tr0.
// - For 3 points in tr0, compute u,v coordinates using up and down vectors
// from center point, tcp. Need to know size of explosion texture. N units
// along right vector corresponds to O units in explosion texture space.
// - For each edge, if either endpoint was outside texture bounds, recursively
// apply previous and current step.
//
// Output of above is a list of triangles with u,v coordinates. These u,v
// coordinates will have to be clipped against the explosion texture bounds.
void create_shield_explosion(int objnum, int model_num, matrix *orient, vec3d *centerp, vec3d *tcp, int tr0)
{
matrix tom; // Texture Orientation Matrix
shield_info *shieldp;
polymodel *pm;
int i;
if (Objects[objnum].flags[Object::Object_Flags::No_shields])
return;
pm = model_get(model_num);
Num_tris = pm->shield.ntris;
shieldp = &pm->shield;
if (Num_tris == 0)
return;
if ( (Detail.shield_effects == 1) || (Detail.shield_effects == 2) ) {
create_shield_low_detail(objnum, model_num, orient, centerp, tcp, tr0, shieldp);
return;
}
for (i=0; i<Num_tris; i++)
shieldp->tris[i].used = 0;
// Compute orientation matrix from normal of surface hit.
// Note, this will cause the shape of the bitmap to change abruptly
// as the impact point moves to another triangle. To prevent this,
// you could average the normals at the vertices, then interpolate the
// normals from the vertices to get a smoothly changing normal across the face.
// I had tried using the vector from the impact point to the center, which
// changes smoothly, but this looked surprisingly bad.
vm_vector_2_matrix(&tom, &shieldp->tris[tr0].norm, NULL, NULL);
// Create the shield from the current triangle, as well as its neighbors.
create_shield_from_triangle(tr0, orient, shieldp, tcp, centerp, Objects[objnum].radius, &tom.vec.rvec, &tom.vec.uvec);
for (i=0; i<3; i++)
create_shield_from_triangle(shieldp->tris[tr0].neighbors[i], orient, shieldp, tcp, centerp, Objects[objnum].radius, &tom.vec.rvec, &tom.vec.uvec);
copy_shield_to_globals(objnum, shieldp, &tom, tcp);
}
MONITOR(NumShieldHits)
/**
* Add data for a shield hit.
*/
void add_shield_point(int objnum, int tri_num, vec3d *hit_pos)
{
if (Num_shield_points >= MAX_SHIELD_POINTS)
return;
Verify(objnum < MAX_OBJECTS);
MONITOR_INC(NumShieldHits,1);
Shield_points[Num_shield_points].objnum = objnum;
Shield_points[Num_shield_points].shield_tri = tri_num;
Shield_points[Num_shield_points].hit_point = *hit_pos;
Num_shield_points++;
Ships[Objects[objnum].instance].shield_hits++;
}
// ugh! I wrote a special routine to store shield points for clients in multiplayer
// games. Problem is initilization and flow control of normal gameplay make this problem
// more than trivial to solve. Turns out that I think I can just keep track of the
// shield_points for multiplayer in a separate count -- then assign the multi count to
// the normal count at the correct time.
void add_shield_point_multi(int objnum, int tri_num, vec3d *hit_pos)
{
if (Num_multi_shield_points >= MAX_SHIELD_POINTS)
return;
Shield_points[Num_shield_points].objnum = objnum;
Shield_points[Num_shield_points].shield_tri = tri_num;
Shield_points[Num_shield_points].hit_point = *hit_pos;
Num_multi_shield_points++;
}
/**
* Sets up the shield point hit information for multiplayer clients
*/
void shield_point_multi_setup()
{
int i;
Assert( MULTIPLAYER_CLIENT );
if ( Num_multi_shield_points == 0 )
return;
Num_shield_points = Num_multi_shield_points;
for (i = 0; i < Num_shield_points; i++ ){
Ships[Objects[Shield_points[i].objnum].instance].shield_hits++;
}
Num_multi_shield_points = 0;
}
/**
* Create all the shield explosions that occurred on object *objp this frame.
*/
void create_shield_explosion_all(object *objp)
{
int i;
int num;
int count;
int objnum;
ship *shipp;
if (Detail.shield_effects == 0){
return;
}
num = objp->instance;
shipp = &Ships[num];
count = shipp->shield_hits;
objnum = OBJ_INDEX(objp);
for (i=0; i<Num_shield_points; i++) {
if (Shield_points[i].objnum == objnum) {
create_shield_explosion(objnum, Ship_info[shipp->ship_info_index].model_num, &objp->orient, &objp->pos, &Shield_points[i].hit_point, Shield_points[i].shield_tri);
count--;
if (count <= 0){
break;
}
}
}
// some some reason, clients seem to have a bogus count valud on occation. I"ll chalk it up
// to missed packets :-) MWA 2/6/98
if ( !MULTIPLAYER_CLIENT ) {
Assert(count == 0); // Couldn't find all the alleged shield hits. Bogus!
}
}
/**
* Returns true if the shield presents any opposition to something trying to force through it.
*
* @return If quadrant is -1, looks at entire shield, otherwise just one quadrant
*/
int ship_is_shield_up( object *obj, int quadrant )
{
if ( (quadrant >= 0) && (quadrant < obj->n_quadrants)) {
// Just check one quadrant
if (obj->shield_quadrant[quadrant] > MAX(2.0f, 0.1f * shield_get_max_quad(obj))) {
return 1;
}
} else {
// Check all quadrants
float strength = shield_get_strength(obj);
if ( strength > MAX(2.0f*4.0f, 0.1f * shield_get_max_strength(obj)) ) {
return 1;
}
}
return 0; // no shield strength
}
// return quadrant containing hit_pnt.
// \ 1 /.
// 3 \ / 0
// / \.
// / 2 \.
// Note: This is in the object's local reference frame. Do _not_ pass a vector in the world frame.
int get_quadrant(vec3d *hit_pnt, object *shipobjp)
{
if (shipobjp != NULL && Ship_info[Ships[shipobjp->instance].ship_info_index].flags[Ship::Info_Flags::Model_point_shields]) {
int closest = -1;
float closest_dist = FLT_MAX;
for (unsigned int i=0; i<Ships[shipobjp->instance].shield_points.size(); i++) {
float dist = vm_vec_dist(hit_pnt, &Ships[shipobjp->instance].shield_points.at(i));
if (dist < closest_dist) {
closest = i;
closest_dist = dist;
}
}
return closest;
} else {
int result = 0;
if (hit_pnt->xyz.x < hit_pnt->xyz.z)
result |= 1;
if (hit_pnt->xyz.x < -hit_pnt->xyz.z)
result |= 2;
return result;
}
}
| 30.736565 | 290 | 0.69759 | [
"mesh",
"render",
"object",
"shape",
"vector",
"model",
"3d"
] |
739059bdafe21f6028dd6ee539db06783135e0ea | 21,587 | cc | C++ | cc/test/render_pass_test_utils.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | cc/test/render_pass_test_utils.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | cc/test/render_pass_test_utils.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/test/render_pass_test_utils.h"
#include <stdint.h>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "components/viz/client/client_resource_provider.h"
#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h"
#include "components/viz/common/quads/compositor_render_pass_draw_quad.h"
#include "components/viz/common/quads/debug_border_draw_quad.h"
#include "components/viz/common/quads/shared_quad_state.h"
#include "components/viz/common/quads/solid_color_draw_quad.h"
#include "components/viz/common/quads/stream_video_draw_quad.h"
#include "components/viz/common/quads/texture_draw_quad.h"
#include "components/viz/common/quads/tile_draw_quad.h"
#include "components/viz/common/quads/yuv_video_draw_quad.h"
#include "components/viz/common/resources/returned_resource.h"
#include "components/viz/common/resources/transferable_resource.h"
#include "components/viz/service/display/display_resource_provider.h"
#include "gpu/command_buffer/common/sync_token.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkImageFilter.h"
#include "ui/gfx/geometry/rect.h"
namespace cc {
namespace {
viz::ResourceId CreateAndImportResource(
viz::ClientResourceProvider* resource_provider,
const gpu::SyncToken& sync_token,
gfx::ColorSpace color_space = gfx::ColorSpace::CreateSRGB()) {
constexpr gfx::Size size(64, 64);
auto transfer_resource = viz::TransferableResource::MakeGL(
gpu::Mailbox::Generate(), GL_LINEAR, GL_TEXTURE_2D, sync_token, size,
false /* is_overlay_candidate */);
transfer_resource.color_space = std::move(color_space);
return resource_provider->ImportResource(
transfer_resource, viz::SingleReleaseCallback::Create(base::DoNothing()));
}
} // anonymous namespace
viz::CompositorRenderPass* AddRenderPass(
viz::CompositorRenderPassList* pass_list,
viz::CompositorRenderPassId render_pass_id,
const gfx::Rect& output_rect,
const gfx::Transform& root_transform,
const FilterOperations& filters) {
auto pass = viz::CompositorRenderPass::Create();
pass->SetNew(render_pass_id, output_rect, output_rect, root_transform);
pass->filters = filters;
viz::CompositorRenderPass* saved = pass.get();
pass_list->push_back(std::move(pass));
return saved;
}
viz::AggregatedRenderPass* AddRenderPass(
viz::AggregatedRenderPassList* pass_list,
viz::AggregatedRenderPassId render_pass_id,
const gfx::Rect& output_rect,
const gfx::Transform& root_transform,
const FilterOperations& filters) {
auto pass = std::make_unique<viz::AggregatedRenderPass>();
pass->SetNew(render_pass_id, output_rect, output_rect, root_transform);
pass->filters = filters;
auto* saved = pass.get();
pass_list->push_back(std::move(pass));
return saved;
}
viz::CompositorRenderPass* AddRenderPassWithDamage(
viz::CompositorRenderPassList* pass_list,
viz::CompositorRenderPassId render_pass_id,
const gfx::Rect& output_rect,
const gfx::Rect& damage_rect,
const gfx::Transform& root_transform,
const FilterOperations& filters) {
auto pass = viz::CompositorRenderPass::Create();
pass->SetNew(render_pass_id, output_rect, damage_rect, root_transform);
pass->filters = filters;
viz::CompositorRenderPass* saved = pass.get();
pass_list->push_back(std::move(pass));
return saved;
}
viz::AggregatedRenderPass* AddRenderPassWithDamage(
viz::AggregatedRenderPassList* pass_list,
viz::AggregatedRenderPassId render_pass_id,
const gfx::Rect& output_rect,
const gfx::Rect& damage_rect,
const gfx::Transform& root_transform,
const FilterOperations& filters) {
auto pass = std::make_unique<viz::AggregatedRenderPass>();
pass->SetNew(render_pass_id, output_rect, damage_rect, root_transform);
pass->filters = filters;
auto* saved = pass.get();
pass_list->push_back(std::move(pass));
return saved;
}
viz::SolidColorDrawQuad* AddClippedQuad(viz::AggregatedRenderPass* pass,
const gfx::Rect& rect,
SkColor color) {
viz::SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(gfx::Transform(), rect, rect, gfx::MaskFilterInfo(),
rect, true, false, 1, SkBlendMode::kSrcOver, 0);
auto* quad = pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
quad->SetNew(shared_state, rect, rect, color, false);
return quad;
}
viz::SolidColorDrawQuad* AddTransformedQuad(viz::AggregatedRenderPass* pass,
const gfx::Rect& rect,
SkColor color,
const gfx::Transform& transform) {
viz::SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(transform, rect, rect, gfx::MaskFilterInfo(), rect,
false, false, 1,
SkBlendMode::kSrcOver, 0);
auto* quad = pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
quad->SetNew(shared_state, rect, rect, color, false);
return quad;
}
template <typename QuadType, typename RenderPassType>
QuadType* AddRenderPassQuadInternal(RenderPassType* to_pass,
RenderPassType* contributing_pass) {
gfx::Rect output_rect = contributing_pass->output_rect;
viz::SharedQuadState* shared_state =
to_pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(gfx::Transform(), output_rect, output_rect,
gfx::MaskFilterInfo(), output_rect, false, false, 1,
SkBlendMode::kSrcOver, 0);
auto* quad = to_pass->template CreateAndAppendDrawQuad<QuadType>();
quad->SetNew(shared_state, output_rect, output_rect, contributing_pass->id,
viz::kInvalidResourceId, gfx::RectF(), gfx::Size(),
gfx::Vector2dF(), gfx::PointF(), gfx::RectF(), false, 1.0f);
return quad;
}
viz::CompositorRenderPassDrawQuad* AddRenderPassQuad(
viz::CompositorRenderPass* to_pass,
viz::CompositorRenderPass* contributing_pass) {
return AddRenderPassQuadInternal<viz::CompositorRenderPassDrawQuad>(
to_pass, contributing_pass);
}
viz::AggregatedRenderPassDrawQuad* AddRenderPassQuad(
viz::AggregatedRenderPass* to_pass,
viz::AggregatedRenderPass* contributing_pass) {
return AddRenderPassQuadInternal<viz::AggregatedRenderPassDrawQuad>(
to_pass, contributing_pass);
}
void AddRenderPassQuad(viz::AggregatedRenderPass* to_pass,
viz::AggregatedRenderPass* contributing_pass,
viz::ResourceId mask_resource_id,
gfx::Transform transform,
SkBlendMode blend_mode) {
gfx::Rect output_rect = contributing_pass->output_rect;
viz::SharedQuadState* shared_state =
to_pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(transform, output_rect, output_rect,
gfx::MaskFilterInfo(), output_rect, false, false, 1,
blend_mode, 0);
auto* quad =
to_pass->CreateAndAppendDrawQuad<viz::AggregatedRenderPassDrawQuad>();
gfx::Size arbitrary_nonzero_size(1, 1);
quad->SetNew(shared_state, output_rect, output_rect, contributing_pass->id,
mask_resource_id, gfx::RectF(output_rect),
arbitrary_nonzero_size, gfx::Vector2dF(), gfx::PointF(),
gfx::RectF(), false, 1.0f);
}
std::vector<viz::ResourceId> AddOneOfEveryQuadType(
viz::CompositorRenderPass* to_pass,
viz::ClientResourceProvider* resource_provider,
viz::CompositorRenderPassId child_pass_id) {
gfx::Rect rect(0, 0, 100, 100);
gfx::Rect visible_rect(0, 0, 100, 100);
bool needs_blending = true;
const float vertex_opacity[] = {1.0f, 1.0f, 1.0f, 1.0f};
static const gpu::SyncToken kSyncToken(
gpu::CommandBufferNamespace::GPU_IO,
gpu::CommandBufferId::FromUnsafeValue(0x123), 30);
viz::ResourceId resource1 =
CreateAndImportResource(resource_provider, kSyncToken);
viz::ResourceId resource2 =
CreateAndImportResource(resource_provider, kSyncToken);
viz::ResourceId resource3 =
CreateAndImportResource(resource_provider, kSyncToken);
viz::ResourceId resource4 =
CreateAndImportResource(resource_provider, kSyncToken);
viz::ResourceId resource5 =
CreateAndImportResource(resource_provider, kSyncToken);
viz::ResourceId resource6 =
CreateAndImportResource(resource_provider, kSyncToken);
viz::ResourceId resource8 =
CreateAndImportResource(resource_provider, kSyncToken);
viz::ResourceId plane_resources[4];
for (int i = 0; i < 4; ++i) {
plane_resources[i] = CreateAndImportResource(
resource_provider, kSyncToken, gfx::ColorSpace::CreateREC601());
}
viz::SharedQuadState* shared_state =
to_pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(gfx::Transform(), rect, rect, gfx::MaskFilterInfo(),
rect, false, false, 1, SkBlendMode::kSrcOver, 0);
auto* debug_border_quad =
to_pass->CreateAndAppendDrawQuad<viz::DebugBorderDrawQuad>();
debug_border_quad->SetNew(shared_state, rect, visible_rect, SK_ColorRED, 1);
if (child_pass_id) {
auto* render_pass_quad =
to_pass->CreateAndAppendDrawQuad<viz::CompositorRenderPassDrawQuad>();
render_pass_quad->SetNew(shared_state, rect, visible_rect, child_pass_id,
resource5, gfx::RectF(rect), gfx::Size(73, 26),
gfx::Vector2dF(), gfx::PointF(), gfx::RectF(),
false, 1.0f);
}
auto* solid_color_quad =
to_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
solid_color_quad->SetNew(shared_state, rect, visible_rect, SK_ColorRED,
false);
auto* stream_video_quad =
to_pass->CreateAndAppendDrawQuad<viz::StreamVideoDrawQuad>();
stream_video_quad->SetNew(shared_state, rect, visible_rect, needs_blending,
resource6, gfx::Size(), gfx::PointF(),
gfx::PointF(1.f, 1.f));
auto* texture_quad = to_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>();
texture_quad->SetNew(
shared_state, rect, visible_rect, needs_blending, resource1, false,
gfx::PointF(0.f, 0.f), gfx::PointF(1.f, 1.f), SK_ColorTRANSPARENT,
vertex_opacity, false, false, false, gfx::ProtectedVideoType::kClear);
auto* external_resource_texture_quad =
to_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>();
external_resource_texture_quad->SetNew(
shared_state, rect, visible_rect, needs_blending, resource8, false,
gfx::PointF(0.f, 0.f), gfx::PointF(1.f, 1.f), SK_ColorTRANSPARENT,
vertex_opacity, false, false, false, gfx::ProtectedVideoType::kClear);
auto* scaled_tile_quad =
to_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>();
scaled_tile_quad->SetNew(shared_state, rect, visible_rect, needs_blending,
resource2, gfx::RectF(0, 0, 50, 50),
gfx::Size(50, 50), false, false, false);
viz::SharedQuadState* transformed_state =
to_pass->CreateAndAppendSharedQuadState();
*transformed_state = *shared_state;
gfx::Transform rotation;
rotation.Rotate(45);
transformed_state->quad_to_target_transform =
transformed_state->quad_to_target_transform * rotation;
auto* transformed_tile_quad =
to_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>();
transformed_tile_quad->SetNew(
transformed_state, rect, visible_rect, needs_blending, resource3,
gfx::RectF(0, 0, 100, 100), gfx::Size(100, 100), false, false, false);
viz::SharedQuadState* shared_state2 =
to_pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(gfx::Transform(), rect, rect, gfx::MaskFilterInfo(),
rect, false, false, 1, SkBlendMode::kSrcOver, 0);
auto* tile_quad = to_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>();
tile_quad->SetNew(shared_state2, rect, visible_rect, needs_blending,
resource4, gfx::RectF(0, 0, 100, 100), gfx::Size(100, 100),
false, false, false);
auto* yuv_quad = to_pass->CreateAndAppendDrawQuad<viz::YUVVideoDrawQuad>();
yuv_quad->SetNew(shared_state2, rect, visible_rect, needs_blending,
gfx::RectF(.0f, .0f, 100.0f, 100.0f),
gfx::RectF(.0f, .0f, 50.0f, 50.0f), gfx::Size(100, 100),
gfx::Size(50, 50), plane_resources[0], plane_resources[1],
plane_resources[2], plane_resources[3],
gfx::ColorSpace::CreateREC601(), 0.0, 1.0, 8);
return {resource1, resource2, resource3,
resource4, resource5, resource6,
resource8, plane_resources[0], plane_resources[1],
plane_resources[2], plane_resources[3]};
}
static void CollectResources(
std::vector<viz::ReturnedResource>* array,
const std::vector<viz::ReturnedResource>& returned) {}
void AddOneOfEveryQuadTypeInDisplayResourceProvider(
viz::AggregatedRenderPass* to_pass,
viz::DisplayResourceProvider* resource_provider,
viz::ClientResourceProvider* child_resource_provider,
viz::ContextProvider* child_context_provider,
viz::AggregatedRenderPassId child_pass_id,
gpu::SyncToken* sync_token_for_mailbox_tebxture) {
gfx::Rect rect(0, 0, 100, 100);
gfx::Rect visible_rect(0, 0, 100, 100);
bool needs_blending = true;
const float vertex_opacity[] = {1.0f, 1.0f, 1.0f, 1.0f};
static const gpu::SyncToken kDefaultSyncToken(
gpu::CommandBufferNamespace::GPU_IO,
gpu::CommandBufferId::FromUnsafeValue(0x111), 42);
static const gpu::SyncToken kSyncTokenForMailboxTextureQuad(
gpu::CommandBufferNamespace::GPU_IO,
gpu::CommandBufferId::FromUnsafeValue(0x123), 30);
*sync_token_for_mailbox_tebxture = kSyncTokenForMailboxTextureQuad;
viz::ResourceId resource1 =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken);
viz::ResourceId resource2 =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken);
viz::ResourceId resource3 =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken);
viz::ResourceId resource4 =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken);
viz::ResourceId resource5 =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken);
viz::ResourceId resource6 =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken);
viz::ResourceId resource7 =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken);
viz::ResourceId resource8 = CreateAndImportResource(
child_resource_provider, kSyncTokenForMailboxTextureQuad);
// Transfer resource to the parent.
std::vector<viz::ResourceId> resource_ids_to_transfer;
resource_ids_to_transfer.push_back(resource1);
resource_ids_to_transfer.push_back(resource2);
resource_ids_to_transfer.push_back(resource3);
resource_ids_to_transfer.push_back(resource4);
resource_ids_to_transfer.push_back(resource5);
resource_ids_to_transfer.push_back(resource6);
resource_ids_to_transfer.push_back(resource7);
resource_ids_to_transfer.push_back(resource8);
viz::ResourceId plane_resources[4];
for (int i = 0; i < 4; ++i) {
plane_resources[i] =
CreateAndImportResource(child_resource_provider, kDefaultSyncToken,
gfx::ColorSpace::CreateREC601());
resource_ids_to_transfer.push_back(plane_resources[i]);
}
std::vector<viz::ReturnedResource> returned_to_child;
int child_id = resource_provider->CreateChild(
base::BindRepeating(&CollectResources, &returned_to_child));
// Transfer resource to the parent.
std::vector<viz::TransferableResource> list;
child_resource_provider->PrepareSendToParent(resource_ids_to_transfer, &list,
child_context_provider);
resource_provider->ReceiveFromChild(child_id, list);
// Delete them in the child so they won't be leaked, and will be released once
// returned from the parent. This assumes they won't need to be sent to the
// parent again.
for (viz::ResourceId id : resource_ids_to_transfer)
child_resource_provider->RemoveImportedResource(id);
// Before create DrawQuad in viz::DisplayResourceProvider's namespace, get the
// mapped resource id first.
std::unordered_map<viz::ResourceId, viz::ResourceId, viz::ResourceIdHasher>
resource_map = resource_provider->GetChildToParentMap(child_id);
viz::ResourceId mapped_resource1 = resource_map[resource1];
viz::ResourceId mapped_resource2 = resource_map[resource2];
viz::ResourceId mapped_resource3 = resource_map[resource3];
viz::ResourceId mapped_resource4 = resource_map[resource4];
viz::ResourceId mapped_resource5 = resource_map[resource5];
viz::ResourceId mapped_resource6 = resource_map[resource6];
viz::ResourceId mapped_resource8 = resource_map[resource8];
viz::ResourceId mapped_plane_resources[4];
for (int i = 0; i < 4; ++i) {
mapped_plane_resources[i] = resource_map[plane_resources[i]];
}
viz::SharedQuadState* shared_state =
to_pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(gfx::Transform(), rect, rect, gfx::MaskFilterInfo(),
rect, false, false, 1, SkBlendMode::kSrcOver, 0);
viz::DebugBorderDrawQuad* debug_border_quad =
to_pass->CreateAndAppendDrawQuad<viz::DebugBorderDrawQuad>();
debug_border_quad->SetNew(shared_state, rect, visible_rect, SK_ColorRED, 1);
if (child_pass_id) {
auto* render_pass_quad =
to_pass->CreateAndAppendDrawQuad<viz::AggregatedRenderPassDrawQuad>();
render_pass_quad->SetNew(shared_state, rect, visible_rect, child_pass_id,
mapped_resource5, gfx::RectF(rect),
gfx::Size(73, 26), gfx::Vector2dF(), gfx::PointF(),
gfx::RectF(), false, 1.0f);
}
viz::SolidColorDrawQuad* solid_color_quad =
to_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
solid_color_quad->SetNew(shared_state, rect, visible_rect, SK_ColorRED,
false);
viz::StreamVideoDrawQuad* stream_video_quad =
to_pass->CreateAndAppendDrawQuad<viz::StreamVideoDrawQuad>();
stream_video_quad->SetNew(shared_state, rect, visible_rect, needs_blending,
mapped_resource6, gfx::Size(), gfx::PointF(),
gfx::PointF(1.f, 1.f));
viz::TextureDrawQuad* texture_quad =
to_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>();
texture_quad->SetNew(
shared_state, rect, visible_rect, needs_blending, mapped_resource1, false,
gfx::PointF(0.f, 0.f), gfx::PointF(1.f, 1.f), SK_ColorTRANSPARENT,
vertex_opacity, false, false, false, gfx::ProtectedVideoType::kClear);
viz::TextureDrawQuad* external_resource_texture_quad =
to_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>();
external_resource_texture_quad->SetNew(
shared_state, rect, visible_rect, needs_blending, mapped_resource8, false,
gfx::PointF(0.f, 0.f), gfx::PointF(1.f, 1.f), SK_ColorTRANSPARENT,
vertex_opacity, false, false, false, gfx::ProtectedVideoType::kClear);
viz::TileDrawQuad* scaled_tile_quad =
to_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>();
scaled_tile_quad->SetNew(shared_state, rect, visible_rect, needs_blending,
mapped_resource2, gfx::RectF(0, 0, 50, 50),
gfx::Size(50, 50), false, false, false);
viz::SharedQuadState* transformed_state =
to_pass->CreateAndAppendSharedQuadState();
*transformed_state = *shared_state;
gfx::Transform rotation;
rotation.Rotate(45);
transformed_state->quad_to_target_transform =
transformed_state->quad_to_target_transform * rotation;
viz::TileDrawQuad* transformed_tile_quad =
to_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>();
transformed_tile_quad->SetNew(
transformed_state, rect, visible_rect, needs_blending, mapped_resource3,
gfx::RectF(0, 0, 100, 100), gfx::Size(100, 100), false, false, false);
viz::SharedQuadState* shared_state2 =
to_pass->CreateAndAppendSharedQuadState();
shared_state2->SetAll(gfx::Transform(), rect, rect, gfx::MaskFilterInfo(),
rect, false, false, 1, SkBlendMode::kSrcOver, 0);
viz::TileDrawQuad* tile_quad =
to_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>();
tile_quad->SetNew(shared_state2, rect, visible_rect, needs_blending,
mapped_resource4, gfx::RectF(0, 0, 100, 100),
gfx::Size(100, 100), false, false, false);
viz::YUVVideoDrawQuad* yuv_quad =
to_pass->CreateAndAppendDrawQuad<viz::YUVVideoDrawQuad>();
yuv_quad->SetNew(
shared_state2, rect, visible_rect, needs_blending,
gfx::RectF(.0f, .0f, 100.0f, 100.0f), gfx::RectF(.0f, .0f, 50.0f, 50.0f),
gfx::Size(100, 100), gfx::Size(50, 50), mapped_plane_resources[0],
mapped_plane_resources[1], mapped_plane_resources[2],
mapped_plane_resources[3], gfx::ColorSpace::CreateREC601(), 0.0, 1.0, 8);
}
} // namespace cc
| 45.066806 | 80 | 0.707231 | [
"geometry",
"vector",
"transform"
] |
73922064f61340c09c1b6afacbfe3d25f1d712d7 | 13,604 | cpp | C++ | Util/OSM2ODR/src/netbuild/NBHeightMapper.cpp | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 5 | 2020-12-14T00:33:42.000Z | 2021-12-22T07:41:49.000Z | Util/OSM2ODR/src/netbuild/NBHeightMapper.cpp | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 2 | 2021-03-31T19:58:35.000Z | 2021-12-13T20:47:16.000Z | Util/OSM2ODR/src/netbuild/NBHeightMapper.cpp | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 4 | 2021-04-15T03:45:53.000Z | 2021-12-24T13:13:39.000Z | /****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file NBHeightMapper.cpp
/// @author Jakob Erdmann
/// @author Laura Bieker
/// @author Michael Behrisch
/// @date Sept 2011
///
// Set z-values for all network positions based on data from a height map
/****************************************************************************/
#include <config.h>
#include <string>
#include <utils/common/MsgHandler.h>
#include <utils/common/ToString.h>
#include <utils/common/StringUtils.h>
#include <utils/options/OptionsCont.h>
#include <utils/geom/GeomHelper.h>
#include "NBHeightMapper.h"
#include <utils/geom/GeoConvHelper.h>
#include <utils/common/RGBColor.h>
#ifdef HAVE_GDAL
#if __GNUC__ > 3
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
#include <ogrsf_frmts.h>
#include <ogr_api.h>
#include <gdal_priv.h>
#if __GNUC__ > 3
#pragma GCC diagnostic pop
#endif
#endif
// ===========================================================================
// static members
// ===========================================================================
NBHeightMapper NBHeightMapper::myInstance;
// ===========================================================================
// method definitions
// ===========================================================================
NBHeightMapper::NBHeightMapper():
myRTree(&Triangle::addSelf) {
}
NBHeightMapper::~NBHeightMapper() {
clearData();
}
const NBHeightMapper&
NBHeightMapper::get() {
return myInstance;
}
bool
NBHeightMapper::ready() const {
return myRasters.size() > 0 || myTriangles.size() > 0;
}
double
NBHeightMapper::getZ(const Position& geo) const {
if (!ready()) {
WRITE_WARNING("Cannot supply height since no height data was loaded");
return 0;
}
for (auto& item : myRasters) {
const Boundary& boundary = item.first;
int16_t* raster = item.second;
double result = -1e6;
if (boundary.around(geo)) {
const int xSize = int((boundary.xmax() - boundary.xmin()) / mySizeOfPixel.x() + .5);
const double normX = (geo.x() - boundary.xmin()) / mySizeOfPixel.x();
const double normY = (geo.y() - boundary.ymax()) / mySizeOfPixel.y();
PositionVector corners;
corners.push_back(Position(floor(normX) + 0.5, floor(normY) + 0.5, raster[(int)normY * xSize + (int)normX]));
if (normX - floor(normX) > 0.5) {
corners.push_back(Position(floor(normX) + 1.5, floor(normY) + 0.5, raster[(int)normY * xSize + (int)normX + 1]));
} else {
corners.push_back(Position(floor(normX) - 0.5, floor(normY) + 0.5, raster[(int)normY * xSize + (int)normX - 1]));
}
if (normY - floor(normY) > 0.5) {
corners.push_back(Position(floor(normX) + 0.5, floor(normY) + 1.5, raster[((int)normY + 1) * xSize + (int)normX]));
} else {
corners.push_back(Position(floor(normX) + 0.5, floor(normY) - 0.5, raster[((int)normY - 1) * xSize + (int)normX]));
}
result = Triangle(corners).getZ(Position(normX, normY));
}
if (result > -1e5 && result < 1e5) {
return result;
}
}
// coordinates in degrees hence a small search window
float minB[2];
float maxB[2];
minB[0] = (float)geo.x() - 0.00001f;
minB[1] = (float)geo.y() - 0.00001f;
maxB[0] = (float)geo.x() + 0.00001f;
maxB[1] = (float)geo.y() + 0.00001f;
QueryResult queryResult;
int hits = myRTree.Search(minB, maxB, queryResult);
Triangles result = queryResult.triangles;
assert(hits == (int)result.size());
UNUSED_PARAMETER(hits); // only used for assertion
for (Triangles::iterator it = result.begin(); it != result.end(); it++) {
const Triangle* triangle = *it;
if (triangle->contains(geo)) {
return triangle->getZ(geo);
}
}
WRITE_WARNING("Could not get height data for coordinate " + toString(geo));
return 0;
}
void
NBHeightMapper::addTriangle(PositionVector corners) {
Triangle* triangle = new Triangle(corners);
myTriangles.push_back(triangle);
Boundary b = corners.getBoxBoundary();
const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
myRTree.Insert(cmin, cmax, triangle);
}
void
NBHeightMapper::loadIfSet(OptionsCont& oc) {
if (oc.isSet("heightmap.geotiff")) {
// parse file(s)
std::vector<std::string> files = oc.getStringVector("heightmap.geotiff");
for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
PROGRESS_BEGIN_MESSAGE("Parsing from GeoTIFF '" + *file + "'");
int numFeatures = myInstance.loadTiff(*file);
MsgHandler::getMessageInstance()->endProcessMsg(
" done (parsed " + toString(numFeatures) +
" features, Boundary: " + toString(myInstance.getBoundary()) + ").");
}
}
if (oc.isSet("heightmap.shapefiles")) {
// parse file(s)
std::vector<std::string> files = oc.getStringVector("heightmap.shapefiles");
for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
PROGRESS_BEGIN_MESSAGE("Parsing from shape-file '" + *file + "'");
int numFeatures = myInstance.loadShapeFile(*file);
MsgHandler::getMessageInstance()->endProcessMsg(
" done (parsed " + toString(numFeatures) +
" features, Boundary: " + toString(myInstance.getBoundary()) + ").");
}
}
}
int
NBHeightMapper::loadShapeFile(const std::string& file) {
#ifdef HAVE_GDAL
#if GDAL_VERSION_MAJOR < 2
OGRRegisterAll();
OGRDataSource* ds = OGRSFDriverRegistrar::Open(file.c_str(), FALSE);
#else
GDALAllRegister();
GDALDataset* ds = (GDALDataset*)GDALOpenEx(file.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, nullptr, nullptr, nullptr);
#endif
if (ds == nullptr) {
throw ProcessError("Could not open shape file '" + file + "'.");
}
// begin file parsing
OGRLayer* layer = ds->GetLayer(0);
layer->ResetReading();
// triangle coordinates are stored in WGS84 and later matched with network coordinates in WGS84
// build coordinate transformation
OGRSpatialReference* sr_src = layer->GetSpatialRef();
OGRSpatialReference sr_dest;
sr_dest.SetWellKnownGeogCS("WGS84");
OGRCoordinateTransformation* toWGS84 = OGRCreateCoordinateTransformation(sr_src, &sr_dest);
if (toWGS84 == nullptr) {
WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed.");
}
int numFeatures = 0;
OGRFeature* feature;
layer->ResetReading();
while ((feature = layer->GetNextFeature()) != nullptr) {
OGRGeometry* geom = feature->GetGeometryRef();
assert(geom != 0);
// @todo gracefull handling of shapefiles with unexpected contents or any error handling for that matter
assert(std::string(geom->getGeometryName()) == std::string("POLYGON"));
// try transform to wgs84
geom->transform(toWGS84);
OGRLinearRing* cgeom = ((OGRPolygon*) geom)->getExteriorRing();
// assume TIN with with 4 points and point0 == point3
assert(cgeom->getNumPoints() == 4);
PositionVector corners;
for (int j = 0; j < 3; j++) {
Position pos((double) cgeom->getX(j), (double) cgeom->getY(j), (double) cgeom->getZ(j));
corners.push_back(pos);
myBoundary.add(pos);
}
addTriangle(corners);
numFeatures++;
/*
OGRwkbGeometryType gtype = geom->getGeometryType();
switch (gtype) {
case wkbPolygon: {
break;
}
case wkbPoint: {
WRITE_WARNING("got wkbPoint");
break;
}
case wkbLineString: {
WRITE_WARNING("got wkbLineString");
break;
}
case wkbMultiPoint: {
WRITE_WARNING("got wkbMultiPoint");
break;
}
case wkbMultiLineString: {
WRITE_WARNING("got wkbMultiLineString");
break;
}
case wkbMultiPolygon: {
WRITE_WARNING("got wkbMultiPolygon");
break;
}
default:
WRITE_WARNING("Unsupported shape type occurred");
break;
}
*/
OGRFeature::DestroyFeature(feature);
}
#if GDAL_VERSION_MAJOR < 2
OGRDataSource::DestroyDataSource(ds);
#else
GDALClose(ds);
#endif
OCTDestroyCoordinateTransformation(reinterpret_cast<OGRCoordinateTransformationH>(toWGS84));
OGRCleanupAll();
return numFeatures;
#else
UNUSED_PARAMETER(file);
WRITE_ERROR("Cannot load shape file since SUMO was compiled without GDAL support.");
return 0;
#endif
}
int
NBHeightMapper::loadTiff(const std::string& file) {
#ifdef HAVE_GDAL
GDALAllRegister();
GDALDataset* poDataset = (GDALDataset*)GDALOpen(file.c_str(), GA_ReadOnly);
if (poDataset == 0) {
WRITE_ERROR("Cannot load GeoTIFF file.");
return 0;
}
Boundary boundary;
const int xSize = poDataset->GetRasterXSize();
const int ySize = poDataset->GetRasterYSize();
double adfGeoTransform[6];
if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None) {
Position topLeft(adfGeoTransform[0], adfGeoTransform[3]);
mySizeOfPixel.set(adfGeoTransform[1], adfGeoTransform[5]);
const double horizontalSize = xSize * mySizeOfPixel.x();
const double verticalSize = ySize * mySizeOfPixel.y();
boundary.add(topLeft);
boundary.add(topLeft.x() + horizontalSize, topLeft.y() + verticalSize);
} else {
WRITE_ERROR("Could not parse geo information from " + file + ".");
return 0;
}
const int picSize = xSize * ySize;
int16_t* raster = (int16_t*)CPLMalloc(sizeof(int16_t) * picSize);
for (int i = 1; i <= poDataset->GetRasterCount(); i++) {
GDALRasterBand* poBand = poDataset->GetRasterBand(i);
if (poBand->GetColorInterpretation() != GCI_GrayIndex) {
WRITE_ERROR("Unknown color band in " + file + ".");
clearData();
break;
}
if (poBand->GetRasterDataType() != GDT_Int16) {
WRITE_ERROR("Unknown data type in " + file + ".");
clearData();
break;
}
assert(xSize == poBand->GetXSize() && ySize == poBand->GetYSize());
if (poBand->RasterIO(GF_Read, 0, 0, xSize, ySize, raster, xSize, ySize, GDT_Int16, 0, 0) == CE_Failure) {
WRITE_ERROR("Failure in reading " + file + ".");
clearData();
break;
}
}
GDALClose(poDataset);
myRasters.push_back(std::make_pair(boundary, raster));
return picSize;
#else
UNUSED_PARAMETER(file);
WRITE_ERROR("Cannot load GeoTIFF file since SUMO was compiled without GDAL support.");
return 0;
#endif
}
void
NBHeightMapper::clearData() {
for (Triangles::iterator it = myTriangles.begin(); it != myTriangles.end(); it++) {
delete *it;
}
myTriangles.clear();
#ifdef HAVE_GDAL
for (auto& item : myRasters) {
CPLFree(item.second);
}
myRasters.clear();
#endif
myBoundary.reset();
}
// ===========================================================================
// Triangle member methods
// ===========================================================================
NBHeightMapper::Triangle::Triangle(const PositionVector& corners):
myCorners(corners) {
assert(myCorners.size() == 3);
// @todo assert non-colinearity
}
void
NBHeightMapper::Triangle::addSelf(const QueryResult& queryResult) const {
queryResult.triangles.push_back(this);
}
bool
NBHeightMapper::Triangle::contains(const Position& pos) const {
return myCorners.around(pos);
}
double
NBHeightMapper::Triangle::getZ(const Position& geo) const {
// en.wikipedia.org/wiki/Line-plane_intersection
Position p0 = myCorners.front();
Position line(0, 0, 1);
p0.sub(geo); // p0 - l0
Position normal = normalVector();
return p0.dotProduct(normal) / line.dotProduct(normal);
}
Position
NBHeightMapper::Triangle::normalVector() const {
// @todo maybe cache result to avoid multiple computations?
Position side1 = myCorners[1] - myCorners[0];
Position side2 = myCorners[2] - myCorners[0];
return side1.crossProduct(side2);
}
/****************************************************************************/
| 35.152455 | 131 | 0.58968 | [
"shape",
"vector",
"transform"
] |
7393472e4ef9f0694d933212ce4304e9666f0fc1 | 31,392 | cpp | C++ | src/platform/P6/BLEManagerImpl.cpp | mrninhvn/matter | c577b233db9d2f3a6f87108a062b1699a40c5169 | [
"Apache-2.0"
] | 4 | 2020-09-11T04:32:44.000Z | 2022-03-11T09:06:07.000Z | src/platform/P6/BLEManagerImpl.cpp | mrninhvn/matter | c577b233db9d2f3a6f87108a062b1699a40c5169 | [
"Apache-2.0"
] | 2 | 2022-02-21T13:52:24.000Z | 2022-03-21T10:38:57.000Z | src/platform/P6/BLEManagerImpl.cpp | mrninhvn/matter | c577b233db9d2f3a6f87108a062b1699a40c5169 | [
"Apache-2.0"
] | 2 | 2022-02-24T15:42:39.000Z | 2022-03-04T20:38:07.000Z | /*
*
* Copyright (c) 2021 Project CHIP Authors
* Copyright (c) 2020 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Provides an implementation of the BLEManager singleton object
* for the PSoC6 platform.
*/
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include <ble/CHIPBleServiceData.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/internal/BLEManager.h>
extern "C" {
#include "app_platform_cfg.h"
#include "cycfg_bt_settings.h"
#include "cycfg_gatt_db.h"
}
#include "cy_utils.h"
#include "wiced_bt_stack.h"
#include <wiced_bt_ble.h>
#include <wiced_bt_gatt.h>
using namespace ::chip;
using namespace ::chip::Ble;
#define BLE_SERVICE_DATA_SIZE 10
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F,
0x9D, 0x11 } };
const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F,
0x9D, 0x12 } };
} // unnamed namespace
BLEManagerImpl BLEManagerImpl::sInstance;
wiced_bt_gatt_status_t app_gatts_callback(wiced_bt_gatt_evt_t event, wiced_bt_gatt_event_data_t * p_data);
wiced_result_t BLEManagerImpl::BLEManagerCallback(wiced_bt_management_evt_t event, wiced_bt_management_evt_data_t * p_event_data)
{
switch (event)
{
case BTM_ENABLED_EVT:
// Post a event to _OnPlatformEvent.
{
// Register with stack to receive GATT callback
wiced_bt_gatt_register(app_gatts_callback);
// Inform the stack to use this app GATT database
wiced_bt_gatt_db_init(gatt_database, gatt_database_len, NULL);
ChipDeviceEvent bleEvent;
bleEvent.Type = DeviceEventType::kP6BLEEnabledEvt;
if (PlatformMgr().PostEvent(&bleEvent) != CHIP_NO_ERROR)
{
return WICED_BT_ERROR;
}
}
break;
}
return WICED_BT_SUCCESS;
}
CHIP_ERROR BLEManagerImpl::_Init()
{
CHIP_ERROR err;
// Initialize the CHIP BleLayer.
err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer());
SuccessOrExit(err);
// Configure platform specific settings for Bluetooth
cybt_platform_config_init(&bt_platform_cfg_settings);
// Initialize the Bluetooth stack with a callback function and stack
// configuration structure */
if (WICED_SUCCESS != wiced_bt_stack_init(BLEManagerCallback, &wiced_bt_cfg_settings))
{
printf("Error initializing BT stack\n");
CY_ASSERT(0);
}
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled;
if (CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART)
{
mFlags.Set(Flags::kFlag_AdvertisingEnabled, true);
}
else
{
mFlags.Set(Flags::kFlag_AdvertisingEnabled, false);
}
mNumCons = 0;
memset(mCons, 0, sizeof(mCons));
memset(mDeviceName, 0, sizeof(mDeviceName));
ChipLogProgress(DeviceLayer, "BLEManagerImpl::Init() complete");
PlatformMgr().ScheduleWork(DriveBLEState, 0);
exit:
return err;
}
CHIP_ERROR BLEManagerImpl::_SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(val != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
if (val != mServiceMode)
{
mServiceMode = val;
PlatformMgr().ScheduleWork(DriveBLEState, 0);
}
exit:
return err;
}
bool BLEManagerImpl::_IsAdvertisingEnabled(void)
{
return mFlags.Has(Flags::kFlag_AdvertisingEnabled);
}
CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
if (mFlags.Has(Flags::kFlag_AdvertisingEnabled) != val)
{
mFlags.Set(Flags::kFlag_AdvertisingEnabled, val);
PlatformMgr().ScheduleWork(DriveBLEState, 0);
}
exit:
return err;
}
/*
* TODO
*/
CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode)
{
(void) (mode);
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize)
{
if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported)
{
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
if (strlen(mDeviceName) >= bufSize)
{
return CHIP_ERROR_BUFFER_TOO_SMALL;
}
strcpy(buf, mDeviceName);
ChipLogProgress(DeviceLayer, "Getting device name to : \"%s\"", mDeviceName);
return CHIP_NO_ERROR;
}
CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName)
{
if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported)
{
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
if (deviceName != NULL && deviceName[0] != 0)
{
if (strlen(deviceName) >= kMaxDeviceNameLength)
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
memset(mDeviceName, 0, kMaxDeviceNameLength);
strncpy(mDeviceName, deviceName, strlen(deviceName));
mFlags.Set(Flags::kFlag_DeviceNameSet, true);
ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName);
}
else
{
wiced_bt_cfg_settings.device_name[0] = 0;
mDeviceName[0] = 0;
mFlags.Set(Flags::kFlag_DeviceNameSet, false);
}
return CHIP_NO_ERROR;
}
uint16_t BLEManagerImpl::_NumConnections(void)
{
return mNumCons;
}
void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
{
switch (event->Type)
{
case DeviceEventType::kP6BLEEnabledEvt:
mFlags.Set(Flags::kFlag_StackInitialized, true);
PlatformMgr().ScheduleWork(DriveBLEState, 0);
break;
case DeviceEventType::kCHIPoBLESubscribe:
HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
{
ChipDeviceEvent _event;
_event.Type = DeviceEventType::kCHIPoBLEConnectionEstablished;
PlatformMgr().PostEventOrDie(&_event);
}
break;
case DeviceEventType::kCHIPoBLEUnsubscribe:
HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
break;
case DeviceEventType::kCHIPoBLEWriteReceived:
HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX,
PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data));
break;
case DeviceEventType::kCHIPoBLENotifyConfirm:
HandleIndicationConfirmation(event->CHIPoBLENotifyConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX);
break;
case DeviceEventType::kCHIPoBLEConnectionError:
HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason);
break;
case DeviceEventType::kFabricMembershipChange:
case DeviceEventType::kServiceProvisioningChange:
case DeviceEventType::kAccountPairingChange:
// If CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, and there is a change to the
// device's provisioning state, then automatically disable CHIPoBLE advertising if the device
// is now fully provisioned.
#if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED
if (ConfigurationMgr().IsFullyProvisioned())
{
ClearFlag(mFlags, kFlag_AdvertisingEnabled);
ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned");
}
#endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED
// Force the advertising state to be refreshed to reflect new provisioning state.
mFlags.Set(Flags::kFlag_AdvertisingRefreshNeeded, true);
DriveBLEState();
break;
default:
break;
}
}
bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
{
ChipLogProgress(DeviceLayer, "BLEManagerImpl::SubscribeCharacteristic() not supported");
return false;
}
bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId)
{
ChipLogProgress(DeviceLayer, "BLEManagerImpl::UnsubscribeCharacteristic() not supported");
return false;
}
bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId)
{
ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId);
// Initiate a GAP disconnect.
wiced_bt_gatt_status_t gatt_err = wiced_bt_gatt_disconnect((uint16_t) conId);
if (gatt_err != WICED_BT_GATT_SUCCESS)
{
ChipLogError(DeviceLayer, "wiced_bt_gatt_disconnect() failed: %ld", gatt_err);
}
return (gatt_err == WICED_BT_GATT_SUCCESS);
}
uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const
{
CHIPoBLEConState * p_conn;
/* Check if target connection state exists. */
p_conn = BLEManagerImpl::sInstance.GetConnectionState(conId);
if (!p_conn)
{
return wiced_bt_cfg_settings.gatt_cfg.max_mtu_size;
}
else
{
return p_conn->Mtu;
}
}
bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
PacketBufferHandle data)
{
CHIP_ERROR err = CHIP_NO_ERROR;
uint16_t dataLen = data->DataLength();
wiced_bt_gatt_status_t gatt_err = WICED_BT_GATT_SUCCESS;
CHIPoBLEConState * conState = GetConnectionState(conId);
VerifyOrExit(conState != NULL, err = CHIP_ERROR_INVALID_ARGUMENT);
#ifdef BLE_DEBUG
ChipLogDetail(DeviceLayer, "Sending notification for CHIPoBLE TX characteristic (con %u, len %u)", conId, dataLen);
#endif
// Send a notification for the CHIPoBLE TX characteristic to the client containing the supplied data.
gatt_err = wiced_bt_gatt_send_notification((uint16_t) conId, HDLC_CHIP_SERVICE_CHAR_C2_VALUE, dataLen, data->Start());
exit:
if (gatt_err != WICED_BT_GATT_SUCCESS)
{
ChipLogError(DeviceLayer, "BLEManagerImpl::SendNotification() failed: %ld", gatt_err);
return false;
}
else
{
// Post an event to the CHIP queue.
ChipDeviceEvent event;
event.Type = DeviceEventType::kCHIPoBLENotifyConfirm;
event.CHIPoBLENotifyConfirm.ConId = conId;
err = PlatformMgr().PostEvent(&event);
}
return err == CHIP_NO_ERROR;
}
bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
PacketBufferHandle data)
{
ChipLogError(DeviceLayer, "BLEManagerImpl::SendWriteRequest() not supported");
return false;
}
bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId,
PacketBufferHandle data)
{
ChipLogError(DeviceLayer, "BLEManagerImpl::SendReadRequest() not supported");
return false;
}
bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext,
const ChipBleUUID * svcId, const ChipBleUUID * charId)
{
ChipLogError(DeviceLayer, "BLEManagerImpl::SendReadResponse() not supported");
return false;
}
void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) {}
void BLEManagerImpl::DriveBLEState(void)
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Exit if Stack not initialized
VerifyOrExit(mFlags.Has(Flags::kFlag_StackInitialized), /* */);
// Perform any initialization actions that must occur after the CHIP task is running.
if (!mFlags.Has(Flags::kFlag_AsyncInitCompleted))
{
mFlags.Set(Flags::kFlag_AsyncInitCompleted, true);
// If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled,
// disable CHIPoBLE advertising if the device is fully provisioned.
#if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED
if (ConfigurationMgr().IsFullyProvisioned())
{
ClearFlag(mFlags, kFlag_AdvertisingEnabled);
ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned");
}
#endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED
}
// If the application has enabled CHIPoBLE and BLE advertising...
if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled &&
mFlags.Has(Flags::kFlag_AdvertisingEnabled)
#if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION
// and no connections are active...
&& (mNumCons == 0)
#endif
)
{
// Start/re-start SoftDevice advertising if not already advertising, or if the
// advertising state of the SoftDevice needs to be refreshed.
if (!mFlags.Has(Flags::kFlag_Advertising) || mFlags.Has(Flags::kFlag_AdvertisingRefreshNeeded))
{
ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started");
mFlags.Set(Flags::kFlag_Advertising, true);
mFlags.Set(Flags::kFlag_AdvertisingRefreshNeeded, false);
SetAdvertisingData();
wiced_bt_start_advertisements(BTM_BLE_ADVERT_UNDIRECTED_HIGH, BLE_ADDR_PUBLIC, NULL);
// Post a CHIPoBLEAdvertisingChange(Started) event.
{
ChipDeviceEvent advChange;
advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange;
advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started;
err = PlatformMgr().PostEvent(&advChange);
}
}
}
// Otherwise, stop advertising if currently active.
else
{
if (mFlags.Has(Flags::kFlag_Advertising))
{
mFlags.Set(Flags::kFlag_Advertising, false);
ChipLogProgress(DeviceLayer, "CHIPoBLE stop advertising");
wiced_bt_start_advertisements(BTM_BLE_ADVERT_OFF, BLE_ADDR_PUBLIC, NULL);
}
}
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err));
mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled;
}
}
/*
* This function searches through the GATT DB to point to the attribute
* corresponding to the given handle
*/
gatt_db_lookup_table_t * BLEManagerImpl::GetGattAttr(uint16_t handle)
{
/* Search for the given handle in the GATT DB and return the pointer to the
correct attribute */
uint8_t array_index = 0;
for (array_index = 0; array_index < app_gatt_db_ext_attr_tbl_size; array_index++)
{
if (app_gatt_db_ext_attr_tbl[array_index].handle == handle)
{
return (&app_gatt_db_ext_attr_tbl[array_index]);
}
}
return NULL;
}
/*
* Currently there is no reason to pass Read Req to CHIP. Only process request for
* attributes in the GATT DB attribute table
*/
wiced_bt_gatt_status_t BLEManagerImpl::HandleGattServiceRead(uint16_t conn_id, wiced_bt_gatt_read_t * p_read_data)
{
gatt_db_lookup_table_t * puAttribute;
int attr_len_to_copy;
/* Get the right address for the handle in Gatt DB */
if (NULL == (puAttribute = GetGattAttr(p_read_data->handle)))
{
ChipLogError(DeviceLayer, "Read handle attribute not found. Handle:0x%X\n", p_read_data->handle);
return WICED_BT_GATT_INVALID_HANDLE;
}
attr_len_to_copy = puAttribute->cur_len;
ChipLogProgress(DeviceLayer, "GATT Read handler: conn_id:%04x handle:%04x len:%d", conn_id, p_read_data->handle,
attr_len_to_copy);
/* If the incoming offset is greater than the current length in the GATT DB
then the data cannot be read back*/
if (p_read_data->offset >= puAttribute->cur_len)
{
attr_len_to_copy = 0;
}
/* Calculate the number of bytes and the position of the data and copy it to
the given pointer */
if (attr_len_to_copy != 0)
{
uint8_t * from;
int size_to_copy = attr_len_to_copy - p_read_data->offset;
if (size_to_copy > *p_read_data->p_val_len)
{
size_to_copy = *p_read_data->p_val_len;
}
from = ((uint8_t *) puAttribute->p_data) + p_read_data->offset;
*p_read_data->p_val_len = size_to_copy;
memcpy(p_read_data->p_val, from, size_to_copy);
}
return WICED_BT_GATT_SUCCESS;
}
/*
* If Attribute is for CHIP, pass it through. Otherwise process request for
* attributes in the GATT DB attribute table.
*/
wiced_bt_gatt_status_t BLEManagerImpl::HandleGattServiceWrite(uint16_t conn_id, wiced_bt_gatt_write_t * p_data)
{
wiced_bt_gatt_status_t result = WICED_BT_GATT_SUCCESS;
gatt_db_lookup_table_t * puAttribute;
const uint16_t valLen = p_data->val_len;
// special handling for CHIP RX path
if (p_data->handle == HDLC_CHIP_SERVICE_CHAR_C1_VALUE)
{
chip::System::PacketBuffer * buf;
const uint16_t minBufSize = chip::System::PacketBuffer::kMaxSize + valLen;
// Attempt to allocate a packet buffer with enough space to hold the characteristic value.
// Note that we must use pbuf_alloc() directly, as PacketBuffer::New() is not interrupt-safe.
if ((buf = (chip::System::PacketBuffer *) pbuf_alloc(PBUF_RAW, minBufSize, PBUF_POOL)) != NULL)
{
// Copy the characteristic value into the packet buffer.
memcpy(buf->Start(), p_data->p_val, valLen);
buf->SetDataLength(valLen);
#ifdef BLE_DEBUG
ChipLogDetail(DeviceLayer, "Write received for CHIPoBLE RX characteristic con %04x len %d", conn_id, valLen);
#endif
// Post an event to the CHIP queue to deliver the data into the CHIP stack.
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kCHIPoBLEWriteReceived;
event.CHIPoBLEWriteReceived.ConId = conn_id;
event.CHIPoBLEWriteReceived.Data = buf;
CHIP_ERROR status = PlatformMgr().PostEvent(&event);
if (status != CHIP_NO_ERROR)
{
result = WICED_BT_GATT_INTERNAL_ERROR;
}
buf = NULL;
}
}
else
{
ChipLogError(DeviceLayer, "BLEManagerImpl: Out of buffers during CHIPoBLE RX");
result = WICED_BT_GATT_NO_RESOURCES;
}
}
else
{
ChipLogDetail(DeviceLayer, "Write received for CHIPoBLE RX characteristic con:%04x handle:%04x len:%d", conn_id,
p_data->handle, valLen);
/* Get the right address for the handle in Gatt DB */
if (NULL == (puAttribute = GetGattAttr(p_data->handle)))
{
ChipLogError(DeviceLayer, "BLEManagerImpl: Write wrong handle:%04x", p_data->handle);
return WICED_BT_GATT_INVALID_HANDLE;
}
puAttribute->cur_len = valLen > puAttribute->max_len ? puAttribute->max_len : valLen;
memcpy(puAttribute->p_data, p_data->p_val, puAttribute->cur_len);
// Post an event to the Chip queue to process either a CHIPoBLE Subscribe or Unsubscribe based on
// whether the client is enabling or disabling indications.
if (p_data->handle == HDLD_CHIP_SERVICE_RX_CLIENT_CHAR_CONFIG)
{
ChipDeviceEvent event;
event.Type = (app_chip_service_char_tx_client_char_config[0] != 0) ? DeviceEventType::kCHIPoBLESubscribe
: DeviceEventType::kCHIPoBLEUnsubscribe;
event.CHIPoBLESubscribe.ConId = conn_id;
if (PlatformMgr().PostEvent(&event) != CHIP_NO_ERROR)
{
return WICED_BT_GATT_INTERNAL_ERROR;
}
}
ChipLogProgress(DeviceLayer, "CHIPoBLE %s received",
app_chip_service_char_tx_client_char_config[0] != 0 ? "subscribe" : "unsubscribe");
}
return result;
}
/*
* Process MTU request received from the GATT client
*/
wiced_bt_gatt_status_t BLEManagerImpl::HandleGattServiceMtuReq(wiced_bt_gatt_attribute_request_t * p_data,
CHIPoBLEConState * p_conn)
{
p_data->data.mtu = p_conn->Mtu;
return WICED_BT_GATT_SUCCESS;
}
/*
* Process GATT attribute requests
*/
wiced_bt_gatt_status_t BLEManagerImpl::HandleGattServiceRequestEvent(wiced_bt_gatt_attribute_request_t * p_request,
CHIPoBLEConState * p_conn)
{
wiced_bt_gatt_status_t result = WICED_BT_GATT_INVALID_PDU;
switch (p_request->request_type)
{
case GATTS_REQ_TYPE_READ:
result = HandleGattServiceRead(p_request->conn_id, &(p_request->data.read_req));
break;
case GATTS_REQ_TYPE_WRITE:
result = HandleGattServiceWrite(p_request->conn_id, &(p_request->data.write_req));
break;
case GATTS_REQ_TYPE_MTU:
result = HandleGattServiceMtuReq(p_request, p_conn);
break;
default:
break;
}
return result;
}
/*
* Handle GATT connection events from the stack
*/
wiced_bt_gatt_status_t BLEManagerImpl::HandleGattConnectEvent(wiced_bt_gatt_connection_status_t * p_conn_status,
CHIPoBLEConState * p_conn)
{
if (p_conn_status->connected)
{
/* Device got connected */
p_conn->connected = true;
ChipLogProgress(DeviceLayer, "BLE GATT connection up (con %u)", p_conn_status->conn_id);
}
else /* Device got disconnected */
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kCHIPoBLEConnectionError;
event.CHIPoBLEConnectionError.ConId = p_conn_status->conn_id;
switch (p_conn_status->reason)
{
case GATT_CONN_TERMINATE_PEER_USER:
event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED;
break;
case GATT_CONN_TERMINATE_LOCAL_HOST:
event.CHIPoBLEConnectionError.Reason = BLE_ERROR_APP_CLOSED_CONNECTION;
break;
default:
event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT;
break;
}
ChipLogProgress(DeviceLayer, "BLE GATT connection closed (con %u, reason %u)", p_conn_status->conn_id,
p_conn_status->reason);
if (PlatformMgr().PostEvent(&event) != CHIP_NO_ERROR)
{
return WICED_BT_GATT_INTERNAL_ERROR;
}
// Arrange to re-enable connectable advertising in case it was disabled due to the
// maximum connection limit being reached.
mFlags.Set(Flags::kFlag_Advertising, false);
PlatformMgr().ScheduleWork(DriveBLEState, 0);
ReleaseConnectionState(p_conn->ConId);
}
return WICED_BT_GATT_SUCCESS;
}
/*
* Process GATT requests. Callback is received in the BT stack thread context.
*
*/
wiced_bt_gatt_status_t app_gatts_callback(wiced_bt_gatt_evt_t event, wiced_bt_gatt_event_data_t * p_data)
{
uint16_t conn_id;
BLEManagerImpl::CHIPoBLEConState * p_conn;
/* Check parameter. */
if (!p_data)
{
return WICED_BT_GATT_ILLEGAL_PARAMETER;
}
/* Check if target connection state exists. */
switch (event)
{
case GATT_CONNECTION_STATUS_EVT:
conn_id = p_data->connection_status.conn_id;
break;
case GATT_OPERATION_CPLT_EVT:
conn_id = p_data->operation_complete.conn_id;
break;
case GATT_DISCOVERY_RESULT_EVT:
conn_id = p_data->discovery_result.conn_id;
break;
case GATT_DISCOVERY_CPLT_EVT:
conn_id = p_data->discovery_complete.conn_id;
break;
case GATT_ATTRIBUTE_REQUEST_EVT:
conn_id = p_data->attribute_request.conn_id;
break;
case GATT_CONGESTION_EVT:
conn_id = p_data->congestion.conn_id;
break;
default:
return WICED_BT_GATT_ILLEGAL_PARAMETER;
}
p_conn = BLEManagerImpl::sInstance.GetConnectionState(conn_id);
/* Allocate connection state if no exist. */
if (!p_conn)
{
p_conn = BLEManagerImpl::sInstance.AllocConnectionState(conn_id);
if (!p_conn)
{
return WICED_BT_GATT_INSUF_RESOURCE;
}
}
switch (event)
{
case GATT_CONNECTION_STATUS_EVT:
return BLEManagerImpl::sInstance.HandleGattConnectEvent(&p_data->connection_status, p_conn);
case GATT_ATTRIBUTE_REQUEST_EVT:
return BLEManagerImpl::sInstance.HandleGattServiceRequestEvent(&p_data->attribute_request, p_conn);
default:
break;
}
return WICED_BT_GATT_ILLEGAL_PARAMETER;
}
void BLEManagerImpl::SetAdvertisingData(void)
{
CHIP_ERROR err;
wiced_bt_ble_advert_elem_t adv_elem[4];
uint8_t num_elem = 0;
uint8_t flag = BTM_BLE_GENERAL_DISCOVERABLE_FLAG | BTM_BLE_BREDR_NOT_SUPPORTED;
uint8_t chip_service_uuid[2] = { BIT16_TO_8(__UUID16_CHIPoBLEService) };
ChipBLEDeviceIdentificationInfo mDeviceIdInfo;
uint16_t deviceDiscriminator = 0;
uint8_t localDeviceNameLen;
uint8_t service_data[BLE_SERVICE_DATA_SIZE];
uint8_t * p = service_data;
static_assert(BLE_SERVICE_DATA_SIZE == sizeof(ChipBLEDeviceIdentificationInfo) + 2, "BLE Service Data Size is incorrect");
// Initialize the CHIP BLE Device Identification Information block that will be sent as payload
// within the BLE service advertisement data.
err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo);
SuccessOrExit(err);
// Get device discriminator
deviceDiscriminator = mDeviceIdInfo.GetDeviceDiscriminator();
// Verify device name was not already set
if (!sInstance.mFlags.Has(sInstance.Flags::kFlag_DeviceNameSet))
{
/* Default device name is CHIP-<DISCRIMINATOR> */
memset(sInstance.mDeviceName, 0, kMaxDeviceNameLength);
snprintf(sInstance.mDeviceName, kMaxDeviceNameLength, "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX,
deviceDiscriminator);
localDeviceNameLen = strlen(sInstance.mDeviceName);
strncpy((char *) app_gap_device_name, sInstance.mDeviceName, sizeof(app_gap_device_name));
app_gatt_db_ext_attr_tbl[0].cur_len = app_gatt_db_ext_attr_tbl[0].max_len < strlen(sInstance.mDeviceName)
? app_gatt_db_ext_attr_tbl[0].max_len
: strlen(sInstance.mDeviceName);
ChipLogProgress(DeviceLayer, "SetAdvertisingData: device name set: %s", sInstance.mDeviceName);
}
else
{
localDeviceNameLen = strlen(sInstance.mDeviceName);
}
/* First element is the advertisement flags */
adv_elem[num_elem].advert_type = BTM_BLE_ADVERT_TYPE_FLAG;
adv_elem[num_elem].len = sizeof(uint8_t);
adv_elem[num_elem].p_data = &flag;
num_elem++;
/* Second element is the service data for CHIP service */
adv_elem[num_elem].advert_type = BTM_BLE_ADVERT_TYPE_SERVICE_DATA;
adv_elem[num_elem].len = sizeof(service_data);
adv_elem[num_elem].p_data = service_data;
num_elem++;
UINT8_TO_STREAM(p, chip_service_uuid[0]);
UINT8_TO_STREAM(p, chip_service_uuid[1]);
UINT8_TO_STREAM(p, 0); // CHIP BLE Opcode == 0x00 (Uncommissioned)
UINT16_TO_STREAM(p, deviceDiscriminator);
UINT8_TO_STREAM(p, mDeviceIdInfo.DeviceVendorId[0]);
UINT8_TO_STREAM(p, mDeviceIdInfo.DeviceVendorId[1]);
UINT8_TO_STREAM(p, mDeviceIdInfo.DeviceProductId[0]);
UINT8_TO_STREAM(p, mDeviceIdInfo.DeviceProductId[1]);
UINT8_TO_STREAM(p, 0); // Additional Data Flag
adv_elem[num_elem].advert_type = BTM_BLE_ADVERT_TYPE_NAME_COMPLETE;
adv_elem[num_elem].len = localDeviceNameLen;
adv_elem[num_elem].p_data = (uint8_t *) sInstance.mDeviceName;
num_elem++;
wiced_bt_ble_set_raw_advertisement_data(num_elem, adv_elem);
/* Configure Scan Response data */
num_elem = 0;
adv_elem[num_elem].advert_type = BTM_BLE_ADVERT_TYPE_NAME_COMPLETE;
adv_elem[num_elem].len = localDeviceNameLen;
adv_elem[num_elem].p_data = (uint8_t *) sInstance.mDeviceName;
num_elem++;
wiced_bt_ble_set_raw_scan_response_data(num_elem, adv_elem);
exit:
ChipLogProgress(DeviceLayer, "BLEManagerImpl::SetAdvertisingData err:%s", ErrorStr(err));
}
BLEManagerImpl::CHIPoBLEConState * BLEManagerImpl::AllocConnectionState(uint16_t conId)
{
for (uint16_t i = 0; i < kMaxConnections; i++)
{
if (mCons[i].connected == false)
{
mCons[i].ConId = conId;
mCons[i].Mtu = wiced_bt_cfg_settings.gatt_cfg.max_mtu_size;
mCons[i].connected = false;
mNumCons++;
return &mCons[i];
}
}
ChipLogError(DeviceLayer, "Failed to allocate CHIPoBLEConState");
return NULL;
}
BLEManagerImpl::CHIPoBLEConState * BLEManagerImpl::GetConnectionState(uint16_t conId)
{
for (uint16_t i = 0; i < kMaxConnections; i++)
{
if (mCons[i].ConId == conId)
{
return &mCons[i];
}
}
ChipLogError(DeviceLayer, "Failed to find CHIPoBLEConState");
return NULL;
}
bool BLEManagerImpl::ReleaseConnectionState(uint16_t conId)
{
for (uint16_t i = 0; i < kMaxConnections; i++)
{
if (mCons[i].ConId == conId)
{
memset(&mCons[i], 0, sizeof(CHIPoBLEConState));
mNumCons--;
return true;
}
}
ChipLogError(DeviceLayer, "Failed to delete CHIPoBLEConState");
return false;
}
void BLEManagerImpl::DriveBLEState(intptr_t arg)
{
sInstance.DriveBLEState();
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip
#endif
| 33.974026 | 132 | 0.67686 | [
"object"
] |
7394d9630b877fcda1934d7f09b39a4c184946de | 3,186 | hpp | C++ | include/LIEF/PE/resources/ResourceIcon.hpp | ienho/LIEF | 29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8 | [
"Apache-2.0"
] | 2 | 2021-12-31T07:25:05.000Z | 2022-03-05T15:03:00.000Z | include/LIEF/PE/resources/ResourceIcon.hpp | ienho/LIEF | 29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8 | [
"Apache-2.0"
] | null | null | null | include/LIEF/PE/resources/ResourceIcon.hpp | ienho/LIEF | 29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 - 2021 R. Thomas
* Copyright 2017 - 2021 Quarkslab
*
* 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.
*/
#ifndef LIEF_PE_RESOURCE_ICON_H_
#define LIEF_PE_RESOURCE_ICON_H_
#include <iostream>
#include <sstream>
#include "LIEF/visibility.h"
#include "LIEF/Object.hpp"
#include "LIEF/PE/Structures.hpp"
namespace LIEF {
namespace PE {
class ResourcesManager;
class LIEF_API ResourceIcon : public Object {
friend class ResourcesManager;
public:
ResourceIcon();
ResourceIcon(const pe_resource_icon_group *header);
ResourceIcon(const pe_icon_header *header);
ResourceIcon(const std::string& iconpath);
ResourceIcon(const ResourceIcon&);
ResourceIcon& operator=(const ResourceIcon&);
virtual ~ResourceIcon();
//! @brief Id associated with the icon
uint32_t id() const;
//! @brief Language associated with the icon
RESOURCE_LANGS lang() const;
//! @brief Sub language associated with the icon
RESOURCE_SUBLANGS sublang() const;
//! @brief Width in pixels of the image
uint8_t width() const;
//! @brief Height in pixels of the image
uint8_t height() const;
//! @brief Number of colors in image (0 if >=8bpp)
uint8_t color_count() const;
//! @brief Reserved (must be 0)
uint8_t reserved() const;
//! @brief Color Planes
uint16_t planes() const;
//! @brief Bits per pixel
uint16_t bit_count() const;
//! @brief Size in bytes of the image
uint32_t size() const;
//! @brief Pixels of the image (as bytes)
const std::vector<uint8_t>& pixels() const;
void id(uint32_t id);
void lang(RESOURCE_LANGS lang);
void sublang(RESOURCE_SUBLANGS sublang);
void width(uint8_t width);
void height(uint8_t height);
void color_count(uint8_t color_count);
void reserved(uint8_t reserved);
void planes(uint16_t planes);
void bit_count(uint16_t bit_count);
void pixels(const std::vector<uint8_t>& pixels);
//! @brief Save the icon to the given filename
//!
//! @param[in] filename Path to file in which the icon will be saved
void save(const std::string& filename) const;
virtual void accept(Visitor& visitor) const override;
bool operator==(const ResourceIcon& rhs) const;
bool operator!=(const ResourceIcon& rhs) const;
LIEF_API friend std::ostream& operator<<(std::ostream& os, const ResourceIcon& entry);
private:
uint8_t width_;
uint8_t height_;
uint8_t color_count_;
uint8_t reserved_;
uint16_t planes_;
uint16_t bit_count_;
uint32_t id_;
RESOURCE_LANGS lang_;
RESOURCE_SUBLANGS sublang_;
std::vector<uint8_t> pixels_;
};
}
}
#endif
| 25.285714 | 88 | 0.703704 | [
"object",
"vector"
] |
73987a2550890be464ebe97cf4b890289c0fe5e3 | 6,440 | cpp | C++ | src/Common/tests/gtest_rw_lock.cpp | ageraab/ClickHouse | 7cf35388407ee57f4e75c7040202274fea793ca2 | [
"Apache-2.0"
] | 3 | 2021-09-14T08:36:18.000Z | 2022-02-24T02:55:38.000Z | src/Common/tests/gtest_rw_lock.cpp | ageraab/ClickHouse | 7cf35388407ee57f4e75c7040202274fea793ca2 | [
"Apache-2.0"
] | 1 | 2020-12-28T19:33:08.000Z | 2020-12-28T19:33:08.000Z | src/Common/tests/gtest_rw_lock.cpp | ageraab/ClickHouse | 7cf35388407ee57f4e75c7040202274fea793ca2 | [
"Apache-2.0"
] | 1 | 2020-12-11T10:30:36.000Z | 2020-12-11T10:30:36.000Z | #include <gtest/gtest.h>
#include <Common/Exception.h>
#include <Common/RWLock.h>
#include <Common/Stopwatch.h>
#include <common/types.h>
#include <Common/ThreadPool.h>
#include <random>
#include <pcg_random.hpp>
#include <thread>
#include <atomic>
#include <iomanip>
using namespace DB;
namespace DB
{
namespace ErrorCodes
{
extern const int DEADLOCK_AVOIDED;
}
}
TEST(Common, RWLock1)
{
constexpr int cycles = 1000;
const std::vector<size_t> pool_sizes{1, 2, 4, 8};
static std::atomic<int> readers{0};
static std::atomic<int> writers{0};
static auto fifo_lock = RWLockImpl::create();
static thread_local std::random_device rd;
static thread_local pcg64 gen(rd());
auto func = [&] (size_t threads, int round)
{
for (int i = 0; i < cycles; ++i)
{
auto type = (std::uniform_int_distribution<>(0, 9)(gen) >= round) ? RWLockImpl::Read : RWLockImpl::Write;
auto sleep_for = std::chrono::duration<int, std::micro>(std::uniform_int_distribution<>(1, 100)(gen));
auto lock = fifo_lock->getLock(type, RWLockImpl::NO_QUERY);
if (type == RWLockImpl::Write)
{
++writers;
ASSERT_EQ(writers, 1);
ASSERT_EQ(readers, 0);
std::this_thread::sleep_for(sleep_for);
--writers;
}
else
{
++readers;
ASSERT_EQ(writers, 0);
ASSERT_GE(readers, 1);
ASSERT_LE(readers, threads);
std::this_thread::sleep_for(sleep_for);
--readers;
}
}
};
for (auto pool_size : pool_sizes)
{
for (int round = 0; round < 10; ++round)
{
Stopwatch watch(CLOCK_MONOTONIC_COARSE);
std::list<std::thread> threads;
for (size_t thread = 0; thread < pool_size; ++thread)
threads.emplace_back([=] () { func(pool_size, round); });
for (auto & thread : threads)
thread.join();
auto total_time = watch.elapsedSeconds();
std::cout << "Threads " << pool_size << ", round " << round << ", total_time " << std::setprecision(2) << total_time << "\n";
}
}
}
TEST(Common, RWLockRecursive)
{
constexpr auto cycles = 10000;
static auto fifo_lock = RWLockImpl::create();
static thread_local std::random_device rd;
static thread_local pcg64 gen(rd());
std::thread t1([&] ()
{
for (int i = 0; i < 2 * cycles; ++i)
{
auto lock = fifo_lock->getLock(RWLockImpl::Write, "q1");
auto sleep_for = std::chrono::duration<int, std::micro>(std::uniform_int_distribution<>(1, 100)(gen));
std::this_thread::sleep_for(sleep_for);
}
});
std::thread t2([&] ()
{
for (int i = 0; i < cycles; ++i)
{
auto lock1 = fifo_lock->getLock(RWLockImpl::Read, "q2");
auto sleep_for = std::chrono::duration<int, std::micro>(std::uniform_int_distribution<>(1, 100)(gen));
std::this_thread::sleep_for(sleep_for);
auto lock2 = fifo_lock->getLock(RWLockImpl::Read, "q2");
EXPECT_ANY_THROW({fifo_lock->getLock(RWLockImpl::Write, "q2");});
}
fifo_lock->getLock(RWLockImpl::Write, "q2");
});
t1.join();
t2.join();
}
TEST(Common, RWLockDeadlock)
{
static auto lock1 = RWLockImpl::create();
static auto lock2 = RWLockImpl::create();
/**
* q1: r1 r2
* q2: w1
* q3: r2 r1
* q4: w2
*/
std::thread t1([&] ()
{
auto holder1 = lock1->getLock(RWLockImpl::Read, "q1");
usleep(100000);
usleep(100000);
usleep(100000);
usleep(100000);
try
{
auto holder2 = lock2->getLock(RWLockImpl::Read, "q1", std::chrono::milliseconds(100));
if (!holder2)
{
throw Exception(
"Locking attempt timed out! Possible deadlock avoided. Client should retry.",
ErrorCodes::DEADLOCK_AVOIDED);
}
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::DEADLOCK_AVOIDED)
throw;
}
});
std::thread t2([&] ()
{
usleep(100000);
auto holder1 = lock1->getLock(RWLockImpl::Write, "q2");
});
std::thread t3([&] ()
{
usleep(100000);
usleep(100000);
auto holder2 = lock2->getLock(RWLockImpl::Read, "q3");
usleep(100000);
usleep(100000);
usleep(100000);
try
{
auto holder1 = lock1->getLock(RWLockImpl::Read, "q3", std::chrono::milliseconds(100));
if (!holder1)
{
throw Exception(
"Locking attempt timed out! Possible deadlock avoided. Client should retry.",
ErrorCodes::DEADLOCK_AVOIDED);
}
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::DEADLOCK_AVOIDED)
throw;
}
});
std::thread t4([&] ()
{
usleep(100000);
usleep(100000);
usleep(100000);
auto holder2 = lock2->getLock(RWLockImpl::Write, "q4");
});
t1.join();
t2.join();
t3.join();
t4.join();
}
TEST(Common, RWLockPerfTestReaders)
{
constexpr int cycles = 100000; // 100k
const std::vector<size_t> pool_sizes{1, 2, 4, 8};
static auto fifo_lock = RWLockImpl::create();
for (auto pool_size : pool_sizes)
{
Stopwatch watch(CLOCK_MONOTONIC_COARSE);
auto func = [&] ()
{
for (auto i = 0; i < cycles; ++i)
{
auto lock = fifo_lock->getLock(RWLockImpl::Read, RWLockImpl::NO_QUERY);
}
};
std::list<std::thread> threads;
for (size_t thread = 0; thread < pool_size; ++thread)
threads.emplace_back(func);
for (auto & thread : threads)
thread.join();
auto total_time = watch.elapsedSeconds();
std::cout << "Threads " << pool_size << ", total_time " << std::setprecision(2) << total_time << "\n";
}
}
| 26.072874 | 137 | 0.517547 | [
"vector"
] |
739ba5e8fd11f889eea33376d7c5d46ea967fb25 | 6,709 | cpp | C++ | src/key_io.cpp | phm87/bitcoin-abc | e0c55f5e6fbb3f4c19a9e203223f8ad2f3eba7b9 | [
"MIT"
] | 1 | 2021-06-12T04:50:08.000Z | 2021-06-12T04:50:08.000Z | src/key_io.cpp | phm87/bitcoin-abc | e0c55f5e6fbb3f4c19a9e203223f8ad2f3eba7b9 | [
"MIT"
] | null | null | null | src/key_io.cpp | phm87/bitcoin-abc | e0c55f5e6fbb3f4c19a9e203223f8ad2f3eba7b9 | [
"MIT"
] | 1 | 2019-09-08T15:35:38.000Z | 2019-09-08T15:35:38.000Z | // Copyright (c) 2014-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key_io.h>
#include <base58.h>
#include <cashaddrenc.h>
#include <chainparams.h>
#include <config.h>
#include <script/script.h>
#include <utilstrencodings.h>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
#include <algorithm>
#include <cassert>
#include <cstring>
namespace {
class DestinationEncoder : public boost::static_visitor<std::string> {
private:
const CChainParams &m_params;
public:
DestinationEncoder(const CChainParams ¶ms) : m_params(params) {}
std::string operator()(const CKeyID &id) const {
std::vector<uint8_t> data =
m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
data.insert(data.end(), id.begin(), id.end());
return EncodeBase58Check(data);
}
std::string operator()(const CScriptID &id) const {
std::vector<uint8_t> data =
m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
data.insert(data.end(), id.begin(), id.end());
return EncodeBase58Check(data);
}
std::string operator()(const CNoDestination &no) const { return {}; }
};
CTxDestination DecodeLegacyDestination(const std::string &str,
const CChainParams ¶ms) {
std::vector<uint8_t> data;
uint160 hash;
if (!DecodeBase58Check(str, data)) {
return CNoDestination();
}
// base58-encoded Bitcoin addresses.
// Public-key-hash-addresses have version 0 (or 111 testnet).
// The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is
// the serialized public key.
const std::vector<uint8_t> &pubkey_prefix =
params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
if (data.size() == hash.size() + pubkey_prefix.size() &&
std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
std::copy(data.begin() + pubkey_prefix.size(), data.end(),
hash.begin());
return CKeyID(hash);
}
// Script-hash-addresses have version 5 (or 196 testnet).
// The data vector contains RIPEMD160(SHA256(cscript)), where cscript is
// the serialized redemption script.
const std::vector<uint8_t> &script_prefix =
params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
if (data.size() == hash.size() + script_prefix.size() &&
std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {
std::copy(data.begin() + script_prefix.size(), data.end(),
hash.begin());
return CScriptID(hash);
}
return CNoDestination();
}
} // namespace
CKey DecodeSecret(const std::string &str) {
CKey key;
std::vector<uint8_t> data;
if (DecodeBase58Check(str, data)) {
const std::vector<uint8_t> &privkey_prefix =
Params().Base58Prefix(CChainParams::SECRET_KEY);
if ((data.size() == 32 + privkey_prefix.size() ||
(data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
std::equal(privkey_prefix.begin(), privkey_prefix.end(),
data.begin())) {
bool compressed = data.size() == 33 + privkey_prefix.size();
key.Set(data.begin() + privkey_prefix.size(),
data.begin() + privkey_prefix.size() + 32, compressed);
}
}
memory_cleanse(data.data(), data.size());
return key;
}
std::string EncodeSecret(const CKey &key) {
assert(key.IsValid());
std::vector<uint8_t> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
data.insert(data.end(), key.begin(), key.end());
if (key.IsCompressed()) {
data.push_back(1);
}
std::string ret = EncodeBase58Check(data);
memory_cleanse(data.data(), data.size());
return ret;
}
CExtPubKey DecodeExtPubKey(const std::string &str) {
CExtPubKey key;
std::vector<uint8_t> data;
if (DecodeBase58Check(str, data)) {
const std::vector<uint8_t> &prefix =
Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() &&
std::equal(prefix.begin(), prefix.end(), data.begin())) {
key.Decode(data.data() + prefix.size());
}
}
return key;
}
std::string EncodeExtPubKey(const CExtPubKey &key) {
std::vector<uint8_t> data =
Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
size_t size = data.size();
data.resize(size + BIP32_EXTKEY_SIZE);
key.Encode(data.data() + size);
std::string ret = EncodeBase58Check(data);
return ret;
}
CExtKey DecodeExtKey(const std::string &str) {
CExtKey key;
std::vector<uint8_t> data;
if (DecodeBase58Check(str, data)) {
const std::vector<uint8_t> &prefix =
Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() &&
std::equal(prefix.begin(), prefix.end(), data.begin())) {
key.Decode(data.data() + prefix.size());
}
}
return key;
}
std::string EncodeExtKey(const CExtKey &key) {
std::vector<uint8_t> data =
Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
size_t size = data.size();
data.resize(size + BIP32_EXTKEY_SIZE);
key.Encode(data.data() + size);
std::string ret = EncodeBase58Check(data);
memory_cleanse(data.data(), data.size());
return ret;
}
std::string EncodeDestination(const CTxDestination &dest,
const Config &config) {
const CChainParams ¶ms = config.GetChainParams();
return config.UseCashAddrEncoding() ? EncodeCashAddr(dest, params)
: EncodeLegacyAddr(dest, params);
}
CTxDestination DecodeDestination(const std::string &addr,
const CChainParams ¶ms) {
CTxDestination dst = DecodeCashAddr(addr, params);
if (IsValidDestination(dst)) {
return dst;
}
return DecodeLegacyAddr(addr, params);
}
bool IsValidDestinationString(const std::string &str,
const CChainParams ¶ms) {
return IsValidDestination(DecodeDestination(str, params));
}
std::string EncodeLegacyAddr(const CTxDestination &dest,
const CChainParams ¶ms) {
return boost::apply_visitor(DestinationEncoder(params), dest);
}
CTxDestination DecodeLegacyAddr(const std::string &str,
const CChainParams ¶ms) {
return DecodeLegacyDestination(str, params);
}
| 35.310526 | 80 | 0.633179 | [
"vector"
] |
739bf378bd9efacf0da281aff590d199e805a98a | 15,725 | hpp | C++ | Pods/Realm/include/core/realm/sync/transform.hpp | hq7781/MoneyBook | 1096e03e6b5c1edba8c12fc826bc1025e246c051 | [
"MIT"
] | 63 | 2015-12-07T08:10:31.000Z | 2022-03-02T20:48:46.000Z | Potatso/Pods/Realm/include/core/realm/sync/transform.hpp | 547/Potatso_SW | 5f04a52e1fa26216852e4dbc6ce11814686d0ed5 | [
"MIT"
] | 30 | 2015-11-25T19:20:55.000Z | 2018-02-14T14:37:35.000Z | Potatso/Pods/Realm/include/core/realm/sync/transform.hpp | 547/Potatso_SW | 5f04a52e1fa26216852e4dbc6ce11814686d0ed5 | [
"MIT"
] | 9 | 2016-06-07T15:00:43.000Z | 2022-02-08T11:34:04.000Z | /*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_SYNC_TRANSFORM_HPP
#define REALM_SYNC_TRANSFORM_HPP
#include <stddef.h>
#include <realm/util/buffer.hpp>
#include <realm/impl/continuous_transactions_history.hpp>
#include <realm/group_shared.hpp>
namespace realm {
namespace sync {
/// Represents an entry in the history of changes in a sync-enabled Realm
/// file. Server and client use different history formats, but this class is
/// used both on the server and the client side. Each history entry corresponds
/// to a version of the Realm state. For server and client-side histories, these
/// versions are referred to as *server versions* and *client versions*
/// respectively. These versions may, or may not correspond to Realm snapshot
/// numbers (on the server-side they currently do not).
///
/// FIXME: Move this class into a separate header
/// (`<realm/sync/history_entry.hpp>`).
class HistoryEntry {
public:
using timestamp_type = uint_fast64_t;
using file_ident_type = uint_fast64_t;
using version_type = _impl::History::version_type;
/// The time of origination of the changes referenced by this history entry,
/// meassured as the number of milliseconds since 2015-01-01T00:00:00Z, not
/// including leap seconds. For changes of local origin, this is the local
/// time at the point when the local transaction was committed. For changes
/// of remote origin, it is the remote time of origin at the client
/// identified by `origin_client_file_ident`.
timestamp_type origin_timestamp;
/// For changes of local origin, this is the identifier of the local
/// file. On the client side, the special value, zero, is used as a stand-in
/// for the actual file identifier. This is necessary because changes may
/// occur on the client-side before it obtains the the actual identifier
/// from the server. Depending on context, the special value, zero, will, or
/// will not have been replaced by the actual local file identifier.
///
/// For changes of remote origin, this is the identifier of the file in the
/// context of which this change originated. This may be a client, or a
/// server-side file. For example, when a change "travels" from client file
/// A with identifier 2, through the server, to client file B with
/// identifier 3, then `origin_client_file_ident` will be 2 on the server
/// and in client file A. On the other hand, if the change originates on the
/// server, and the server-side file identifier is 1, then
/// `origin_client_file_ident` will be 1 in both client files.
///
/// FIXME: Rename this member to `origin_file_ident`. It is no longer
/// necessarily a client-side file.
file_ident_type origin_client_file_ident;
/// For changes of local origin on the client side, this is the last server
/// version integrated locally prior to this history entry. In other words,
/// it is a copy of `remote_version` of the last preceding history entry
/// that carries changes of remote origin, or zero if there is no such
/// preceding history entry.
///
/// For changes of local origin on the server-side, this is always zero.
///
/// For changes of remote origin, this is the version produced within the
/// remote-side Realm file by the change that gave rise to this history
/// entry. The remote-side Realm file is not always the same Realm file from
/// which the change originated. On the client side, the remote side is
/// always the server side, and `remote_version` is always a server version
/// (since clients do not speak directly to each other). On the server side,
/// the remote side is always a client side, and `remote_version` is always
/// a client version.
version_type remote_version;
/// Referenced memory is not owned by this class.
BinaryData changeset;
};
/// The interface between the sync history and the operational transformer
/// (Transformer).
class TransformHistory {
public:
using timestamp_type = HistoryEntry::timestamp_type;
using file_ident_type = HistoryEntry::file_ident_type;
using version_type = HistoryEntry::version_type;
/// Get the first history entry where the produced version is greater than
/// `begin_version` and less than or equal to `end_version`, and whose
/// changeset is neither empty, nor produced by integration of a changeset
/// received from the specified remote peer.
///
/// If \a buffer is non-null, memory will be allocated and transferred to
/// \a buffer. The changeset will be copied into the newly allocated memory.
///
/// If \a buffer is null, the changeset is not copied out of the Realm,
/// and entry.changeset.data() does not point to the changeset.
/// The changeset in the Realm could be chunked, hence it is not possible
/// to point to it with BinaryData. entry.changeset.size() always gives the
/// size of the changeset.
///
/// \param begin_version, end_version The range of versions to consider. If
/// `begin_version` is equal to `end_version`, this is the empty range. If
/// `begin_version` is zero, it means that everything preceeding
/// `end_version` is to be considered, which is again the empty range if
/// `end_version` is also zero. Zero is is special value in that no
/// changeset produces that version. It is an error if `end_version`
/// preceeds `begin_version`, or if `end_version` is zero and
/// `begin_version` is not.
///
/// \param not_from_remote_client_file_ident Skip entries whose changeset is
/// produced by integration of changesets received from this remote
/// peer. Zero if the remote peer is the server, otherwise the peer
/// identifier of a client.
///
/// \param only_nonempty Skip entries with empty changesets.
///
/// \return The version produced by the changeset of the located history
/// entry, or zero if no history entry exists matching the specified
/// criteria.
virtual version_type find_history_entry(version_type begin_version, version_type end_version,
file_ident_type not_from_remote_client_file_ident,
bool only_nonempty, HistoryEntry& entry,
util::Optional<std::unique_ptr<char[]>&> buffer) const noexcept = 0;
/// Copy a contiguous sequence of bytes from the specified reciprocally
/// transformed changeset into the specified buffer. The targeted history
/// entry is the one whose untransformed changeset produced the specified
/// version. Copying starts at the specified offset within the transform,
/// and will continue until the end of the transform or the end of the
/// buffer, whichever comes first. The first copied byte is always placed in
/// `buffer[0]`. The number of copied bytes is returned.
///
/// \param remote_client_file_ident Zero if the remote peer is the server,
/// otherwise the peer identifier of a client.
virtual size_t read_reciprocal_transform(version_type version,
file_ident_type remote_client_file_ident,
size_t offset, char* buffer, size_t size) const = 0;
/// Replace a contiguous chunk of bytes within the specified reciprocally
/// transformed changeset. The targeted history entry is the one whose
/// untransformed changeset produced the specified version. If the new chunk
/// has a different size than the on it replaces, subsequent bytes (those
/// beyond the end of the replaced chunk) are shifted to lower or higher
/// offsets accordingly. If `replaced_size` is equal to `size_t(-1)`, the
/// replaced chunk extends from `offset` to the end of the transform. Let
/// `replaced_size_2` be the actual size of the replaced chunk, then the
/// total number of bytes in the transform will increase by `size -
/// replaced_size_2`. It is an error if `replaced_size` is not `size_t(-1)`
/// and `offset + replaced_size` is greater than the size of the transform.
///
/// \param remote_client_file_ident See read_reciprocal_transform().
///
/// \param offset The index of the first replaced byte relative to the
/// beginning of the transform.
///
/// \param replaced_size The number of bytes in the replaced chunk.
///
/// \param data The buffer holding the replacing chunk.
///
/// \param size The number of bytes in the replacing chunk, which is also
/// the number of bytes that will be read from the specified buffer.
virtual void write_reciprocal_transform(version_type version,
file_ident_type remote_client_file_ident,
size_t offset, size_t replaced_size,
const char* data, size_t size) = 0;
virtual ~TransformHistory() noexcept {}
};
class TransformError; // Exception
typedef std::function<bool(int)> TransformerCallback;
class Transformer {
public:
using timestamp_type = HistoryEntry::timestamp_type;
using file_ident_type = HistoryEntry::file_ident_type;
using version_type = HistoryEntry::version_type;
struct RemoteChangeset {
/// The version produced on the remote peer by this changeset.
///
/// On the server, the remote peer is the client from which the
/// changeset originated, and `remote_version` is the client version
/// produced by the changeset on that client.
///
/// On a client, the remote peer is the server, and `remote_version` is
/// the server version produced by this changeset on the server. Since
/// the server is never the originator of changes, this changeset must
/// in turn have been produced on the server by integration of a
/// changeset uploaded by some other client.
version_type remote_version;
/// The last local version that has been integrated into
/// `remote_version`.
///
/// A local version, L, has been integrated into a remote version, R,
/// when, and only when L is the latest local version such that all
/// preceeding changesets in the local history have been integrated by
/// the remote peer prior to R.
///
/// On the server, this is the last server version integrated into the
/// client version `remote_version`. On a client, it is the last client
/// version integrated into the server version `remote_version`.
version_type last_integrated_local_version;
/// The changeset itself.
BinaryData data;
/// Same meaning as `HistoryEntry::origin_timestamp`.
timestamp_type origin_timestamp;
/// Same meaning as `HistoryEntry::origin_client_file_ident`.
file_ident_type origin_client_file_ident;
RemoteChangeset(version_type rv, version_type lv, BinaryData d, timestamp_type ot,
file_ident_type fi);
};
/// Produce an operationally transformed version of the specified changeset,
/// which is assumed to be of remote origin, and received from remote peer
/// P. Note that P is not necessarily the peer from which the changes
/// originated.
///
/// Operational transformation is carried out between the specified
/// changeset and all causally unrelated changesets in the local history. A
/// changeset in the local history is causally unrelated if, and only if it
/// occurs after the local changeset that produced
/// `remote_changeset.last_integrated_local_version` and is not a produced
/// by integration of a changeset received from P. This assumes that
/// `remote_changeset.last_integrated_local_version` is set to the local
/// version produced by the last local changeset, that was integrated by P
/// before P produced the specified changeset.
///
/// The operational transformation is reciprocal (two-way), so it also
/// transforms the causally unrelated local changesets. This process does
/// not modify the history itself (the changesets available through
/// TransformHistory::get_history_entry()), instead the reciprocally
/// transformed changesets are stored separately, and individually for each
/// remote peer, such that they can participate in transformation of the
/// next incoming changeset from P. Note that the peer identifier of P can
/// be derived from `origin_client_file_ident` and information about whether
/// the local peer is a server or a client.
///
/// In general, if A and B are two causally unrelated (alternative)
/// changesets based on the same version V, then the operational
/// transformation between A and B produces changesets A' and B' such that
/// both of the concatenated changesets A + B' and B + A' produce the same
/// final state when applied to V. Operational transformation is meaningful
/// only when carried out between alternative changesets based on the same
/// version.
///
/// \return The size of the transformed version of the specified
/// changeset. Upon return, the changeset itself is stored in the specified
/// output buffer.
///
/// \throw TransformError Thrown if operational transformation fails due to
/// a problem with the specified changeset.
virtual size_t transform_remote_changeset(TransformHistory&,
version_type current_local_version,
RemoteChangeset changeset,
util::Buffer<char>& output_buffer,
TransformerCallback& callback) = 0;
virtual ~Transformer() noexcept {}
};
/// \param local_client_file_ident The server assigned local client file
/// identifier. This must be zero on the server-side, and only on the
/// server-side.
std::unique_ptr<Transformer> make_transformer(Transformer::file_ident_type local_client_file_ident);
// Implementation
class TransformError: public std::runtime_error {
public:
TransformError(const std::string& message):
std::runtime_error(message)
{
}
};
inline Transformer::RemoteChangeset::RemoteChangeset(version_type rv, version_type lv,
BinaryData d, timestamp_type ot,
file_ident_type fi):
remote_version(rv),
last_integrated_local_version(lv),
data(d),
origin_timestamp(ot),
origin_client_file_ident(fi)
{
}
} // namespace sync
} // namespace realm
#endif // REALM_SYNC_TRANSFORM_HPP
| 48.533951 | 112 | 0.678919 | [
"transform"
] |
739c5c199cbe915135b48785f2bc12b360c8b73a | 8,694 | cpp | C++ | ProxyDllGenerator/Source.cpp | kagasu/ProxyDllGenerator | adfb46a766bb4e2041908d044f7d593114240cdf | [
"MIT"
] | 6 | 2021-03-04T07:11:35.000Z | 2021-11-05T07:49:55.000Z | ProxyDllGenerator/Source.cpp | kagasu/ProxyDllGenerator | adfb46a766bb4e2041908d044f7d593114240cdf | [
"MIT"
] | null | null | null | ProxyDllGenerator/Source.cpp | kagasu/ProxyDllGenerator | adfb46a766bb4e2041908d044f7d593114240cdf | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <winnt.h>
#include <iostream>
#include <fstream>
#include <iterator>
#include <sstream>
#include <codecvt>
#include <vector>
#include <algorithm>
#include <list>
#include <filesystem>
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <fmt/format.h>
#include <boost/program_options.hpp>
#include "ToVector.hpp"
#include "FunctionInfo.hpp"
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif
#define DebugLog(str) std::cout << "[DEBUG] [LINE: " << std::dec << __LINE__ << "] " << str << std::endl;
std::string GenerateGuid()
{
GUID guid;
auto result = CoCreateGuid(&guid);
if (result == S_OK)
{
return fmt::format("{:08x}{:04x}{:04x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
}
else
{
return std::string();
}
}
std::string ReadAllText(const std::string& filePath)
{
std::ifstream ifs(filePath, std::ios::in);
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
ifs.close();
return str;
}
void ReplaceString(std::string& str1, const std::string &str2, const std::string& str3)
{
std::string::size_type Pos(str1.find(str2));
while (Pos != std::string::npos)
{
str1.replace(Pos, str2.length(), str3);
Pos = str1.find(str2, Pos + str3.length());
}
}
// https://stackoverflow.com/a/3999597/4771485
std::string utf8_encode(const std::wstring& wstr)
{
if (wstr.empty()) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
// https://stackoverflow.com/a/3999597/4771485
std::wstring utf8_decode(const std::string& str)
{
if (str.empty()) return std::wstring();
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
void generateProxyDllSourceCode32(const uintptr_t moduleAddress, int numberOfNames, const uint32_t addressOfNames[], const std::string& originalFileName, const std::string& outputDirectory)
{
auto dllMainTemplate = ReadAllText("templates/32/DllMain.cpp");
auto functionDefineTemplate = ReadAllText("templates/32/FunctionDefine.cpp");
std::ofstream ofsDllMain(fmt::format("{0}/DllMain.cpp", outputDirectory), std::ios::out);
ReplaceString(dllMainTemplate, "$FUNCTION_COUNT$", std::to_string(numberOfNames));
auto functionInfos = boost::irange<int>(0, numberOfNames)
| boost::adaptors::transformed([&moduleAddress, &addressOfNames](int i)
{
FunctionInfo fi(i, GenerateGuid(), std::string(reinterpret_cast<char*>(moduleAddress + addressOfNames[i])));
return fi;
})
| boost_extension::to_vec;
auto functionNames = functionInfos
| boost::adaptors::transformed([](auto x)
{
return fmt::format("\"{0}\"", x.name);
});
auto functionDefines = functionInfos
| boost::adaptors::transformed([&functionDefineTemplate](auto x)
{
return fmt::format(functionDefineTemplate, x.name, x.guid, x.index, x.index + 1);
});
ReplaceString(dllMainTemplate, "$FUNCTION_NAMES$", fmt::format("{0}", fmt::join(functionNames, ",\n\t")));
ReplaceString(dllMainTemplate, "$FUNCTION_DEFINES$", fmt::format("{0}", fmt::join(functionDefines, "\n")));
ReplaceString(dllMainTemplate, "$ORIGINAL_DLL_NAME$", fmt::format("\"{0}\"", originalFileName));
ofsDllMain << dllMainTemplate;
ofsDllMain.close();
}
void generateProxyDllSourceCode64(const uintptr_t moduleAddress, int numberOfNames, const uint32_t addressOfNames[], const std::string& originalFileName, const std::string& outputDirectory)
{
auto dllMainTemplate = ReadAllText("templates/64/DllMain.cpp");
auto functionDefineTemplate = ReadAllText("templates/64/FunctionDefine.cpp");
auto asmTemplate = ReadAllText("templates/64/asm.asm");
auto asmFunctionDefineTemplate = ReadAllText("templates/64/asmFunctionDefine.asm");
std::ofstream ofsDllMain(fmt::format("{0}/DllMain.cpp", outputDirectory), std::ios::out);
ReplaceString(dllMainTemplate, "$FUNCTION_COUNT$", std::to_string(numberOfNames));
auto functionInfos = boost::irange<int>(0, numberOfNames)
| boost::adaptors::transformed([&moduleAddress, &addressOfNames](int i)
{
FunctionInfo fi(i, GenerateGuid(), std::string(reinterpret_cast<char*>(moduleAddress + addressOfNames[i])));
return fi;
})
| boost_extension::to_vec;
auto functionNames = functionInfos
| boost::adaptors::transformed([](auto x)
{
return fmt::format("\"{0}\"", x.name);
});
auto functionDefines = functionInfos
| boost::adaptors::transformed([&functionDefineTemplate](auto x)
{
return fmt::format(functionDefineTemplate, x.name, x.guid, x.index, x.index + 1);
});
ReplaceString(dllMainTemplate, "$FUNCTION_NAMES$", fmt::format("{0}", fmt::join(functionNames, ",\n\t")));
ReplaceString(dllMainTemplate, "$FUNCTION_DEFINES$", fmt::format("{0}", fmt::join(functionDefines, "\n")));
ReplaceString(dllMainTemplate, "$ORIGINAL_DLL_NAME$", fmt::format("\"{0}\"", originalFileName));
ofsDllMain << dllMainTemplate;
ofsDllMain.close();
std::ofstream ofsAsm(fmt::format("{0}/asm.asm", outputDirectory), std::ios::out);
auto asmFunctionDefines = functionInfos
| boost::adaptors::transformed([&asmFunctionDefineTemplate](auto x)
{
return fmt::format(asmFunctionDefineTemplate, x.name, x.guid, x.index, x.index + 1);
});
ReplaceString(asmTemplate, "$ASM_FUNCTION_DEFINES$", fmt::format("{0}", fmt::join(asmFunctionDefines, "\n")));
ofsAsm << asmTemplate;
ofsAsm.close();
}
int main(int argc, char** argv)
{
boost::program_options::options_description description("ProxyDllGenerator");
description.add_options()("dll,d", boost::program_options::value<std::string>(), "DLL file");
boost::program_options::variables_map vm;
try
{
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, description), vm);
}
catch (const boost::program_options::error_with_option_name& e)
{
std::cout << e.what() << std::endl;
return 0;
}
notify(vm);
if (!vm.count("dll"))
{
std::cout << description << std::endl;
return 0;
}
auto inputFileName = vm["dll"].as<std::string>();
if (inputFileName.empty())
{
std::cout << description << std::endl;
return 0;
}
auto originalFileName = std::filesystem::path(inputFileName).stem().generic_string() + "_original.dll";
auto outputDirectory = std::string("out");
if (!std::filesystem::exists(outputDirectory))
{
std::filesystem::create_directory(outputDirectory);
}
if (!std::filesystem::exists(inputFileName))
{
std::cout << "Input file not found" << std::endl;
return 0;
}
auto moduleHandle = LoadLibraryExA(inputFileName.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES);
if (moduleHandle == nullptr)
{
DebugLog("moduleHandle == nullptr");
return -1;
}
auto moduleAddress = reinterpret_cast<uintptr_t>(moduleHandle);
auto moduleDosHeader = reinterpret_cast<PIMAGE_DOS_HEADER>(moduleAddress);
auto header = reinterpret_cast<PIMAGE_NT_HEADERS>(moduleAddress + moduleDosHeader->e_lfanew);
auto exports = reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(moduleAddress + header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
auto addressOfNames = reinterpret_cast<uint32_t*>(moduleAddress + exports->AddressOfNames);
auto numberOfNames = static_cast<int>(exports->NumberOfNames);
#ifdef ENVIRONMENT64
generateProxyDllSourceCode64(moduleAddress, numberOfNames, addressOfNames, originalFileName, outputDirectory);
#else
generateProxyDllSourceCode32(moduleAddress, numberOfNames, addressOfNames, originalFileName, outputDirectory);
#endif
}
| 38.131579 | 189 | 0.663791 | [
"vector"
] |
739ce9e1912726743bde15d6f7920691e132ad48 | 12,523 | cpp | C++ | hphp/runtime/vm/jit/irgen-control.cpp | ivanmurashko/hhvm | ce6e2c423308b6be196d1797a52e128746c69181 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/irgen-control.cpp | ivanmurashko/hhvm | ce6e2c423308b6be196d1797a52e128746c69181 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/irgen-control.cpp | ivanmurashko/hhvm | ce6e2c423308b6be196d1797a52e128746c69181 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2021-01-29T08:44:22.000Z | 2021-01-29T08:44:22.000Z | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/irgen-control.h"
#include "hphp/runtime/vm/resumable.h"
#include "hphp/runtime/vm/unwind.h"
#include "hphp/runtime/vm/jit/normalized-instruction.h"
#include "hphp/runtime/vm/jit/switch-profile.h"
#include "hphp/runtime/vm/jit/target-profile.h"
#include "hphp/runtime/vm/jit/irgen-exit.h"
#include "hphp/runtime/vm/jit/irgen-internal.h"
#include "hphp/runtime/vm/jit/irgen-interpone.h"
namespace HPHP { namespace jit { namespace irgen {
void surpriseCheck(IRGS& env) {
auto const ptr = resumeMode(env) != ResumeMode::None ? sp(env) : fp(env);
auto const exit = makeExitSlow(env);
gen(env, CheckSurpriseFlags, exit, ptr);
}
void surpriseCheck(IRGS& env, Offset relOffset) {
if (relOffset <= 0) {
surpriseCheck(env);
}
}
void surpriseCheckWithTarget(IRGS& env, Offset targetBcOff) {
auto const ptr = resumeMode(env) != ResumeMode::None ? sp(env) : fp(env);
auto const exit = makeExitSurprise(env, SrcKey{curSrcKey(env), targetBcOff});
gen(env, CheckSurpriseFlags, exit, ptr);
}
/*
* Returns an IR block corresponding to the given bytecode offset. The block
* may be a side exit or a normal IR block, depending on whether or not the
* offset is in the current RegionDesc.
*/
Block* getBlock(IRGS& env, Offset offset) {
SrcKey sk(curSrcKey(env), offset);
// If hasBlock returns true, then IRUnit already has a block for that offset
// and makeBlock will just return it. This will be the proper successor
// block set by setSuccIRBlocks. Otherwise, the given offset doesn't belong
// to the region, so we just create an exit block.
if (!env.irb->hasBlock(sk)) return makeExit(env, sk);
return env.irb->makeBlock(sk, curProfCount(env));
}
//////////////////////////////////////////////////////////////////////
void jmpImpl(IRGS& env, Offset offset) {
auto target = getBlock(env, offset);
assertx(target != nullptr);
gen(env, Jmp, target);
}
void implCondJmp(IRGS& env, Offset taken, bool negate, SSATmp* src) {
auto const target = getBlock(env, taken);
assertx(target != nullptr);
auto const boolSrc = gen(env, ConvTVToBool, src);
decRef(env, src);
gen(env, negate ? JmpZero : JmpNZero, target, boolSrc);
}
//////////////////////////////////////////////////////////////////////
void emitJmp(IRGS& env, Offset relOffset) {
surpriseCheck(env, relOffset);
jmpImpl(env, bcOff(env) + relOffset);
}
void emitJmpNS(IRGS& env, Offset relOffset) {
jmpImpl(env, bcOff(env) + relOffset);
}
void emitJmpZ(IRGS& env, Offset relOffset) {
surpriseCheck(env, relOffset);
auto const takenOff = bcOff(env) + relOffset;
implCondJmp(env, takenOff, true, popC(env));
}
void emitJmpNZ(IRGS& env, Offset relOffset) {
surpriseCheck(env, relOffset);
auto const takenOff = bcOff(env) + relOffset;
implCondJmp(env, takenOff, false, popC(env));
}
//////////////////////////////////////////////////////////////////////
static const StaticString s_switchProfile("SwitchProfile");
void emitSwitch(IRGS& env, SwitchKind kind, int64_t base,
const ImmVector& iv) {
auto bounded = kind == SwitchKind::Bounded;
int nTargets = bounded ? iv.size() - 2 : iv.size();
SSATmp* const switchVal = popC(env);
Type type = switchVal->type();
assertx(IMPLIES(!(type <= TInt), bounded));
assertx(IMPLIES(bounded, iv.size() > 2));
SSATmp* index;
SSATmp* ssabase = cns(env, base);
SSATmp* ssatargets = cns(env, nTargets);
Offset defaultOff = bcOff(env) + iv.vec32()[iv.size() - 1];
Offset zeroOff = 0;
if (base <= 0 && (base + nTargets) > 0) {
zeroOff = bcOff(env) + iv.vec32()[0 - base];
} else {
zeroOff = defaultOff;
}
if (type <= TNull) {
gen(env, Jmp, getBlock(env, zeroOff));
return;
}
if (type <= TBool) {
Offset nonZeroOff = bcOff(env) + iv.vec32()[iv.size() - 2];
gen(env, JmpNZero, getBlock(env, nonZeroOff), switchVal);
gen(env, Jmp, getBlock(env, zeroOff));
return;
}
if (type <= TArrLike) {
decRef(env, switchVal);
gen(env, Jmp, getBlock(env, defaultOff));
return;
}
if (type <= TInt) {
// No special treatment needed
index = switchVal;
} else if (type <= TDbl) {
// switch(Double|String|Obj)Helper do bounds-checking for us, so we need to
// make sure the default case is in the jump table, and don't emit our own
// bounds-checking code.
bounded = false;
index = gen(env, LdSwitchDblIndex, switchVal, ssabase, ssatargets);
} else if (type <= TStr) {
bounded = false;
index = gen(env, LdSwitchStrIndex, switchVal, ssabase, ssatargets);
} else if (type <= TObj) {
// switchObjHelper can throw exceptions and reenter the VM so we use the
// catch block here.
bounded = false;
index = gen(env, LdSwitchObjIndex, switchVal, ssabase, ssatargets);
} else {
PUNT(Switch-UnknownType);
}
auto const dataSize = SwitchProfile::extraSize(iv.size());
TargetProfile<SwitchProfile> profile(
env.context, env.irb->curMarker(), s_switchProfile.get(), dataSize
);
auto checkBounds = [&] {
if (!bounded) return;
index = gen(env, SubInt, index, cns(env, base));
auto const ok = gen(env, CheckRange, index, cns(env, nTargets));
gen(env, JmpZero, getBlock(env, defaultOff), ok);
bounded = false;
};
auto const offsets = iv.range32();
// We lower Switch to a series of comparisons if any of the successors are in
// included in the region.
auto const shouldLower =
std::any_of(offsets.begin(), offsets.end(), [&](Offset o) {
SrcKey sk(curSrcKey(env), bcOff(env) + o);
return env.irb->hasBlock(sk);
});
if (shouldLower && profile.optimizing()) {
auto const values = sortedSwitchProfile(profile, iv.size());
FTRACE(2, "Switch profile data for Switch @ {}\n", bcOff(env));
for (UNUSED auto const& val : values) {
FTRACE(2, " case {} hit {} times\n", val.caseIdx, val.count);
}
// Emit conditional checks for all successors in this region, in descending
// order of hotness. We rely on the region selector to decide which arcs
// are appropriate to include in the region. Fall through to the
// fully-generic JmpSwitchDest at the end if nothing matches.
for (auto const& val : values) {
auto targetOff = bcOff(env) + offsets[val.caseIdx];
SrcKey sk(curSrcKey(env), targetOff);
if (!env.irb->hasBlock(sk)) continue;
if (bounded && val.caseIdx == iv.size() - 2) {
// If we haven't checked bounds yet and this is the "first non-zero"
// case, we have to skip it. This case is only hit for non-Int input
// types anyway.
continue;
}
if (val.caseIdx == iv.size() - 1) {
// Default case.
checkBounds();
} else {
auto ok = gen(env, EqInt, cns(env, val.caseIdx + (bounded ? base : 0)),
index);
gen(env, JmpNZero, getBlock(env, targetOff), ok);
}
}
} else if (profile.profiling()) {
gen(env, ProfileSwitchDest,
ProfileSwitchData{profile.handle(), iv.size(), bounded ? base : 0},
index);
}
// Make sure to check bounds, if we haven't yet.
checkBounds();
std::vector<SrcKey> targets;
targets.reserve(iv.size());
for (auto const offset : offsets) {
targets.emplace_back(SrcKey{curSrcKey(env), bcOff(env) + offset});
}
auto data = JmpSwitchData{};
data.cases = iv.size();
data.targets = &targets[0];
data.spOffBCFromFP = spOffBCFromFP(env);
data.spOffBCFromIRSP = spOffBCFromIRSP(env);
gen(env, JmpSwitchDest, data, index, sp(env), fp(env));
}
void emitSSwitch(IRGS& env, const ImmVector& iv) {
const int numCases = iv.size() - 1;
/*
* We use a fast path translation with a hashtable if none of the
* cases are numeric strings and if the input is actually a string.
*
* Otherwise we do a linear search through the cases calling string
* conversion routines.
*/
const bool fastPath =
topC(env)->isA(TStr) &&
std::none_of(iv.strvec(), iv.strvec() + numCases,
[&](const StrVecItem& item) {
return curUnit(env)->lookupLitstrId(item.str)->isNumeric();
}
);
auto const testVal = popC(env);
std::vector<LdSSwitchData::Elm> cases(numCases);
for (int i = 0; i < numCases; ++i) {
auto const& kv = iv.strvec()[i];
cases[i].str = curUnit(env)->lookupLitstrId(kv.str);
cases[i].dest = SrcKey{curSrcKey(env), bcOff(env) + kv.dest};
}
LdSSwitchData data;
data.numCases = numCases;
data.cases = &cases[0];
data.defaultSk = SrcKey{curSrcKey(env),
bcOff(env) + iv.strvec()[iv.size() - 1].dest};
data.bcSPOff = spOffBCFromFP(env);
auto const dest = gen(env,
fastPath ? LdSSwitchDestFast
: LdSSwitchDestSlow,
data,
testVal);
decRef(env, testVal);
gen(
env,
JmpSSwitchDest,
IRSPRelOffsetData { spOffBCFromIRSP(env) },
dest,
sp(env),
fp(env)
);
}
void emitThrowNonExhaustiveSwitch(IRGS& env) {
interpOne(env);
}
const StaticString s_class_to_string(Strings::CLASS_TO_STRING);
void emitRaiseClassStringConversionWarning(IRGS& env) {
if (RuntimeOption::EvalRaiseClassConversionWarning) {
gen(env, RaiseWarning, cns(env, s_class_to_string.get()));
}
}
//////////////////////////////////////////////////////////////////////
void emitSelect(IRGS& env) {
auto const condSrc = popC(env);
auto const boolSrc = gen(env, ConvTVToBool, condSrc);
decRef(env, condSrc);
ifThenElse(
env,
[&] (Block* taken) { gen(env, JmpZero, taken, boolSrc); },
[&] { // True case
auto const val = popC(env, DataTypeGeneric);
popDecRef(env, DataTypeGeneric);
push(env, val);
},
[&] { popDecRef(env, DataTypeGeneric); } // False case
);
}
//////////////////////////////////////////////////////////////////////
void emitThrow(IRGS& env) {
auto const stackEmpty = spOffBCFromFP(env) == spOffEmpty(env) + 1;
auto const offset = findCatchHandler(curFunc(env), bcOff(env));
auto const srcTy = topC(env)->type();
auto const maybeThrowable =
srcTy.maybe(Type::SubObj(SystemLib::s_ExceptionClass)) ||
srcTy.maybe(Type::SubObj(SystemLib::s_ErrorClass));
if (!stackEmpty || !maybeThrowable || !(srcTy <= TObj)) return interpOne(env);
auto const handleThrow = [&] {
if (offset != kInvalidOffset) return jmpImpl(env, offset);
// There are no more catch blocks in this function, we are at the top
// level throw
auto const exn = popC(env);
auto const spOff = IRSPRelOffsetData { spOffBCFromIRSP(env) };
gen(env, EagerSyncVMRegs, spOff, fp(env), sp(env));
updateMarker(env);
gen(env, EnterTCUnwind, EnterTCUnwindData { true }, exn);
};
if (srcTy <= Type::SubObj(SystemLib::s_ThrowableClass)) return handleThrow();
ifThenElse(env,
[&] (Block* taken) {
assertx(srcTy <= TObj);
auto const srcClass = gen(env, LdObjClass, topC(env));
auto const ecdExc = ExtendsClassData { SystemLib::s_ExceptionClass };
auto const isException = gen(env, ExtendsClass, ecdExc, srcClass);
gen(env, JmpNZero, taken, isException);
auto const ecdErr = ExtendsClassData { SystemLib::s_ErrorClass };
auto const isError = gen(env, ExtendsClass, ecdErr, srcClass);
gen(env, JmpNZero, taken, isError);
},
[&] { gen(env, Jmp, makeExitSlow(env)); },
handleThrow
);
}
//////////////////////////////////////////////////////////////////////
}}}
| 34.029891 | 80 | 0.607602 | [
"vector"
] |
739e1cb46a526dc51c75194caba34b7ad2fe4cb2 | 1,623 | cpp | C++ | uva/volume-006/blowing_fuses.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | uva/volume-006/blowing_fuses.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | uva/volume-006/blowing_fuses.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <iostream>
#include <vector>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int test {1};
unsigned int devices;
unsigned int operations;
unsigned int capacity;
while (cin >> devices >> operations >> capacity &&
!(devices == 0 && operations == 0 && capacity == 0))
{
vector<unsigned int> consumptions(devices);
for (auto& consumption : consumptions)
{
cin >> consumption;
}
vector<bool> is_on(devices);
unsigned int current_consumption {0};
unsigned int max_consumption {0};
for (unsigned int i {0}; i < operations; ++i)
{
unsigned int device;
cin >> device;
if (is_on[device - 1])
{
current_consumption -= consumptions[device - 1];
}
else
{
current_consumption += consumptions[device - 1];
}
max_consumption = max(max_consumption, current_consumption);
is_on[device - 1] = !is_on[device - 1];
}
cout << "Sequence " << test++ << '\n';
if (max_consumption > capacity)
{
cout << "Fuse was blown.\n";
}
else
{
cout << "Fuse was not blown.\n"
<< "Maximal power consumption was "
<< max_consumption
<< " amperes.\n";
}
cout << '\n';
}
return 0;
}
| 21.64 | 75 | 0.496611 | [
"vector"
] |
73a0800fe010af9cac977ef39182152450ae30f0 | 8,035 | hpp | C++ | include/LaneDetectionModule.hpp | harshkakashaniya/Traffic_Lane_Detection_for_Autonomous_Vehicles | b1ff6686d6fb2bea3e39908b0b0d360ce530058d | [
"MIT"
] | 3 | 2019-01-18T07:21:18.000Z | 2022-03-27T09:40:09.000Z | include/LaneDetectionModule.hpp | harshkakashaniya/Traffic_Lane_Detection_for_Autonomous_Vehicles | b1ff6686d6fb2bea3e39908b0b0d360ce530058d | [
"MIT"
] | null | null | null | include/LaneDetectionModule.hpp | harshkakashaniya/Traffic_Lane_Detection_for_Autonomous_Vehicles | b1ff6686d6fb2bea3e39908b0b0d360ce530058d | [
"MIT"
] | 6 | 2018-10-09T23:17:17.000Z | 2020-03-15T04:42:52.000Z | /************************************************************************
MIT License
Copyright (c) 2018 Harsh Kakashaniya,Rohitkrishna Nambiar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*************************************************************************/
/**
* @file LaneDetectionModule.cpp
* @author Harsh Kakashaniya and Rohitkrishna Nambiar
* @date 10/12/2018
* @version 1.0
*
* @brief UMD ENPM 808X, Week 5,Midterm Project.
*
* @Description DESCRIPTION
*
* Class member functions for LaneDetectionModule.h
*
*/
#ifndef INCLUDE_LANEDETECTIONMODULE_HPP_
#define INCLUDE_LANEDETECTIONMODULE_HPP_
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <opencv2/opencv.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "Lane.hpp"
class LaneDetectionModule {
public:
/**
* @brief Default constructor for LaneDetectionModule
*
*/
LaneDetectionModule();
/**
* @brief Default destructor for LaneDetectionModule
*
*/
~LaneDetectionModule();
/**
* @brief Method Undistortedimage for LaneDetectionModule
*
* @param src is a Matrix of source of image
* @param dst is a Matrix of destination of image
*/
void undistortImage(const cv::Mat& src, cv::Mat& dst);
/**
* @brief Method thresholdImageY to set
* yellow threshold image for LaneDetectionModule
*
* @param src is a Matrix of source of image
* @param dst is a Matrix of destination of imageg
*/
void thresholdImageY(const cv::Mat& src, cv::Mat& dst);
/**
* @brief Method thresholdImageW to set
* white threshold image for LaneDetectionModule
*
* @param src is a Matrix of source of image
* @param dst is a Matrix of destination of image
*/
void thresholdImageW(const cv::Mat& src, cv::Mat& dst);
/**
* @brief Method extractROI to set
* region of interest for LaneDetectionModule
*
* @param src is a Matrix of source of image
* @param dst is a Matrix of destination of image
*/
void extractROI(const cv::Mat& src, cv::Mat& dst);
/**
* @brief Method transforming perspective of lane image
*
*
* @param src is a Matrix of source of image
* @param dst is a Matrix of destination of image
* @param Tm is the transformation matrix for perspective
* @param invTm is the inverse of the transformation matrix
*/
void transformPerspective(const cv::Mat& src, cv::Mat& dst, cv::Mat& Tm,
cv::Mat& invTm);
/**
* @brief Method extractLanes to calculate
* parameters of lines and its characteristics
* for LaneDetectionModule.
*
* @param src is a Matrix of source of image
* @param dst is a Matrix of destination of image
* @param lane1 object of class lane to store line characteristic.
* @param lane2 object of class lane to store line characteristic
* @param curveFlag to set degree of curve
*/
void extractLanes(const cv::Mat& src, cv::Mat& dst, Lane& lane1, Lane& lane2,
int curveFlag);
/**
* @brief Method fitPoly fits a 2nd order polynomial to the points
* on the lane
*
* @param src is the input image from previous step
* @param dst is the destination Mat to store the coefficients of the
* polynomial
* @param order is the order of polynomial
*/
void fitPoly(const std::vector<cv::Point>& src, cv::Mat& dst, int order);
/**
* @brief Method getDriveHeading to calculate
* drive heading to be given to actuator for further action
* in LaneDetectionModule.
*
* @param lane1 object of class lane to store line characteristic.
* @param lane2 object of class lane to store line characteristic.
* @param direction is the string object to hold direction left etc.
*
* @return value of drive head.
*/
double getDriveHeading(Lane& lane1, Lane& lane2, std::string& direction);
/**
* @brief Method displayOutput to calculate
* to display of the system
* for LaneDetectionModule.
*
* @param src is a Matrix of source of image
* @param src2 is the source color image
* @param lane1 object of class lane to store line characteristic.
* @param lane2 object of class lane to store line characteristic
* @param inv is the inverse perspective transformation matrix
*/
void displayOutput(const cv::Mat& src, cv::Mat& src2, Lane& lane1,
Lane& lane2, cv::Mat inv);
/**
* @brief Method detectLane check if program is successfully running
* gives bool output for LaneDetectionModule
*
* @param videoName is video of source
*
* @return Status of lane detection.
*/
bool detectLane(std::string videoName);
/**
* @brief Method getYellowMax is to use get HSL max value of yellow
* for LaneDetectionModule
*
* @return HSL values for yellow lane.
*/
cv::Scalar getYellowMax();
/**
* @brief Method getYellowMin is to use get HSL min value of yellow
* for LaneDetectionModule
*
* @return HSL values for yellow lane.
*/
cv::Scalar getYellowMin();
/**
* @brief Method setYellowMax is to use set HSL max value of yellow
* for LaneDetectionModule
*
* @param HSL values for yellow lane
*/
void setYellowMax(cv::Scalar value);
/**
* @brief Method setYellowMin is to use set min value of yellow
* for LaneDetectionModule
*
* @param HSL values for yellow lane.
*/
void setYellowMin(cv::Scalar value);
/**
* @brief Method setGrayScaleMax is to use set max value of Gray scale
* value for LaneDetectionModule
*
* @param int of max GrayScale value.
*/
void setGrayScaleMax(int value);
/**
* @brief Method setGrayScaleMin is to use set min value of Gray scale
* value for LaneDetectionModule
*
* @param int of min GrayScale value
*/
void setGrayScaleMin(int value);
/**
* @brief Method getGrayScaleMin is to use get min value of GrayScale
* for LaneDetectionModule
*
* @return int of min GrayScale value
*/
int getGrayScaleMin();
/**
* @brief Method getGrayScaleMax is to use get max value of GrayScale
* for LaneDetectionModule
*
* @return int of max GrayScale values
*/
int getGrayScaleMax();
private:
cv::Scalar yellowMin; // max possible RGB values of yellow
cv::Scalar yellowMax; // min possible RGB values of yellow
int grayscaleMin; // min possible grayscale value for white in our video
int grayscaleMax; // max possible grayscale value for white in our video
std::string videoName; // specify video name
};
#endif // INCLUDE_LANEDETECTIONMODULE_HPP_
| 31.884921 | 79 | 0.664592 | [
"object",
"vector"
] |
73a806aa2f22cee32035f1cd628977a146f349af | 11,847 | cpp | C++ | src/PointwiseFunctions/AnalyticData/GrMhd/MagnetizedFmDisk.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 1 | 2022-01-11T00:17:33.000Z | 2022-01-11T00:17:33.000Z | src/PointwiseFunctions/AnalyticData/GrMhd/MagnetizedFmDisk.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | src/PointwiseFunctions/AnalyticData/GrMhd/MagnetizedFmDisk.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "PointwiseFunctions/AnalyticData/GrMhd/MagnetizedFmDisk.hpp"
#include <array>
#include <cmath>
#include <cstddef>
#include <ostream>
#include <pup.h>
#include "DataStructures/DataVector.hpp" // IWYU pragma: keep
#include "DataStructures/Index.hpp"
#include "DataStructures/Tensor/EagerMath/DotProduct.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "PointwiseFunctions/GeneralRelativity/Tags.hpp" // IWYU pragma: keep
#include "PointwiseFunctions/Hydro/EquationsOfState/PolytropicFluid.hpp" // IWYU pragma: keep
#include "PointwiseFunctions/Hydro/Tags.hpp"
#include "Utilities/ConstantExpressions.hpp"
#include "Utilities/ContainerHelpers.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/MakeWithValue.hpp"
// IWYU pragma: no_forward_declare Tensor
namespace grmhd::AnalyticData {
MagnetizedFmDisk::MagnetizedFmDisk(
const double bh_mass, const double bh_dimless_spin,
const double inner_edge_radius, const double max_pressure_radius,
const double polytropic_constant, const double polytropic_exponent,
const double threshold_density, const double inverse_plasma_beta,
const size_t normalization_grid_res)
: RelativisticEuler::Solutions::FishboneMoncriefDisk(
bh_mass, bh_dimless_spin, inner_edge_radius, max_pressure_radius,
polytropic_constant, polytropic_exponent),
threshold_density_(threshold_density),
inverse_plasma_beta_(inverse_plasma_beta),
normalization_grid_res_(normalization_grid_res),
kerr_schild_coords_{bh_mass, bh_dimless_spin} {
ASSERT(threshold_density_ > 0.0 and threshold_density_ < 1.0,
"The threshold density must be in the range (0, 1). The value given "
"was "
<< threshold_density_ << ".");
ASSERT(inverse_plasma_beta_ >= 0.0,
"The inverse plasma beta must be non-negative. The value given "
"was "
<< inverse_plasma_beta_ << ".");
ASSERT(normalization_grid_res_ >= 4,
"The grid resolution used in the magnetic field normalization must be "
"at least 4 points. The value given was "
<< normalization_grid_res_);
// The normalization of the magnetic field is determined by the condition
//
// plasma beta = pgas_max / pmag_max
//
// where pgas_max and pmag_max are the maximum values of the gas and magnetic
// pressure over the domain, respectively. pgas_max is obtained by
// evaluating the pressure of the Fishbone-Moncrief solution at the
// corresponding radius. In order to compare with other groups, pmag_max is
// obtained by precomputing the unnormalized magnetic field and then
// finding the maximum of the comoving field squared on a given grid.
// Following the CodeComparisonProject files, we choose to find the maximum
// on a spherical grid as described below.
// Set up a Kerr ("spherical Kerr-Schild") grid of constant phi = 0,
// whose parameterization in Cartesian Kerr-Schild coordinates is
// x(r, theta) = r sin_theta,
// y(r, theta) = a sin_theta,
// z(r, theta) = r cos_theta.
const double r_init = inner_edge_radius_ * bh_mass_;
const double r_fin = max_pressure_radius_ * bh_mass_;
const double dr = (r_fin - r_init) / normalization_grid_res_;
const double dtheta = M_PI / normalization_grid_res_;
const double cartesian_n_pts = square(normalization_grid_res_);
Index<2> extents(normalization_grid_res_, normalization_grid_res_);
auto grid =
make_with_value<tnsr::I<DataVector, 3>>(DataVector(cartesian_n_pts), 0.0);
for (size_t i = 0; i < normalization_grid_res_; ++i) {
double r_i = r_init + static_cast<double>(i) * dr;
for (size_t j = 0; j < normalization_grid_res_; ++j) {
double sin_theta_j = sin(static_cast<double>(j) * dtheta);
auto index = collapsed_index(Index<2>{i, j}, extents);
get<0>(grid)[index] = r_i * sin_theta_j;
get<1>(grid)[index] = bh_spin_a_ * sin_theta_j;
get<2>(grid)[index] = r_i * cos(static_cast<double>(j) * dtheta);
}
}
const auto b_field = unnormalized_magnetic_field(grid);
const auto unmagnetized_vars = variables(
grid, tmpl::list<gr::Tags::SpatialMetric<3>,
hydro::Tags::LorentzFactor<DataVector>,
hydro::Tags::SpatialVelocity<DataVector, 3>>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3>>(unmagnetized_vars);
const tnsr::I<double, 3> x_max{{{max_pressure_radius_, bh_spin_a_, 0.0}}};
const double b_squared_max = max(
get(dot_product(b_field, b_field, spatial_metric)) /
square(get(
get<hydro::Tags::LorentzFactor<DataVector>>(unmagnetized_vars))) +
square(get(dot_product(
b_field,
get<hydro::Tags::SpatialVelocity<DataVector, 3>>(unmagnetized_vars),
spatial_metric))));
ASSERT(b_squared_max > 0.0, "Max b squared is zero.");
b_field_normalization_ =
sqrt(2.0 *
get(get<hydro::Tags::Pressure<double>>(
variables(x_max, tmpl::list<hydro::Tags::Pressure<double>>{}))) *
inverse_plasma_beta_ / b_squared_max);
}
MagnetizedFmDisk::MagnetizedFmDisk(CkMigrateMessage* msg)
: FishboneMoncriefDisk(msg) {}
void MagnetizedFmDisk::pup(PUP::er& p) {
RelativisticEuler::Solutions::FishboneMoncriefDisk::pup(p);
p | threshold_density_;
p | inverse_plasma_beta_;
p | b_field_normalization_;
p | normalization_grid_res_;
p | kerr_schild_coords_;
}
template <typename DataType>
tnsr::I<DataType, 3> MagnetizedFmDisk::unnormalized_magnetic_field(
const tnsr::I<DataType, 3>& x) const {
auto magnetic_field =
make_with_value<tnsr::I<DataType, 3, Frame::NoFrame>>(x, 0.0);
// The maximum pressure (and hence the maximum rest mass density) is located
// on the ring x^2 + y^2 = r_max^2 + a^2, z = 0.
// Note that `x` may or may not include points on this ring.
const tnsr::I<double, 3> x_max{{{max_pressure_radius_, bh_spin_a_, 0.0}}};
const double threshold_rest_mass_density =
threshold_density_ *
get(get<hydro::Tags::RestMassDensity<double>>(variables(
x_max, tmpl::list<hydro::Tags::RestMassDensity<double>>{})));
const double inner_edge_potential =
fm_disk::potential(square(inner_edge_radius_), 1.0);
// A_phi \propto rho - rho_threshold. Normalization comes later.
const auto mag_potential = [this, &threshold_rest_mass_density,
&inner_edge_potential](
const double r,
const double sin_theta_squared) {
// enthalpy = exp(Win - W(r,theta)), as in the Fishbone-Moncrief disk
return get(equation_of_state_.rest_mass_density_from_enthalpy(
Scalar<double>{
exp(inner_edge_potential -
fm_disk::potential(square(r), sin_theta_squared))})) -
threshold_rest_mass_density;
};
// The magnetic field is present only within the disk, where the
// rest mass density is greater than the threshold rest mass density.
const DataType rest_mass_density =
get(get<hydro::Tags::RestMassDensity<DataType>>(
variables(x, tmpl::list<hydro::Tags::RestMassDensity<DataType>>{})));
for (size_t s = 0; s < get_size(get<0>(x)); ++s) {
if (get_element(rest_mass_density, s) > threshold_rest_mass_density) {
// The magnetic field is defined in terms of the Faraday tensor in Kerr
// (r, theta, phi) coordinates. We need to get B^r, B^theta, B^phi first,
// then we transform to Cartesian coordinates.
const double z_squared = square(get_element(get<2>(x), s));
const double a_squared = bh_spin_a_ * bh_spin_a_;
double sin_theta_squared =
square(get_element(get<0>(x), s)) + square(get_element(get<1>(x), s));
double r_squared = 0.5 * (sin_theta_squared + z_squared - a_squared);
r_squared += sqrt(square(r_squared) + a_squared * z_squared);
sin_theta_squared /= (r_squared + a_squared);
// B^i is proportional to derivatives of the magnetic potential. One has
//
// B^r = sqrt(gamma) * \partial_\theta A_\phi
// B^\theta = -sqrt(gamma) * \partial_r A_\phi
//
// where sqrt(gamma) = sqrt( sigma (sigma + 2Mr) ) * sin\theta.
const double radius = sqrt(r_squared);
const double sin_theta = sqrt(sin_theta_squared);
double prefactor = r_squared + square(bh_spin_a_) * z_squared / r_squared;
prefactor *= (prefactor + 2.0 * bh_mass_ * radius);
// As done by SpEC and other groups, we approximate the derivatives
// with a 2nd-order centered finite difference expression.
// For simplicity, we set \delta r = \delta\theta = small number.
const double small = 0.0001 * bh_mass_;
prefactor = 2.0 * small * sqrt(prefactor) * sin_theta;
prefactor = 1.0 / prefactor;
// Since the metric, and thus the field, depend on theta through
// sin^2(theta) only, we use chain rule in B^\theta and write
//
// d/d\theta = 2 * sin\theta * cos\theta * d/d(sin^2(theta)),
//
// where cos\theta = z/r.
get_element(get<0>(magnetic_field), s) =
2.0 * prefactor * sin_theta * get_element(get<2>(x), s) *
(mag_potential(radius, sin_theta_squared + small) -
mag_potential(radius, sin_theta_squared - small)) /
radius;
get_element(get<1>(magnetic_field), s) =
prefactor * (mag_potential(radius - small, sin_theta_squared) -
mag_potential(radius + small, sin_theta_squared));
// phi component of the field vanishes identically.
}
}
return kerr_schild_coords_.cartesian_from_spherical_ks(
std::move(magnetic_field), x);
}
template <typename DataType, bool NeedSpacetime>
tuples::TaggedTuple<hydro::Tags::MagneticField<DataType, 3>>
MagnetizedFmDisk::variables(
const tnsr::I<DataType, 3>& x,
tmpl::list<hydro::Tags::MagneticField<DataType, 3>> /*meta*/,
const IntermediateVariables<DataType, NeedSpacetime>& /*vars*/,
const size_t /*index*/) const {
auto result = unnormalized_magnetic_field(x);
for (size_t i = 0; i < 3; ++i) {
result.get(i) *= b_field_normalization_;
}
return result;
}
PUP::able::PUP_ID MagnetizedFmDisk::my_PUP_ID = 0;
bool operator==(const MagnetizedFmDisk& lhs, const MagnetizedFmDisk& rhs) {
using fm_disk = MagnetizedFmDisk::fm_disk;
return *static_cast<const fm_disk*>(&lhs) ==
*static_cast<const fm_disk*>(&rhs) and
lhs.threshold_density_ == rhs.threshold_density_ and
lhs.inverse_plasma_beta_ == rhs.inverse_plasma_beta_ and
lhs.b_field_normalization_ == rhs.b_field_normalization_ and
lhs.normalization_grid_res_ == rhs.normalization_grid_res_;
}
bool operator!=(const MagnetizedFmDisk& lhs, const MagnetizedFmDisk& rhs) {
return not(lhs == rhs);
}
#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)
#define NEED_SPACETIME(data) BOOST_PP_TUPLE_ELEM(1, data)
#define INSTANTIATE(_, data) \
template tuples::TaggedTuple<hydro::Tags::MagneticField<DTYPE(data), 3>> \
MagnetizedFmDisk::variables( \
const tnsr::I<DTYPE(data), 3>& x, \
tmpl::list<hydro::Tags::MagneticField<DTYPE(data), 3>> /*meta*/, \
const FishboneMoncriefDisk::IntermediateVariables< \
DTYPE(data), NEED_SPACETIME(data)>& vars, \
const size_t) const;
GENERATE_INSTANTIATIONS(INSTANTIATE, (double, DataVector), (true, false))
#undef DTYPE
#undef NEED_SPACETIME
#undef INSTANTIATE
} // namespace grmhd::AnalyticData
| 44.370787 | 94 | 0.678315 | [
"transform"
] |
73a98788fb9be50e51dc844d90968ad04d8795bc | 314 | cpp | C++ | LeetCode/Problems/Algorithms/#771_JewelsAndStones.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#771_JewelsAndStones.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#771_JewelsAndStones.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
public:
int numJewelsInStones(string J, string S) {
vector<int> cnt(256, 0);
for(char c: S){
++cnt[c];
}
int answer = 0;
for(char c: J){
answer += cnt[c];
}
return answer;
}
}; | 19.625 | 48 | 0.39172 | [
"vector"
] |
73aba9261c25b7db490eb6c1e55ec58868197198 | 9,288 | cpp | C++ | .history/src/BehaviorDribble_20210917134821.cpp | hoang000147/wrighteaglebase | 227e0151ba90a8367a4b09b934cac863b483d4dd | [
"BSD-2-Clause"
] | null | null | null | .history/src/BehaviorDribble_20210917134821.cpp | hoang000147/wrighteaglebase | 227e0151ba90a8367a4b09b934cac863b483d4dd | [
"BSD-2-Clause"
] | null | null | null | .history/src/BehaviorDribble_20210917134821.cpp | hoang000147/wrighteaglebase | 227e0151ba90a8367a4b09b934cac863b483d4dd | [
"BSD-2-Clause"
] | null | null | null | /************************************************************************************
* WrightEagle (Soccer Simulation League 2D) *
* BASE SOURCE CODE RELEASE 2016 *
* Copyright (c) 1998-2016 WrightEagle 2D Soccer Simulation Team, *
* Multi-Agent Systems Lab., *
* School of Computer Science and Technology, *
* University of Science and Technology of China *
* 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 WrightEagle 2D Soccer Simulation Team 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 WrightEagle 2D Soccer Simulation Team 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 "BehaviorDribble.h"
#include "Agent.h"
#include "Kicker.h"
#include "WorldState.h"
#include "Strategy.h"
#include "Formation.h"
#include "Dasher.h"
#include "Types.h"
#include "Logger.h"
#include "VisualSystem.h"
#include "CommunicateSystem.h"
#include "Utilities.h"
#include <sstream>
#include <vector>
#include <utility>
#include "Evaluation.h"
#include <cmath>
using namespace std;
const BehaviorType BehaviorDribbleExecuter::BEHAVIOR_TYPE = BT_Dribble;
namespace {
bool ret = BehaviorExecutable::AutoRegister<BehaviorDribbleExecuter>();
}
BehaviorDribbleExecuter::BehaviorDribbleExecuter(Agent & agent) :
BehaviorExecuterBase<BehaviorAttackData>( agent )
{
Assert(ret);
}
BehaviorDribbleExecuter::~BehaviorDribbleExecuter(void)
{
}
bool BehaviorDribbleExecuter::Execute(const ActiveBehavior & dribble)
{
Logger::instance().LogDribble(mBallState.GetPos(), dribble.mTarget, "@Dribble", true);
if(dribble.mDetailType == BDT_Dribble_Normal) {
Vector ballpos = mBallState.GetPos();
PlayerState oppState = mWorldState.GetOpponent(mPositionInfo.GetClosestOpponentToBall());
Vector posOpp = oppState.GetPos();
ballpos = mBallState.GetPredictedPos(1);
Vector agentpos = mSelfState.GetPos();
Vector agent_v = agentpos - mSelfState.GetPos();
AngleDeg agentang = mSelfState.GetBodyDir();
AtomicAction act;
if ( mSelfState.GetStamina() < 2700){
Dasher::instance().GoToPoint(mAgent,act,dribble.mTarget,0.01,30);
}
else {
Dasher::instance().GoToPoint(mAgent,act,dribble.mTarget, 0.01 ,100 );
}
act.mDashPower = MinMax(-ServerParam::instance().maxDashPower(), act.mDashPower, ServerParam::instance().maxDashPower());
agent_v = mSelfState.GetVel() * mSelfState.GetDecay();
if(act.mType != CT_Dash){
agentpos = mSelfState.GetPredictedPos(1);
}
else
agentpos = mSelfState.GetPredictedPosWithDash(1,act.mDashPower,act.mDashDir);
bool collide = mSelfState.GetCollideWithPlayer();
if ( ballpos.Dist(agentpos) > 0.95 * ( mSelfState.GetKickableArea())
|| collide )//will not be kickable or will make a collision ??
{
int p = ( ( mBallState.GetPos() - mSelfState.GetPos() ).Dir() - mSelfState.GetBodyDir()) > 0 ? 1:-1 ;
double outSpeed = mSelfState.GetVel().Mod();
if ( act.mType == CT_Dash && fabs( act.mDashDir ) < FLOAT_EPS )
outSpeed += mSelfState.GetAccelerationFront(act.mDashPower);
if((agentpos + Polar2Vector(mSelfState.GetKickableArea(),agentang + p * 45) - mBallState.GetPos()).Mod() <
( agentpos + Polar2Vector(mSelfState.GetKickableArea(),agentang + p * 45) -mSelfState.GetPos()).Mod()) {
if ( mSelfState.GetStamina() < 2700)
{
return Dasher::instance().GoToPoint( mAgent , dribble.mTarget,0.01,30 ); // dash slow
}
else return Dasher::instance().GoToPoint( mAgent , dribble.mTarget,0.01,100 );
}
return Kicker::instance().KickBall(mAgent ,agentpos + Polar2Vector(mSelfState.GetKickableArea(),agentang + p * 45) , outSpeed,KM_Hard);
}
else {
if ( mSelfState.GetStamina() < 2700)
{
return Dasher::instance().GoToPoint( mAgent , dribble.mTarget,0.01,30 ); // dash slow
}
else return Dasher::instance().GoToPoint( mAgent , dribble.mTarget,0.01,100 );
}
}
else /*if(dribble.mDetailType == BDT_Dribble_Fast)*/{
return Kicker::instance().KickBall(mAgent, dribble.mAngle, dribble.mKickSpeed, KM_Quick);
}
}
BehaviorDribblePlanner::BehaviorDribblePlanner(Agent & agent) :
BehaviorPlannerBase <BehaviorAttackData>(agent)
{
}
BehaviorDribblePlanner::~BehaviorDribblePlanner(void)
{
}
void BehaviorDribblePlanner::Plan(std::list<ActiveBehavior> & behavior_list)
{
// if ball is not in this player's control (not in kickable area), return
if (!mSelfState.IsKickable()) return;
// if strategy forbids a player to dribble, return
if (mStrategy.IsForbidenDribble()) return;
// if player is goalie, return
if (mSelfState.IsGoalie()) return;
// for 180 degrees angle in front of player
for (AngleDeg dir = -90.0; dir < 90.0; dir += 2.5) {
ActiveBehavior dribble(mAgent, BT_Dribble, BDT_Dribble_Normal);
dribble.mAngle = dir;
// get all players that are in a specific distance with the ball
const std::vector<Unum> & opp2ball = mPositionInfo.GetCloseOpponentToBall();
AngleDeg min_differ = HUGE_VALUE;
for (uint j = 0; j < opp2ball.size(); ++j) {
// if this player's distance to ball > 15 then skip this player
Vector rel_pos = mWorldState.GetOpponent(opp2ball[j]).GetPos() - mBallState.GetPos();
if (rel_pos.Mod() > 15.0) continue;
// if this player's angle difference to this direction is smaller than min_differ, modify min_differ
AngleDeg differ = GetAngleDegDiffer(dir, rel_pos.Dir());
if (differ < min_differ) {
min_differ = differ;
}
}
// if min_differ < 10 then skip this direction
if (min_differ < 10.0) continue;
// dribble target position = player's position + vector polar (probably the distance if the player runs with max speed in the current direction)
dribble.mTarget= mSelfState.GetPos() + Polar2Vector( mSelfState.GetEffectiveSpeedMax(), dir);
// set behavior's evaluation to the calculation of (target position)
dribble.mEvaluation = Evaluation::instance().EvaluatePosition(dribble.mTarget, true);
// add behavior to the list
mActiveBehaviorList.push_back(dribble);
}
double speed = mSelfState.GetEffectiveSpeedMax();
for (AngleDeg dir = -90.0; dir < 90.0; dir += 2.5) {
ActiveBehavior dribble(mAgent, BT_Dribble, BDT_Dribble_Fast);
dribble.mKickSpeed = speed;
dribble.mAngle = dir;
const std::vector<Unum> & opp2ball = mPositionInfo.GetCloseOpponentToBall();
Vector target = mBallState.GetPos() + Polar2Vector(dribble.mKickSpeed * 10, dribble.mAngle);
if(!ServerParam::instance().pitchRectanglar().IsWithin(target)){
continue;
}
bool ok = true;
for (uint j = 0; j < opp2ball.size(); ++j) {
Vector rel_pos = mWorldState.GetOpponent(opp2ball[j]).GetPos() - target;
if (rel_pos.Mod() < dribble.mKickSpeed * 12 ||
mWorldState.GetOpponent(opp2ball[j]).GetPosConf() < PlayerParam::instance().minValidConf()){
ok = false;
break;
}
}
if(!ok){
continue;
}
dribble.mEvaluation = 0;
for (int i = 1; i <= 8; ++i) {
dribble.mEvaluation += Evaluation::instance().EvaluatePosition(mBallState.GetPos() + Polar2Vector(dribble.mKickSpeed * i, dribble.mAngle), true);
}
dribble.mEvaluation /= 8;
dribble.mTarget = target;
mActiveBehaviorList.push_back(dribble);
}
if (!mActiveBehaviorList.empty()) {
mActiveBehaviorList.sort(std::greater<ActiveBehavior>());
behavior_list.push_back(mActiveBehaviorList.front());
}
}
| 40.9163 | 148 | 0.661822 | [
"vector"
] |
73afc19c7963cb3abbdb61553020bf9bf6d02605 | 3,784 | hpp | C++ | include/codegen/include/GlobalNamespace/RGBPanelController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/RGBPanelController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/RGBPanelController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: UnityEngine.Color
#include "UnityEngine/Color.hpp"
// Including type: ColorChangeUIEventType
#include "GlobalNamespace/ColorChangeUIEventType.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: ColorGradientSlider
class ColorGradientSlider;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: RGBPanelController
class RGBPanelController : public UnityEngine::MonoBehaviour {
public:
// private HMUI.ColorGradientSlider _redSlider
// Offset: 0x18
HMUI::ColorGradientSlider* redSlider;
// private HMUI.ColorGradientSlider _greenSlider
// Offset: 0x20
HMUI::ColorGradientSlider* greenSlider;
// private HMUI.ColorGradientSlider _blueSlider
// Offset: 0x28
HMUI::ColorGradientSlider* blueSlider;
// private System.Action`2<UnityEngine.Color,ColorChangeUIEventType> colorDidChangeEvent
// Offset: 0x30
System::Action_2<UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* colorDidChangeEvent;
// private UnityEngine.Color _color
// Offset: 0x38
UnityEngine::Color color;
// public System.Void add_colorDidChangeEvent(System.Action`2<UnityEngine.Color,ColorChangeUIEventType> value)
// Offset: 0xC1FB04
void add_colorDidChangeEvent(System::Action_2<UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* value);
// public System.Void remove_colorDidChangeEvent(System.Action`2<UnityEngine.Color,ColorChangeUIEventType> value)
// Offset: 0xC1FBA8
void remove_colorDidChangeEvent(System::Action_2<UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* value);
// public UnityEngine.Color get_color()
// Offset: 0xC1FC4C
UnityEngine::Color get_color();
// public System.Void set_color(UnityEngine.Color value)
// Offset: 0xC1FC58
void set_color(UnityEngine::Color value);
// protected System.Void Awake()
// Offset: 0xC1FE58
void Awake();
// protected System.Void OnDestroy()
// Offset: 0xC1FF5C
void OnDestroy();
// private System.Void HandleSliderColorDidChange(HMUI.ColorGradientSlider slider, UnityEngine.Color color, ColorChangeUIEventType colorChangeUIEventType)
// Offset: 0xC20130
void HandleSliderColorDidChange(HMUI::ColorGradientSlider* slider, UnityEngine::Color color, GlobalNamespace::ColorChangeUIEventType colorChangeUIEventType);
// private System.Void RefreshSlidersValues()
// Offset: 0xC1FE00
void RefreshSlidersValues();
// private System.Void RefreshSlidersColors()
// Offset: 0xC1FC84
void RefreshSlidersColors();
// public System.Void .ctor()
// Offset: 0xC201D4
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static RGBPanelController* New_ctor();
}; // RGBPanelController
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::RGBPanelController*, "", "RGBPanelController");
#pragma pack(pop)
| 42.516854 | 161 | 0.738372 | [
"object"
] |
73b1468a96fcc8815fb213559c6c3254b9d7fea7 | 24,214 | cpp | C++ | librarymanagementsystem.cpp | sirilalithaadapa/LibraryManagementSystem | 8f2c7bda42c46ab4cc0785886d8a78e4324bbc81 | [
"MIT"
] | null | null | null | librarymanagementsystem.cpp | sirilalithaadapa/LibraryManagementSystem | 8f2c7bda42c46ab4cc0785886d8a78e4324bbc81 | [
"MIT"
] | null | null | null | librarymanagementsystem.cpp | sirilalithaadapa/LibraryManagementSystem | 8f2c7bda42c46ab4cc0785886d8a78e4324bbc81 | [
"MIT"
] | null | null | null | //DEFAULT ADMIN PASS IS "admin"
#include <bits/stdc++.h>
#define cntr setw(70)
using namespace std;
void adminMenu();
void mainMenu();
//*****************************************************************************************************************
// CLASS DECLARATION
//*****************************************************************************************************************
class Books
{
int bookId;
string bookName;
string authorName;
public:
void createBook()
{
cout << "Enter Book Id: ";
cin >> bookId;
cout << "Enter Book Name: ";
cin.ignore();
getline(cin, bookName);
cout << "Enter Author Name: ";
getline(cin, authorName);
}
void showBook()
{
cout << setw(43) << bookId << "\t\t " << bookName << "\t\t " << authorName << "\n";
}
void displayBook()
{
cout << "\n\t\t\t\t\t\tBOOK DETAILS\n\n";
cout << "Book Id: " << bookId << "\n"
<< "Book Name: " << bookName << "\n"
<< "Author Name: " << authorName << "\n\n";
}
int getBookId()
{
return bookId;
}
string getBookName()
{
return bookName;
}
string getAuthorName()
{
return authorName;
}
};
class Date
{
int currDay;
int currMonth;
int currYear;
public:
void setDate()
{
time_t now = time(0);
tm *ltm = localtime(&now);
currDay = ltm->tm_mday;
currMonth = 1 + ltm->tm_mon;
currYear = 1900 + ltm->tm_year;
}
void showDate()
{
cout << currDay << "/" << currMonth << "/" << currYear;
}
void resetDate()
{
currDay = 0;
currMonth = 0;
currYear = 0;
}
int getCurrDay()
{
return currDay;
}
int getCurrMonth()
{
return currMonth;
}
int getCurrYear()
{
return currYear;
}
};
class Student : public Date
{
int univRoll;
int currSem;
int studentBookNo;
int booksIssued;
string name;
public:
void createStudent()
{
cout << "Enter Student Id: ";
cin >> univRoll;
cout << "Enter Student Name: ";
cin.ignore();
getline(cin, name);
cout << "Enter Current Semester: ";
cin >> currSem;
booksIssued = 0;
studentBookNo = 0;
}
void showStudent()
{
cout << "\t\t\t\t" << univRoll << "\t\t" << name << setw(17) << currSem << setw(15);
if (booksIssued == 1)
{
cout << studentBookNo << setw(17);
setDate();
showDate();
cout << "\n";
}
else
{
cout << " - "
<< setw(16) << " - "
<< "\n";
}
}
void displayStudent()
{
cout << "\n\t\t\t\t\t\tSTUDENT DETAILS\n\n";
cout << "University Roll No.: " << univRoll << "\n"
<< "Student's Name: " << name << "\n"
<< "Current Semester: " << currSem << "\n\n";
}
void addBooks()
{
booksIssued = 1;
}
void resetBooks()
{
booksIssued = 0;
}
void setBookid(int bNum)
{
studentBookNo = bNum;
}
int getUnivRoll()
{
return univRoll;
}
int getCurrSemester()
{
return currSem;
}
int getBooksIssued()
{
return booksIssued;
}
int getStudentBooks()
{
return studentBookNo;
}
string getStudentName()
{
return name;
}
};
//*****************************************************************************************************************
// GLOBAL OBJECT DECLARATION
//*****************************************************************************************************************
Student st;
Books b;
fstream stu, file;
//*****************************************************************************************************************
// FUNCTION TO REPEATE A CERTAIN TASK
//*****************************************************************************************************************
void doTaskOnceAgain(string question, void (*f)(void))
{
cout << question;
char choice;
cin >> choice;
cout << "\n";
if (choice == 'Y' || choice == 'y')
f();
}
//*****************************************************************************************************************
// BOOK MAAGEMENT
//*****************************************************************************************************************
void addBook()
{
system("cls");
file.open("BookDetails.dat", ios::out | ios::app);
b.createBook();
file.write((char *)&b, sizeof(Books));
file.close();
cout << "\n\n\t\t\t\t\t\tBOOK ADDED SUCCESSFULLY\n";
doTaskOnceAgain("\t\t\t\t\t\tDO YOU WANT TO ADD ANOTHER BOOK?(Y/N): ", addBook);
}
void deleteBook()
{
system("cls");
int num;
cout << "Enter Book Id: ";
cin >> num;
file.open("BookDetails.dat", ios::in | ios::out);
fstream file2;
file2.open("temp.dat", ios::out);
file.seekg(0, ios::beg);
while (file.read((char *)&b, sizeof(Books)))
{
if (b.getBookId() == num)
{
b.displayBook();
}
if (b.getBookId() != num)
{
file2.write((char *)&b, sizeof(Books));
}
}
file2.close();
file.close();
remove("BookDetails.dat");
rename("temp.dat", "bookDetails.dat");
cout << "\t\t\t\t\t\tRECORD DELETED SUCCESSFULLY\n\n";
doTaskOnceAgain("\t\t\t\t\t\tDO YOU WANT TO DELETE ANOTHER RECORD?(Y/N): ", deleteBook);
}
void updateBook()
{
system("cls");
bool found = false;
int num;
cout << "Enter Book Id: ";
cin >> num;
file.open("BookDetails.dat", ios::in | ios::out);
while (file.read((char *)&b, sizeof(Books)) && found == false)
{
if (b.getBookId() == num)
{
cout << "\n";
b.displayBook();
cout << "\t\t\t\t\t\tENTER NEW DETAILS\n\n";
b.createBook();
int pos = -1 * sizeof(Books);
file.seekp(pos, ios::cur);
file.write((char *)&b, sizeof(Books));
cout << "\t\t\t\t\t\tRECORD UPDATED SUCCESSFULLY\n\n";
found = true;
}
}
file.close();
if (found == false)
{
cout << "\t\t\t\t\t\tRECORD NOT FOUND!!\n\n";
}
doTaskOnceAgain("\t\t\t\t\t\tDO YOU WANT TO UPDATE ANOTHER RECORD?(Y/N):", updateBook);
}
void displayBooks()
{
system("cls");
file.open("BookDetails.dat", ios::in);
cout << setw(78) << "**************************\n";
cout << cntr << " BOOK RECORDS\n";
cout << setw(78) << "**************************\n";
cout << "\n";
cout << "\t\t\t\t-------------------------------------------------------------\n";
cout << setw(45) << "Book Id" << setw(20) << "Book Name" << setw(20) << "Authour Name\n";
cout << "\t\t\t\t-------------------------------------------------------------\n";
while (file.read((char *)&b, sizeof(Books)))
{
b.showBook();
cout << "\t\t\t\t-------------------------------------------------------------\n";
}
cout << "\n\n";
file.close();
}
//*****************************************************************************************************************
// STUDENT MANAGEMENT FUNCTIONS
//*****************************************************************************************************************
void addStudent()
{
system("cls");
stu.open("StudentDetails.dat", ios::out | ios::app);
st.createStudent();
stu.write((char *)&st, sizeof(Student));
stu.close();
cout << "\n\n"
<< "\t\t\t\t\t\tSTUDENT RECORD ADDED SUCCESSFULLY\n";
doTaskOnceAgain("\t\t\t\t\t\tDO YOU WANT TO ADD ANOTHER RECORD?(Y/N): ", addStudent);
}
void deleteStudent()
{
system("cls");
int num;
cout << "Enter Student Id: ";
cin >> num;
stu.open("StudentDetails.dat", ios::in | ios::out);
fstream file1;
file1.open("temp.dat", ios::out);
stu.seekg(0, ios::beg);
while (stu.read((char *)&st, sizeof(Student)))
{
if (st.getUnivRoll() == num)
{
st.displayStudent();
}
if (st.getUnivRoll() != num)
{
file1.write((char *)&st, sizeof(Student));
}
}
file1.close();
stu.close();
remove("StudentDetails.dat");
rename("temp.dat", "StudentDetails.dat");
cout << "\t\t\t\t\t\tRECORD DELETED SUCCESSFULLY\n";
doTaskOnceAgain("\t\t\t\t\t\tDO YOU WANT TO DELETE ANOTHER RECORD?(Y/N): ", deleteStudent);
}
void updateStudent()
{
system("cls");
bool found = false;
int num;
cout << "Enter Student Id: ";
cin >> num;
stu.open("StudentDetails.dat", ios::in | ios::out);
while (stu.read((char *)&st, sizeof(Student)) && found == false)
{
if (st.getUnivRoll() == num)
{
cout << "\n";
st.displayStudent();
cout << "\n";
cout << "\t\t\t\t\t\tENTER NEW DETAILS\n\n\n";
st.createStudent();
int pos = -1 * sizeof(Student);
stu.seekp(pos, ios::cur);
stu.write((char *)&st, sizeof(Student));
cout << "\t\t\t\t\t\tRECORD UPDATED SUCCESSFULLY\n\n";
found = true;
}
}
stu.close();
if (found == false)
{
cout << "\t\t\t\t\t\tRECORD NOT FOUND!!\n\n";
}
doTaskOnceAgain("\t\t\t\t\t\tDO YOU WANT TO UPDATE ANOTHER RECORD?(Y/N):", updateStudent);
}
void displayStudents()
{
system("cls");
stu.open("StudentDetails.dat", ios::in);
cout << setw(78) << "**************************\n";
cout << cntr << "\tSTUDENT RECORDS\n";
cout << setw(78) << "**************************\n";
cout << "\n";
cout << "\t\t\t--------------------------------------------------------------------------------------------\n";
cout << setw(38) << "Student Id" << setw(15) << "Name" << setw(20) << "Semester" << setw(15) << "Book Id" << setw(20) << "Issue Date"
<< "\n";
cout << "\t\t\t--------------------------------------------------------------------------------------------\n";
while (stu.read((char *)&st, sizeof(Student)))
{
st.showStudent();
cout << "\t\t\t--------------------------------------------------------------------------------------------\n";
}
cout<<"\n\n";
stu.close();
}
//*****************************************************************************************************************
// FUNCTIONS TO ISSUE/RETURN BOOKS
//*****************************************************************************************************************
void issueBook()
{
system("cls");
int num, bNum;
bool found = false, bFound = false;
cout << "\t\t\t\t\t\tISSUE BOOK\n";
cout << "Enter Student Id: ";
cin >> num;
file.open("BookDetails.dat", ios::in | ios::out);
stu.open("StudentDetails.dat", ios::in | ios::out);
while (stu.read((char *)&st, sizeof(Student)) && found == false)
{
if (st.getUnivRoll() == num)
{
found = true;
st.displayStudent();
if (st.getBooksIssued() == 0)
{
cout << "Enter Book Id: ";
cin >> bNum;
while (file.read((char *)&b, sizeof(Books)) && bFound == false)
{
if (b.getBookId() == bNum)
{
b.displayBook();
bFound = true;
st.addBooks();
st.setBookid(bNum);
int pos = -1 * sizeof(st);
stu.seekp(pos, ios::cur);
stu.write((char *)&st, sizeof(Student));
cout << "\t\t\t\t\t\tBOOK ISSUED\n\n\n";
}
}
if (bFound == false)
{
cout << "\t\t\t\t\t\tBOOK RECORD NOT FOUND\n";
}
}
else
{
cout << "\t\t\t\t\t\tYOU HAVE NOT RETUREND THE PREVIOUS BOOK\n";
}
}
}
if (found == false)
{
cout << "\t\t\t\t\t\tSTUDENT RECORD NOT FOUND\n";
}
file.close();
stu.close();
}
bool checkReturn()
{
time_t now = time(0);
tm *ltm = localtime(&now);
int month = st.getCurrMonth();
int year = st.getCurrYear();
int sysMonth = 1 + ltm->tm_mon;
int sysYear = 1900 + ltm->tm_year;
if (sysMonth >= month + 1 || sysYear >= year + 1)
{
return false;
}
else
{
return true;
}
}
void collectFine()
{
int amount = 0, remAmount = 500;
cout << "\t\t\t\t\t\t*******************************\n";
cout << "\t\t\t\t\t\t\tFINE COLLECTION \n";
cout << "\t\t\t\t\t\t*******************************\n";
do
{
cout << "Amount to deposite: " << remAmount << "\n";
cout << "Deposite Amount: ";
cin >> amount;
cout << "\n";
remAmount = remAmount - amount;
if (remAmount == 0)
{
cout << "\t\t\t\t\t\tFINE DEPOSITED SUCCESSFULLY\n";
}
else if (remAmount > 0)
{
cout << "\nRemaning Amount: " << remAmount << "\n";
cout << "Please deposite the remaining amount\n";
}
} while (remAmount != 0);
}
void returnBook()
{
system("cls");
int fine, bNum, num;
bool found = false, bFound = false;
cout << cntr << "RETURN BOOK\n";
cout << "Enter Student Id: ";
cin >> num;
file.open("BookDetails.dat", ios::in | ios::out);
stu.open("StudentDetails.dat", ios::in | ios::out);
while (stu.read((char *)&st, sizeof(Student)) && found == false)
{
if (st.getUnivRoll() == num)
{
found = true;
if (st.getBooksIssued() == 1)
{
while (file.read((char *)&b, sizeof(Books)) && bFound == false)
{
if (st.getStudentBooks() == b.getBookId())
{
b.displayBook();
bFound = true;
if (checkReturn())
{
cout << "\t\t\t\t\t\tYOU ARE RETURNING THE BOOK AFTER THE DUE DATE\n";
cout << "\t\t\t\t\t\tFINE: RS. 500\n\n";
cout << "\t\t\t\t\tPLEASE DEPOSITE THE AMOUNT AT THE FRONT DESK BEFORE"
<< "RETURNING THE BOOK\n\n";
collectFine();
st.resetBooks();
st.resetDate();
int pos = -1 * sizeof(st);
stu.seekp(pos, ios::cur);
stu.write((char *)&st, sizeof(Student));
cout << "\n\t\t\t\t\t\t\tBOOK RETURNED\n\n";
}
else
{
st.resetBooks();
st.resetDate();
int pos = -1 * sizeof(st);
stu.seekp(pos, ios::cur);
stu.write((char *)&st, sizeof(Student));
cout << "\t\t\t\t\t\tBOOK RETURNED\n\n";
}
}
}
if (bFound == false)
{
cout << "\t\t\t\t\t\tBOOK RECORD NOT FOUND\n";
}
}
else
{
cout << "\t\t\t\t\t\tNO ISSUED BOOKS FOUND\n";
cout << "\t\t\t\t\t\tPLEASE CHECK AGAIN\n";
}
}
}
if (found == false)
{
cout << "\t\t\t\t\t\tSTUDENT RECORD NOT FOUND\n";
}
file.close();
stu.close();
}
//*****************************************************************************************************************
// PASSWORD MANAGEMENT FUNCTIONS
//*****************************************************************************************************************
void adminPass()
{
system("cls");
string defaultPass = "admin", inputPass;
ifstream inf("PASSWORD.txt");
inf >> defaultPass;
inf.close();
cout << "\t\t\t\t\tENTER PASSWORD TO ACCESS ADMIN MENU\n\n";
cout << "Password: ";
cin >> inputPass;
if (inputPass == defaultPass)
{
system("cls");
adminMenu();
}
else
{
cout << "\t\t\t\t\tWRONG PASSWORD\n";
cout << "\t\t\t\t\tRETURNING TO MAIN MENU\n\n";
return;
}
}
void changePass()
{
system("cls");
string oldPass, newPass, defaultPass;
cout << "Current Password: ";
cin >> oldPass;
ifstream inf;
inf.open("PASSWORD.txt", fstream::out | fstream::in);
getline(inf, defaultPass);
if (oldPass == defaultPass)
{
cout << "\n\n\t\t\t\tNOTE:- Password should not include spaces\n\n";
cout << "New Pass: ";
cin >> newPass;
if (newPass == oldPass)
{
cout << "\t\t\t\t\tNEW PASSWORD CANNOT BE SAME AS OLD PASSWORD\n\n";
cout << "\t\t\t\t\tRETURNING BACK TO ADMIN MENU\n\n";
return;
}
ofstream temp("temp.txt");
temp << newPass;
temp.close();
inf.close();
remove("PASSWORD.txt");
rename("temp.txt", "PASSWORD.txt");
cout << "\t\t\t\t\tPASSWORD CHANGED SUCCESSFULLY\n\n";
return;
}
else
{
cout << "\t\t\t\t\tWRONG PASSWORD\n\n";
doTaskOnceAgain("\t\t\t\t\tTRY AGAIN?(Y/N):", changePass);
}
}
//*****************************************************************************************************************
// FUNCTION TO DISPLAY BASIC DETAILS ABOUT THE DEVLOPER
//*****************************************************************************************************************
void intro()
{
system("cls");
cout << "\t\t\t\t---------------------------------------------------------\n";
cout << "\t\t\t\t| CREATED BY : Siri Lalitha Adapa\t\t\t |\n";
cout << "\t\t\t\t| COURSE : BACHELOR OF TECHNOLOGY\t\t\t|\n";
cout << "\t\t\t\t| BRANCH : COMPUTER SCIENCE AND ENGINEERING\t\t|\n";
cout << "\t\t\t\t| UNIVERSITY : Vasireddy Venkatadhri Institute of Technology\t|\n";
cout << "\t\t\t\t|\t Nambur\t\t\t\t\t|\n";
cout << "\t\t\t\t---------------------------------------------------------\n\n\n";
}
//*****************************************************************************************************************
// MENU FUNCTIONS
//*****************************************************************************************************************
void studentsMenu()
{
system("cls");
int option;
do
{
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t\tSTUDENT MENU\n";
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t1. Add Student\n"
<< "\t\t\t\t\t2. Update Student\n"
<< "\t\t\t\t\t3. Delete Student\n"
<< "\t\t\t\t\t4. Display Student\n"
<< "\t\t\t\t\t5. Back to Admin Menu\n"
<< "\t\t\t\t\t0. Exit\n";
cin >> option;
switch (option)
{
case 0:
intro();
exit(0);
break;
case 1:
addStudent();
break;
case 2:
updateStudent();
break;
case 3:
deleteStudent();
break;
case 4:
displayStudents();
break;
case 5:
system("cls");
break;
default:
studentsMenu();
break;
}
} while (option != 5);
}
void bookMenu()
{
system("cls");
int option;
do
{
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t\tBOOK MENU\n";
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t1. Add Book\n"
<< "\t\t\t\t\t2. Update Book\n"
<< "\t\t\t\t\t3. Delete Book\n"
<< "\t\t\t\t\t4. Display Books\n"
<< "\t\t\t\t\t5. Back to Admin Menu\n"
<< "\t\t\t\t\t0. Exit\n";
cin >> option;
switch (option)
{
case 0:
intro();
exit(0);
break;
case 1:
addBook();
break;
case 2:
updateBook();
break;
case 3:
deleteBook();
break;
case 4:
displayBooks();
break;
case 5:
system("cls");
break;
default:
bookMenu();
break;
}
} while (option != 5);
}
void adminMenu()
{
system("cls");
int option;
do
{
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t\tADMIN MENU\n";
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t1. Books\n"
<< "\t\t\t\t\t2. Student\n"
<< "\t\t\t\t\t3. Change Password\n"
<< "\t\t\t\t\t4. Back To Main Menu\n"
<< "\t\t\t\t\t0. Exit\n\n\n";
cin >> option;
switch (option)
{
case 0:
intro();
exit(0);
break;
case 1:
bookMenu();
break;
case 2:
studentsMenu();
break;
case 3:
changePass();
break;
case 4:
system("cls");
break;
default:
system("cls");
adminMenu();
}
} while (option != 4);
}
void studentMenu()
{
system("cls");
int option;
do
{
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t\tSTUDENT MENU\n";
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t1. Issue Book\n"
<< "\t\t\t\t\t2. Return Book\n"
<< "\t\t\t\t\t3. Back To Main Menu\n\t\t\t\t\t0. Exit\n\n\n";
cin >> option;
switch (option)
{
case 0:
system("cls");
intro();
exit(0);
break;
case 1:
issueBook();
break;
case 2:
returnBook();
break;
case 3:
mainMenu();
break;
default:
system("cls");
studentMenu();
}
} while (option != 0);
}
void mainMenu()
{
system("cls");
cout << "\t\t\t\t----------------------------------------------\n";
cout << "\t\t\t\t| \t LIBRARY MANAGEMENT PROJECT\t |\n";
cout << "\t\t\t\t----------------------------------------------\n\n\n";
int choice;
do
{
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t\tMAIN MENU\n";
cout << "\t\t\t\t\t**************************\n";
cout << "\t\t\t\t\t1. Admin\n\t\t\t\t\t2. Student\n\t\t\t\t\t0. Exit\n\n";
cin >> choice;
switch (choice)
{
case 0:
intro();
exit(0);
break;
case 1:
adminPass();
break;
case 2:
studentMenu();
break;
default:
mainMenu();
break;
}
} while (choice != 0);
}
//Driver Code
int main()
{
system("cls");
system("color 01");
mainMenu();
return 0;
}
| 26.934372 | 137 | 0.381061 | [
"object"
] |
73b364b10651009126cfca0d7fcb9ac10657bbc9 | 25,962 | hh | C++ | sdk-remote/include/urbi/uabstractclient.hh | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 16 | 2016-05-10T05:50:58.000Z | 2021-10-05T22:16:13.000Z | sdk-remote/include/urbi/uabstractclient.hh | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 7 | 2016-09-05T10:08:33.000Z | 2019-02-13T10:51:07.000Z | sdk-remote/include/urbi/uabstractclient.hh | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 15 | 2015-01-28T20:27:02.000Z | 2021-09-28T19:26:08.000Z | /*
* Copyright (C) 2004, 2006-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/uabstractclient.hh
/// \brief Definition of the URBI interface class
#ifndef URBI_UABSTRACTCLIENT_HH
# define URBI_UABSTRACTCLIENT_HH
# include <libport/cstdio>
# include <libport/sys/types.h>
# include <libport/cstring>
# include <libport/cstdlib>
# include <cstdarg>
# include <list>
# include <iostream>
# include <string>
# include <libport/compiler.hh>
# include <libport/fwd.hh>
# include <libport/lockable.hh>
# include <libport/traits.hh>
# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ubinary.hh>
# include <urbi/umessage.hh>
/**
\mainpage
This document is the autogenerated documentation for Urbi SDK Remote.
Classes of interest:
- Urbi connections: urbi::UAbstractClient, urbi::UClient, urbi::USyncClient.
- Data types: urbi::UValue, urbi::UBinary.
- UObject API: urbi::UObject, urbi::UVar.
*/
namespace urbi
{
/// Return values for the callcack functions.
/*! Each callback function, when called, must return with either URBI_CONTINUE
or URBI_REMOVE:
- URBI_CONTINUE means that the client should continue to call this callbak
function.
- URBI_REMOVE means that the client should never call this callback again.
*/
enum UCallbackAction
{
URBI_CONTINUE=0,
URBI_REMOVE
};
/// Maximum length of an URBI tag.
enum { URBI_MAX_TAG_LENGTH = 64 };
typedef unsigned int UCallbackID;
# define UINVALIDCALLBACKID 0
/// Callback prototypes.
typedef UCallbackAction (*UCallback) (const UMessage&msg);
typedef UCallbackAction (*UCustomCallback) (void * callbackData,
const UMessage&msg);
//used internaly
class UCallbackInfo
{
public:
UCallbackInfo(UCallbackWrapper &w);
bool operator==(UCallbackID id) const;
char tag[URBI_MAX_TAG_LENGTH];
UCallbackWrapper& callback;
UCallbackID id;
};
//used internaly
class UClientStreambuf;
class LockableOstream: public std::ostream
{
public:
LockableOstream(std::streambuf* sb)
: std::ostream(sb)
{
}
mutable libport::Lockable sendBufferLock;
};
/// Interface for an Urbi wrapper object.
/*! Implementations of this interface are wrappers around the Urbi protocol.
It handles Urbi messages parsing, callback registration and various
formatting functions.
Implementations of this interface should:
- Redefine errorNotify() as a function able to notify the user of eventual
errors.
- Redfine the four mutual exclusion functions.
- Redefine effectiveSend().
- Fill recvBuffer, update recvBufferPosition and call processRecvBuffer()
when new data is available.
- Provide an execute() function in the namespace urbi, that never returns,
and that will be called after initialization.
- Call onConnection when the connection is established.
See the liburbi-cpp documentation for more informations on
how to use this class.
*/
class URBI_SDK_API UAbstractClient : public LockableOstream
{
public:
/// Connection Buffer size.
enum { URBI_BUFLEN = 128000 };
/// Standard port of Urbi server.
enum { URBI_PORT = 54000 } ;
/// Default host.
static const char* default_host();
/// Error code.
/// 0 iff no error.
/// Other values are unspecified.
typedef int error_type;
/// Create a new instance and connect to the Urbi server.
/*! Initialize sendBuffer and recvBuffer, and copy host and port.
* \param host IP address or name of the robot to connect to.
* \param port TCP port to connect to.
* \param buflen size of send and receive buffers.
* \param server whether accepts incoming connections.
* Implementations should establish the connection in their constructor.
*/
UAbstractClient(const std::string& host = default_host(),
unsigned port = URBI_PORT,
size_t buflen = URBI_BUFLEN,
bool server = false);
virtual ~UAbstractClient();
bool init() const;
/// Return current error status, or zero if no error occurred.
error_type error() const;
/*----------.
| Sending. |
`----------*/
/**
* \defgroup Sending urbiscript code.
*
* All the send functions are expected to be asynchronous by default: they
* return immediately, and
* send the data in a separate thread.
*/
//@{
/// Send an Urbi command. The syntax is similar to the printf()
/// function.
/// Passing `0' is supported as means `""', but with no warning.
ATTRIBUTE_PRINTF(2, 3)
error_type send(const char* format, ...);
/// A C++ string.
error_type send(const std::string& s);
/// Send the value without any prefix or terminator
error_type send(const UValue& v);
/// Send the remainder of the stream.
error_type send(std::istream& is);
/// Send an urbi Binary value.
error_type sendBinary(const void* data, size_t len,
const std::string& header);
/// Send binary data.
error_type sendBin(const void*, size_t len);
/// Send an Urbi header followed by binary data.
ATTRIBUTE_PRINTF(4, 5)
error_type sendBin(const void*, size_t len, const char* header, ...);
/// Lock the send buffer (for backward compatibility, will be
/// removed in future versions).
error_type startPack();
/// Unlock the send buffer (for backward compatibility, will be
/// removed in future versions).
error_type endPack();
/// Append Urbi commands to the send buffer (for backward
/// compatibility, will be removed in future versions).
/// Passing `0' is supported as means `""', but with no warning.
ATTRIBUTE_PRINTF(2, 3)
error_type pack(const char* format, ...);
/// va_list version of pack.
/// Passing `0' is supported as means `""', but with no warning.
error_type vpack(const char* format, va_list args);
/// Send urbi commands contained in a file.
/// The file "/dev/stdin" is recognized as referring to std::cin.
error_type sendFile(const std::string& f);
/// Send a command, prefixing it with a tag, and associate the
/// given callback with this tag.
ATTRIBUTE_PRINTF(3, 4)
UCallbackID sendCommand(UCallback, const char*, ...);
/// Send a command, prefixing it with a tag, and associate the
/// given callback with this tag.
ATTRIBUTE_PRINTF(4, 5)
UCallbackID sendCommand(UCustomCallback, void *, const char*, ...);
/// Send sound data to the robot for immediate playback.
error_type sendSound(const char* device,
const USound& sound, const char* tag = 0);
/// Put a file on the robot's mass storage device.
error_type putFile(const char* localName, const char* remoteName = 0);
/// Save a buffer to a file on the robot.
error_type putFile(const void* buffer, size_t length,
const char* remoteName);
//@}
//@{
/**
* \defgroup Setting read callbacks.
*
* All those functions register function callbacks that are called on
* some events. The UClient subclass calls those callbacks synchronously
* in the main read thread, so no other callback will be called until
* the first one returns.
* The USyncClient subclass uses a separate thread per instance.
*/
/// Associate a callback function with a tag. New style.
/*!
\param callback a callback function wrapper, generated by callback()
\param tag the tag to associate the callback with
*/
UCallbackID setCallback(UCallbackWrapper& callback, const char* tag);
/// Associate a callback function with all error messages from the server
UCallbackID setErrorCallback(UCallbackWrapper& callback);
/// Associate a callback with all messages
UCallbackID setWildcardCallback(UCallbackWrapper& callback);
/// Associate a callback with local connection errors
UCallbackID setClientErrorCallback(UCallbackWrapper& callback);
/// OLD-style callbacks
UCallbackID setCallback(UCallback, const char* tag);
/// Associate a callback function with a tag, specifiing a
/// callback custom value that will be passed back to the callback
/// function.
UCallbackID setCallback(UCustomCallback, void* callbackData,
const char* tag);
//@}
//@{
/// \deprecated{ Callback to class member functions(old-style).}
template<class C>
UCallbackID
setCallback(C& ref, UCallbackAction (C::*)(const UMessage&),
const char * tag);
template<class C, class P1>
UCallbackID
setCallback(C& ref, UCallbackAction (C::*)(P1, const UMessage&),
P1, const char * tag);
template<class C, class P1, class P2>
UCallbackID
setCallback(C& ref, UCallbackAction (C::*)(P1 , P2, const UMessage&),
P1, P2, const char * tag);
template<class C, class P1, class P2, class P3>
UCallbackID
setCallback(C& ref, UCallbackAction (C::*)(P1 , P2, P3, const UMessage&),
P1, P2, P3, const char* tag);
template<class C, class P1, class P2, class P3, class P4>
UCallbackID
setCallback(C& ref, UCallbackAction(C::*)(P1 , P2, P3, P4, const UMessage&),
P1, P2, P3, P4, const char* tag);
//@}
/// Get the tag associated with a registered callback.
/// \return 1 and fill tag on success, 0 on failure.
int getAssociatedTag(UCallbackID id, char* tag);
/// Delete a callback.
/// \return 0 if no callback with this id was found, 1 otherwise.
int deleteCallback(UCallbackID id);
/// Return a identifier, for tags for instance.
std::string fresh();
/// Fill tag with a unique tag for this client.
/// Obsolete, use fresh() instead.
ATTRIBUTE_DEPRECATED
void makeUniqueTag(char* tag);
/// Pass the given UMessage to all registered callbacks with the
/// corresponding tag, as if it were comming from the Urbi server.
virtual void notifyCallbacks(const UMessage& msg);
/// Notify of an error.
ATTRIBUTE_PRINTF(2, 3)
virtual void printf(const char* format, ...) = 0;
/// Get time in milliseconds since an unspecified but constant
/// reference time.
virtual unsigned int getCurrentTime() const = 0;
/// Active KeepAlive functionality
/// Sends an Urbi message at specified interval, if no anwser is received
/// close the connection and notify 'URBI_ERROR_CONNECTION_TIMEOUT'.
///
/// \param pingInterval interval between ping messages
/// in milliseconds, 0 to disable.
/// \param pongTimeout timeout in milliseconds to wait answer.
virtual void setKeepAliveCheck(unsigned pingInterval,
unsigned pongTimeout) = 0;
/// Return the server name or IP address.
const std::string& getServerName() const;
/// Return the server port.
unsigned getServerPort() const;
/// Called each time new data is available in recvBuffer.
void processRecvBuffer();
private:
/// New binary data is available.
/// \return true if there is still data to process.
bool process_recv_buffer_binary_();
/// New text data is available.
/// \return true if there is still data to process.
bool process_recv_buffer_text_();
public:
/// This, as a stream.
std::ostream& stream_get();
/// dummy tag for client error callback.
static const char* CLIENTERROR_TAG;
/** Lock on send buffer. Can be locked by the user when performing an
* atomic operation in multiple calls.
*/
/* Inherited from LockableOstream libport::Lockable sendBufferLock;*/
protected:
/// Must be called by subclasses when the connection is established.
void onConnection();
/// Executed when closing connection.
virtual error_type onClose();
bool closed_;
/// Queue data for sending, returns zero on success, nonzero on failure.
virtual error_type effectiveSend(const void* buffer, size_t size) = 0;
/// Direct forward the call to effectiveSend.
/// Allows to insert debugging information.
error_type effective_send(const void* buffer, size_t size);
/// Bounce to effective_send() using strlen.
error_type effective_send(const char* buffer);
/// Bounce to effective_send() using c_str().
error_type effective_send(const std::string& buffer);
libport::Lockable listLock;
/// Add a callback to the list.
UCallbackID addCallback(const char* tag, UCallbackWrapper& w);
/// Generate a client error message and notify callbacks.
/// \param msg an optional string describing the error.
/// The possible prefix "!!! " is skipped if present.
/// \param code an optional system error code on which strerror is called
void clientError(std::string msg, int code = 0);
void clientError(const char* msg = 0, int code = 0);
/// Host name.
std::string host_;
/// Urbi Port.
unsigned port_;
/// Server mode
bool server_;
/// Buffer sizes.
size_t sendBufSize;
size_t recvBufSize;
/// System calls return value storage.
/// 0 iff no error.
/// Other values are unspecified.
error_type rc;
/// Reception buffer.
char* recvBuffer;
/// Current position in reception buffer.
size_t recvBufferPosition;
/// Temporary buffer for send data.
char* sendBuffer;
/// \name Kernel Version.
/// \{
public:
/// Kernel version string.
/// Call waitForKernelVersion to make sure it is defined (beware
/// that there are two signatures, one for UAbstractClient,
/// another for USyncClient).
const std::string& kernelVersion() const;
/// Major kernel version. Dies if unknown yet.
int kernelMajor() const;
/// Minor kernel version. Dies if unknown yet.
int kernelMinor() const;
/** Block until kernel version is available or an error occurrs.
* Message processing must not depend on this thread.
*/
virtual void waitForKernelVersion() const = 0;
protected:
/// The full kernel version as answered by the server.
/// Empty if not available yet.
std::string kernelVersion_;
/// The major version. -1 if not yet available.
int kernelMajor_;
/// The minor version. -1 if not yet available.
int kernelMinor_;
/// A callback, installed by onConnection(), that reads an answer
/// from the server to know if it's k1 or k2.
virtual UCallbackAction setVersion(const UMessage& msg);
/// \}
public:
const std::string& connectionID() const;
protected:
std::string connectionID_;
/// A callback, installed by setVersion, that computes
/// connectionID_.
virtual UCallbackAction setConnectionID(const UMessage& msg);
private:
/// Bin object for this command.
binaries_type bins;
/// Empty bins.
void bins_clear();
/// Temporary storage of binary data.
void* binaryBuffer;
/// Current position in binaryBuffer.
size_t binaryBufferPosition;
/// Size of binaryBuffer.
size_t binaryBufferLength;
/// Position of parse in recvBuffer.
size_t parsePosition;
/// True if preparsing is in a string.
bool inString;
/// Current depth of bracket.
size_t nBracket;
/// Start of command, after [ts:tag] header.
char* currentCommand;
/// Currently parsing binary
bool binaryMode;
/// Parsing a system message
bool system;
/// Position of end of header.
size_t endOfHeaderPosition;
char currentTag[URBI_MAX_TAG_LENGTH];
int currentTimestamp;
protected:
/// Client fully created
bool init_;
public:
int getCurrentTimestamp() const;
private:
typedef std::list<UCallbackInfo> callbacks_type;
callbacks_type callbacks_;
/// A counter, used to generate unique (tag) identifiers.
unsigned int counter_;
/// Ourself as a stream.
/// It looks useless, agreed, but VC++ wants it.
std::ostream* stream_;
friend class UClientStreambuf;
};
/// Wrapper around a callback function. Use callback() to create them.
class UCallbackWrapper
{
public:
virtual UCallbackAction operator ()(const UMessage&)=0;
virtual ~UCallbackWrapper() {}
};
///@{
/// \internal
class UCallbackWrapperF
: public UCallbackWrapper
{
UCallback cb;
public:
UCallbackWrapperF(UCallback cb) : cb(cb) {}
virtual UCallbackAction operator ()(const UMessage& msg)
{
return cb(msg);
}
virtual ~UCallbackWrapperF() {}
};
class UCallbackWrapperCF
: public UCallbackWrapper
{
UCustomCallback cb;
void* cbData;
public:
UCallbackWrapperCF(UCustomCallback cb, void* cbData)
: cb(cb), cbData(cbData)
{}
virtual UCallbackAction operator ()(const UMessage& msg)
{
return cb(cbData, msg);
}
virtual ~UCallbackWrapperCF() {}
};
template<class C>
class UCallbackWrapper0 :
public UCallbackWrapper
{
C& instance;
UCallbackAction (C::*func)(const UMessage&);
public:
UCallbackWrapper0(C& instance, UCallbackAction (C::*func)(const UMessage&))
: instance(instance), func(func)
{}
virtual UCallbackAction operator ()(const UMessage& msg)
{
return (instance.*func)(msg);
}
virtual ~UCallbackWrapper0() {}
};
template<class C, class P1>
class UCallbackWrapper1
: public UCallbackWrapper
{
C& instance;
UCallbackAction (C::*funcPtr)(P1, const UMessage&);
typename libport::traits::remove_reference<P1>::type p1;
public:
UCallbackWrapper1(C& instance,
UCallbackAction (C::*func)(P1, const UMessage&), P1 p1)
: instance(instance), funcPtr(func), p1(p1)
{}
virtual UCallbackAction operator ()(const UMessage& msg)
{
return (instance.*funcPtr)(p1, msg);
}
virtual ~UCallbackWrapper1()
{}
};
template<class C, class P1, class P2>
class UCallbackWrapper2 : public UCallbackWrapper
{
C& instance;
UCallbackAction (C::*func)(P1, P2, const UMessage&);
typename libport::traits::remove_reference<P1>::type p1;
typename libport::traits::remove_reference<P2>::type p2;
public:
UCallbackWrapper2(
C& instance, UCallbackAction (C::*func)(P1, P2, const UMessage&),
P1 p1, P2 p2)
: instance(instance), func(func), p1(p1), p2(p2)
{}
virtual UCallbackAction operator ()(const UMessage& msg)
{
return (instance.*func)(p1, p2, msg);
}
virtual ~UCallbackWrapper2()
{}
};
template<class C, class P1, class P2, class P3>
class UCallbackWrapper3 : public UCallbackWrapper
{
C& instance;
UCallbackAction (C::*func)(P1, P2, P3, const UMessage&);
typename libport::traits::remove_reference<P1>::type p1;
typename libport::traits::remove_reference<P2>::type p2;
typename libport::traits::remove_reference<P3>::type p3;
public:
UCallbackWrapper3(
C& instance, UCallbackAction (C::*func)(P1, P2, P3, const UMessage&),
P1 p1, P2 p2, P3 p3)
: instance(instance), func(func), p1(p1), p2(p2), p3(p3)
{}
virtual UCallbackAction operator ()(const UMessage& msg)
{
return (instance.*func)(p1, p2, p3, msg);
}
virtual ~UCallbackWrapper3()
{}
};
template<class C, class P1, class P2, class P3, class P4>
class UCallbackWrapper4 : public UCallbackWrapper
{
C& instance;
UCallbackAction (C::*func)(P1, P2, P3, P4, const UMessage&);
typename libport::traits::remove_reference<P1>::type p1;
typename libport::traits::remove_reference<P2>::type p2;
typename libport::traits::remove_reference<P3>::type p3;
typename libport::traits::remove_reference<P4>::type p4;
public:
UCallbackWrapper4(
C& instance, UCallbackAction(C::*func)(P1, P2, P3, P4, const UMessage&),
P1 p1, P2 p2, P3 p3, P4 p4)
: instance(instance), func(func), p1(p1), p2(p2), p3(p3), p4(p4)
{}
virtual UCallbackAction operator ()(const UMessage& msg)
{
return (instance.*func)(p1, p2, p3, p4, msg);
}
virtual ~UCallbackWrapper4()
{}
};
//@}
//overloaded callback generators
//@{
/// Generate a callback wrapper used by UAbstractClient::setCallback().
/*!
You can pass to this function:
- A function pointer, with signature UCallbackAction(*)(const UMessage&)
\code setCallback(callback(&myFunction), "tag"); \endcode
- A reference to a class instance and a pointer to a member function.
\code setCallback(callback(*this, &MyClass::myMemberFunction)); \endcode
*/
inline UCallbackWrapper& callback(UCallback cb)
{
return *new UCallbackWrapperF(cb);
}
inline UCallbackWrapper& callback(UCustomCallback cb, void* data)
{
return *new UCallbackWrapperCF(cb, data);
}
template<class C> UCallbackWrapper&
callback(C& ref, UCallbackAction (C::*func)(const UMessage&))
{
return *new UCallbackWrapper0<C>(ref, func);
}
template<class C, class P1> UCallbackWrapper&
callback(C& ref, UCallbackAction (C::*func)(P1, const UMessage&), P1 p1)
{
return *new UCallbackWrapper1<C, P1>(ref, func, p1);
}
template<class C, class P1, class P2> UCallbackWrapper&
callback(C& ref, UCallbackAction (C::*func)(P1, P2, const UMessage&),
P1 p1, P2 p2)
{
return *new UCallbackWrapper2<C, P1, P2>(ref, func, p1, p2);
}
template<class C, class P1, class P2, class P3> UCallbackWrapper&
callback(C& ref, UCallbackAction (C::*func)(P1, P2, P3, const UMessage&),
P1 p1, P2 p2, P3 p3)
{
return *new UCallbackWrapper3<C, P1, P2, P3>(ref, func, p1, p2, p3);
}
template<class C, class P1, class P2, class P3, class P4> UCallbackWrapper&
callback(C& ref, UCallbackAction (C::*func)(P1, P2, P3, P4, const UMessage&),
P1 p1, P2 p2, P3 p3, P4 p4)
{
return *new UCallbackWrapper4<C, P1, P2, P3, P4>(ref, func, p1, p2, p3, p4);
}
//@}
//old-style addCallback, deprecated
template<class C>
UCallbackID
UAbstractClient::setCallback(C& ref,
UCallbackAction (C::*func)(const UMessage&),
const char* tag)
{
return addCallback(tag,*new UCallbackWrapper0<C>(ref, func));
}
template<class C, class P1>
UCallbackID
UAbstractClient::setCallback(C& ref,
UCallbackAction (C::*func)(P1 , const UMessage&),
P1 p1, const char* tag)
{
return addCallback(tag, *new UCallbackWrapper1<C, P1>(ref, func, p1));
}
template<class C, class P1, class P2>
UCallbackID
UAbstractClient::setCallback(
C& ref, UCallbackAction (C::*func)(P1, P2, const UMessage&),
P1 p1, P2 p2, const char* tag)
{
return addCallback(tag, *new UCallbackWrapper2<C, P1, P2>
(ref, func, p1, p2));
}
template<class C, class P1, class P2, class P3>
UCallbackID
UAbstractClient::setCallback(
C& ref, UCallbackAction (C::*func)(P1, P2, P3, const UMessage&),
P1 p1 , P2 p2, P3 p3, const char* tag)
{
return addCallback(tag, *new UCallbackWrapper3<C, P1, P2, P3>
(ref, func, p1, p2, p3));
}
template<class C, class P1, class P2, class P3, class P4>
UCallbackID
UAbstractClient::setCallback(
C& ref, UCallbackAction (C::*func)(P1, P2, P3, P4, const UMessage&),
P1 p1, P2 p2, P3 p3, P4 p4, const char* tag)
{
return addCallback(tag, *new UCallbackWrapper4<C, P1, P2, P3, P4>
(ref, func, p1, p2, p3, p4));
}
/// Conveniant macro for easy insertion of Urbi code in C
/**
With this macro, the following code is enough to send a simple
command to a robot using Urbi:
int main()
{
urbi::connect("robot");
URBI(headPan.val'n = 0 time:1000 |
headTilt.val'n = 0 time:1000,
speaker.play("test.wav"),
echo "test";
);
}
The following construct is also valid:
URBI(()) << "headPan.val="<<12<<";";
*/
# ifndef URBI
# define URBI(A) \
::urbi::unarmorAndSend(#A)
# endif
static const char semicolon = ';';
static const char pipe = '|';
static const char parallel = '&';
static const char comma = ',';
/// Must be called at the last line of your main() function.
URBI_SDK_API
void execute(void);
/// Terminate your Urbi program.
ATTRIBUTE_NORETURN
URBI_SDK_API
void exit(int code);
/// Create a new UClient object
URBI_SDK_API
UClient& connect(const std::string& host);
/// Destroy an UClient object
/// Be careful: don't use client after called this function
URBI_SDK_API
void disconnect(UClient &client);
/*-----------------.
| Default client. |
`-----------------*/
/// Return the first UClient created by the program.
URBI_SDK_API
UClient* getDefaultClient();
/// Same as getDefaultClient(), but as a reference.
URBI_SDK_API
UClient& get_default_client();
/// Redefine the default client.
URBI_SDK_API
void setDefaultClient(UClient* cl);
URBI_SDK_API
std::string getClientConnectionID(const UAbstractClient* cli);
# ifndef DISABLE_IOSTREAM
/// Send a possibly armored string to the default client
URBI_SDK_API
std::ostream&
unarmorAndSend(const char* str,
UAbstractClient* c = (UAbstractClient*)getDefaultClient());
# endif
URBI_SDK_API
extern UClient* defaultClient;
/// Return a stream for error, preferrably the one the defaultClient.
URBI_SDK_API
std::ostream& default_stream();
} // namespace urbi
# include <urbi/uabstractclient.hxx>
#endif // URBI_UABSTRACTCLIENT_HH
| 30.223516 | 80 | 0.657384 | [
"object"
] |
73b8e9eff1536e7a0529d4411c75ada03fb4d6b4 | 46,301 | cpp | C++ | src/pcbeditor/packageeditor.cpp | schdesign/board-builder | 9b4f56e38dbf6e8ffabab5fcdb9fda834fd00226 | [
"MIT"
] | null | null | null | src/pcbeditor/packageeditor.cpp | schdesign/board-builder | 9b4f56e38dbf6e8ffabab5fcdb9fda834fd00226 | [
"MIT"
] | null | null | null | src/pcbeditor/packageeditor.cpp | schdesign/board-builder | 9b4f56e38dbf6e8ffabab5fcdb9fda834fd00226 | [
"MIT"
] | null | null | null | // packageeditor.cpp
// Copyright (C) 2018 Alexander Karpeko
#include "exceptiondata.h"
#include "function.h"
#include "packageeditor.h"
#include "ui_packageeditor.h"
#include <QFile>
#include <QFileDialog>
#include <QIODevice>
#include <QJsonArray>
#include <QJsonDocument>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QMessageBox>
#include <QPainter>
#include <QPushButton>
#include <QRadioButton>
#include <QSvgGenerator>
#include <QTextStream>
#include <QVBoxLayout>
PackageEditor::PackageEditor(QWidget *parent) : QMainWindow(parent)
{
setupUi(this);
connect(actionNewFile, SIGNAL(triggered()), this, SLOT(newFile()));
connect(actionOpenFile, SIGNAL(triggered()), this, SLOT(openFile()));
connect(actionSaveFile, SIGNAL(triggered()), this, SLOT(saveFile()));
connect(actionCloseFile, SIGNAL(triggered()), this, SLOT(closeFile()));
connect(actionQuit, SIGNAL(triggered()), this, SLOT(hide()));
connect(actionNewPackage, SIGNAL(triggered()), this, SLOT(newPackage()));
connect(actionAbout, SIGNAL(triggered()), this, SLOT(about()));
QCheckBox *tmpCheckBox[checkBoxes] =
{
borderCheckBox, packageCheckBox, padsCheckBox
};
std::copy(tmpCheckBox, tmpCheckBox + checkBoxes, checkBox);
for (int i = 0; i < checkBoxes; i++)
connect(checkBox[i], &QCheckBox::clicked, [=] () { selectCheckBox(i); });
QComboBox *tmpComboBox[comboBoxes] =
{
addPadOrientationComboBox, addPadTypeComboBox, addPadsOrientationComboBox,
addPadsTypeComboBox, padType0ShapeComboBox, padType1ShapeComboBox,
padType2ShapeComboBox, selectedPadOrientationComboBox,
selectedPadTypeComboBox, typeComboBox
};
std::copy(tmpComboBox, tmpComboBox + comboBoxes, comboBox);
for (int i = 0; i < comboBoxes; i++)
connect(comboBox[i], QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
[=] (const QString &text) { selectComboBox(i, text); });
QLineEdit *tmpLineEdit[lineEdits] =
{
addEllipseHLineEdit, addEllipseWLineEdit, addEllipseXLineEdit, addEllipseYLineEdit,
addLineX1LineEdit, addLineX2LineEdit, addLineY1LineEdit, addLineY2LineEdit,
addPadNumberLineEdit, addPadXLineEdit, addPadYLineEdit, addPadsDxLineEdit,
addPadsDyLineEdit, addPadsFirstLineEdit, addPadsFirstXLineEdit, addPadsFirstYLineEdit,
addPadsLastLineEdit, borderBottomLineEdit, borderLeftXLineEdit, borderRightXLineEdit,
borderTopYLineEdit, deleteEllipsesFirstLineEdit, deleteEllipsesLastLineEdit,
deleteLinesFirstLineEdit, deleteLinesLastLineEdit, deletePadsFirstLineEdit,
deletePadsLastLineEdit, ellipsesLineEdit, gridLineEdit, linesLineEdit, nameLineEdit,
padType0LineEdit1, padType0LineEdit2, padType0LineEdit3, padType0LineEdit4,
padType1LineEdit1, padType1LineEdit2, padType1LineEdit3, padType1LineEdit4,
padType2LineEdit1, padType2LineEdit2, padType2LineEdit3, padType2LineEdit4,
padsLineEdit, selectedEllipseHLineEdit, selectedEllipseWLineEdit,
selectedEllipseXLineEdit, selectedEllipseYLineEdit, selectedLineX1LineEdit,
selectedLineX2LineEdit, selectedLineY1LineEdit, selectedLineY2LineEdit,
selectedPadNumberLineEdit, selectedPadXLineEdit, selectedPadYLineEdit
};
std::copy(tmpLineEdit, tmpLineEdit + lineEdits, lineEdit);
QRadioButton *tmpRadioButton[radioButtons] =
{
addEllipseRadioButton, addLineRadioButton, addPadRadioButton, addPadsRadioButton,
borderRadioButton, deleteEllipsesRadioButton, deleteLinesRadioButton,
deletePadsRadioButton, nameRadioButton, padTypesRadioButton, readOnlyModeRadioButton,
selectedEllipseRadioButton, selectedLineRadioButton, selectedPadRadioButton,
typeRadioButton
};
std::copy(tmpRadioButton, tmpRadioButton + radioButtons, radioButton);
for (int i = 0; i < radioButtons; i++)
connect(radioButton[i], &QRadioButton::clicked, [=] () { selectRadioButton(i); });
QPushButton *tmpPushButton[pushButtons] =
{
cancelPushButton, centerPushButton, decGridPushButton,
incGridPushButton, updatePushButton
};
std::copy(tmpPushButton, tmpPushButton + pushButtons, pushButton);
for (int i = 0; i < pushButtons; i++)
connect(pushButton[i], &QPushButton::clicked, [=] () { selectPushButton(i); });
/*
QToolButton *tmpToolButton[toolButtons] =
{
createGroupsButton, decreaseStepButton, deleteButton, deleteJunctionButton,
deletePolygonButton, deleteNetSegmentsButton, deleteSegmentButton, enumerateButton,
fillPolygonButton, increaseStepButton, meterButton, moveButton,
moveGroupButton, moveDownButton, moveLeftButton, moveRightButton,
moveUpButton, placeElementsButton, placeInductorButton, placeInductor2Button,
placeJunctionButton, placeLineButton, placeNoConnectionButton, placeNpnTransistorButton,
placePnpTransistorButton, placePolygonButton, placePowerButton, placeQuartzButton,
placeSegmentButton, placeShottkyButton, placeSwitchButton, placeZenerButton,
routeTracksButton, segmentNetsButton, selectButton, setValueButton,
showGroundNetsButton, tableRouteButton, turnToLeftButton, turnToRightButton,
updateNetsButton, waveRouteButton, zoomInButton, zoomOutButton
};
std::copy(tmpToolButton, tmpToolButton + toolButtons, toolButton);
for (int i = 0; i < toolButtons; i++)
connect(toolButton[i], &QToolButton::clicked, [=] () { selectToolButton(i); });
*/
QLineEdit *tmpPadTypeLineEdit[maxPadTypes][maxPadParams] =
{
{ padType0LineEdit1, padType0LineEdit2, padType0LineEdit3, padType0LineEdit4 },
{ padType1LineEdit1, padType1LineEdit2, padType1LineEdit3, padType1LineEdit4 },
{ padType2LineEdit1, padType2LineEdit2, padType2LineEdit3, padType2LineEdit4 }
};
for (int i = 0; i < maxPadTypes; i++)
for (int j = 0; j < maxPadParams; j++)
padTypeLineEdit[i][j] = tmpPadTypeLineEdit[i][j];
QComboBox *tmpPadTypeShapeComboBox[maxPadTypes] =
{
padType0ShapeComboBox, padType1ShapeComboBox, padType2ShapeComboBox
};
std::copy(tmpPadTypeShapeComboBox, tmpPadTypeShapeComboBox + maxPadTypes,
padTypeShapeComboBox);
padType0Label3->hide();
padType0Label4->hide();
padType1Label3->hide();
padType1Label4->hide();
padType2Label3->hide();
padType2Label4->hide();
padType0LineEdit3->hide();
padType0LineEdit4->hide();
padType1LineEdit3->hide();
padType1LineEdit4->hide();
padType2LineEdit3->hide();
padType2LineEdit4->hide();
package.clear();
tmpPackage.clear();
package.type = "SMD";
QString str;
//command = SELECT;
//previousCommand = command;
//mousePoint = QPoint(0, 0);
//step = gridStep;
gridNumber = 6; // 250 um in grid step
scale = double(gridStep) / grid[gridNumber];
gridLineEdit->setText(str.setNum(grid[gridNumber]));
//space = package.defaultPolygonSpace;
//spaceLineEdit->setText(str.setNum(space));
//width = package.defaultLineWidth;
//widthLineEdit->setText(str.setNum(width));
dx = gridX;
dy = gridY;
centerX = grid[gridNumber] * ((gridWidth / gridStep - 1) / 2);
centerY = grid[gridNumber] * ((gridHeight / gridStep - 1) / 2);
//maxXLineEdit->setText(str.setNum(maxX));
//maxYLineEdit->setText(str.setNum(maxY));
//dxLineEdit->setText(str.setNum(dx));
//dyLineEdit->setText(str.setNum(dy));
//stepLineEdit->setText(str.setNum(step));
refX = centerX;
refY = centerY;
orientation = 0; // "Up"
updateElement();
}
void PackageEditor::about()
{
QMessageBox::information(this, tr("About Package Editor"),
tr("Package Editor\n""Copyright (C) 2018 Alexander Karpeko"));
}
/*
void PackageEditor::buttonsSetEnabled(const char *params)
{
for (int i = 0; i < maxButton; i++) {
if (params[i] == '1')
button[i]->setEnabled(true);
if (params[i] == '0')
button[i]->setEnabled(false);
}
}
*/
void PackageEditor::centerElement()
{
Border border = element.outerBorder;
if (border.leftX >= border.rightX ||
border.topY >= border.bottomY)
return;
int cx = (border.leftX + border.rightX) / 2;
int cy = (border.topY + border.bottomY) / 2;
refX += centerX - cx;
refY += centerY - cy;
int step = grid[gridNumber];
refX = step * (refX / step);
refY = step * (refY / step);
}
void PackageEditor::closeFile()
{/*
//package.clear();
actionOpenFile->setEnabled(true);
actionCloseFile->setEnabled(false);
update();
// Left, right, up, down, zoom in, zoom out
// buttonsSetEnabled("000000");*/
}
/*
void PackageEditor::keyPressEvent(QKeyEvent *event)
{
switch (command) {
case PLACE_NET_NAME:
if (package.selectedWire)
if (event->text() != QString("q"))
package.value += event->text();
else
package.addNetName(0, 0);
break;
case SET_VALUE:
if (package.selectedElement)
if (event->text() != QString("q"))
package.value += event->text();
else
package.setValue(0, 0);
break;
}
update();
}
void PackageEditor::mousePressEvent(QMouseEvent *event)
{
enum ElementOrientation {UP, RIGHT, DOWN, LEFT};
int x;
int y;
QString str;
if (event->button() == Qt::LeftButton) {
mousePoint = event->pos();
x = (1. / scale) * (gridStep * ((mousePoint.x() + gridStep / 2) / gridStep) - dx);
y = (1. / scale) * (gridStep * ((mousePoint.y() + gridStep / 2) / gridStep) - dy);
switch (command) {
case DELETE_LINE:
package.deleteLine(x, y);
break;
case METER:
meterLineEdit->setText(str.setNum(package.meter(x, y), 'f', 2));
break;
case MOVE:
package.moveElement(x, y);
break;
case MOVE_GROUP:
package.moveGroup(x, y, scale);
break;
case PLACE_LINE:
package.addLinePoint(x, y, width);
break;
// case SET_VALUE:
// package.setValue(x, y);
// break;
case TURN_TO_LEFT:
package.turnElement(x, y, LEFT);
break;
case TURN_TO_RIGHT:
package.turnElement(x, y, RIGHT);
break;
}
update();
}
if (event->button() == Qt::RightButton) {
mousePoint = event->pos();
x = (1. / scale) * (gridStep * ((mousePoint.x() + gridStep / 2) / gridStep) - dx);
y = (1. / scale) * (gridStep * ((mousePoint.y() + gridStep / 2) / gridStep) - dy);
switch (command) {
case PLACE_LINE:
package.addTrack();
break;
default:
command = SELECT;
package.selectedElement = false;
package.showMessage = false;
package.pointNumber = 0;
}
update();
}
}
*/
void PackageEditor::newFile()
{
}
void PackageEditor::newPackage()
{
package.clear();
showPackageData();
update();
}
void PackageEditor::openFile()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open pkg file"),
packageDirectory, tr("pkg files (*.pkg)"));
if (fileName.isNull()) {
QMessageBox::warning(this, tr("Error"), tr("Filename is null"));
return;
}
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return;
QByteArray array = file.readAll();
file.close();
try {
readPackages(array);
if (!packages.empty()) {
package = packages[0];
updateElement();
centerElement();
updateElement();
}
}
catch (ExceptionData &e) {
QMessageBox::warning(this, tr("Error"), e.show());
return;
}
actionOpenFile->setEnabled(false);
actionCloseFile->setEnabled(true);
update();
}
QString PackageEditor::padShape(const PadTypeParams &padTypeParams)
{
bool isDiameter = padTypeParams.diameter > 0;
bool isRectangle = padTypeParams.height > 0 && padTypeParams.width > 0;
QString text;
if (!isDiameter && isRectangle)
text = "Rectangle";
if (isDiameter && isRectangle)
text = "Rounded rectangle";
if (isDiameter && !isRectangle)
text = "Circle";
return text;
}
void PackageEditor::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QFont serifFont("Times", 10, QFont::Normal);
QFont serifFont2("Times", 12, QFont::Normal);
painter.fillRect(gridX - gridStep, gridY - gridStep,
gridWidth + gridStep, gridHeight + gridStep,
QColor(255, 255, 255, 255));
painter.setPen(Qt::black);
painter.setFont(serifFont);
//if (showGridCheckBox->isChecked()) {
for (int i = 0; i < gridWidth / gridStep; i++)
for (int j = 0; j < gridHeight / gridStep; j++)
painter.drawPoint(gridX + gridStep * i, gridY + gridStep * j);
//}
painter.translate(dx, dy);
if (layers.draw & (1 << BORDER_LAYER)) {
painter.setPen(layers.color[BORDER_LAYER]);
int x = scale * element.border.leftX;
int y = scale * element.border.topY;
int w = scale * (element.border.rightX - element.border.leftX);
int h = scale * (element.border.bottomY - element.border.topY);
painter.drawRect(x, y, w, h);
}
ElementDrawingOptions options;
options.fillPads = true;
options.scale = scale;
options.fontSize = 0;
options.space = 0;
element.draw(painter, layers, options);
}
void PackageEditor::readPackages(const QByteArray &byteArray)
{
QJsonParseError error;
QString str;
QJsonDocument document(QJsonDocument::fromJson(byteArray, &error));
if (document.isNull())
throw ExceptionData("Packages file read error: " + error.errorString() +
", offset: " + str.setNum(error.offset));
QJsonObject object = document.object();
if (object["object"].toString() != "packages")
throw ExceptionData("File is not a packages file");
QJsonArray packageArray(object["packages"].toArray());
for (auto p : packageArray) {
Package package(p);
packages.push_back(package);
}
}
void PackageEditor::saveFile()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save pkg file"),
packageDirectory, tr("pkg files (*.pkg)"));
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
return;
QJsonArray packagesArray;
packagesArray.append(package.toJson());
QJsonObject packages
{
{"object", "packages"},
{"packages", packagesArray}
};
QJsonDocument document(packages);
QByteArray array(document.toJson());
file.write(array);
file.close();
}
void PackageEditor::selectCheckBox(int number)
{
bool state = checkBox[number]->isChecked();
switch (number) {
case SHOW_BORDER:
setRadioButton(borderRadioButton, state);
showLayer(BORDER_LAYER, state);
break;
case SHOW_PACKAGE:
setRadioButton(addEllipseRadioButton, state);
setRadioButton(addLineRadioButton, state);
setRadioButton(deleteEllipsesRadioButton, state);
setRadioButton(deleteLinesRadioButton, state);
setRadioButton(selectedEllipseRadioButton, state);
setRadioButton(selectedLineRadioButton, state);
showLayer(TOP_PACKAGE_LAYER, state);
break;
case SHOW_PADS:
setRadioButton(addPadRadioButton, state);
setRadioButton(addPadsRadioButton, state);
setRadioButton(deletePadsRadioButton, state);
setRadioButton(padTypesRadioButton, state);
setRadioButton(selectedPadRadioButton, state);
showLayer(TOP_PAD_LAYER, state);
break;
}
update();
}
void PackageEditor::showLayer(int number, bool state)
{
if (state)
layers.draw |= (1 << number);
else
layers.draw &= ~(1 << number);
}
void PackageEditor::selectComboBox(int number, const QString &text)
{
constexpr int padTypeShapeComboBoxNumbers[maxPadTypes] =
{
PAD_TYPE_0_SHAPE, PAD_TYPE_1_SHAPE, PAD_TYPE_2_SHAPE
};
switch (number) {
case PAD_TYPE_0_SHAPE:
case PAD_TYPE_1_SHAPE:
case PAD_TYPE_2_SHAPE:
selectPadTypeComboBox(number, text);
break;
case PACKAGE_TYPE:
if (text == "SMD" || text == "DIP") {
tmpPackage.type = text;
for (int i = 0; i < maxPadTypes; i++) {
QString text2 = padTypeShapeComboBox[i]->currentText();
selectPadTypeComboBox(padTypeShapeComboBoxNumbers[i], text2);
for (int j = 0; j < maxPadParams; j++)
padTypeLineEdit[i][j]->setReadOnly(true);
}
}
break;
}
}
void PackageEditor::selectPadTypeComboBox(int number, const QString &text)
{
QLabel *padTypeLabel[maxPadTypes][maxPadParams] =
{
{ padType0Label1, padType0Label2, padType0Label3, padType0Label4 },
{ padType1Label1, padType1Label2, padType1Label3, padType1Label4 },
{ padType2Label1, padType2Label2, padType2Label3, padType2Label4 }
};
bool isDip = (tmpPackage.type == "DIP") ||
(package.type == "DIP" && tmpPackage.type != "SMD");
int t = -1; // padType
switch (number) {
case PAD_TYPE_0_SHAPE:
t = 0;
case PAD_TYPE_1_SHAPE:
if (t == -1)
t = 1;
case PAD_TYPE_2_SHAPE:
if (t == -1)
t = 2;
padTypeShape[t] = text;
if (text == "Rectangle") {
setPadTypeLineEdit(padTypeLabel[t][0], "w", padTypeLineEdit[t][0], "", true);
setPadTypeLineEdit(padTypeLabel[t][1], "h", padTypeLineEdit[t][1], "", true);
if (isDip)
setPadTypeLineEdit(padTypeLabel[t][2], "d in", padTypeLineEdit[t][2], "", true);
else
setPadTypeLineEdit(padTypeLabel[t][2], "", padTypeLineEdit[t][2], "", false);
setPadTypeLineEdit(padTypeLabel[t][3], "", padTypeLineEdit[t][3], "", false);
}
if (text == "Rounded rectangle") {
setPadTypeLineEdit(padTypeLabel[t][0], "w", padTypeLineEdit[t][0], "", true);
setPadTypeLineEdit(padTypeLabel[t][1], "h", padTypeLineEdit[t][1], "", true);
setPadTypeLineEdit(padTypeLabel[t][2], "r", padTypeLineEdit[t][2], "", true);
if (isDip)
setPadTypeLineEdit(padTypeLabel[t][3], "d in", padTypeLineEdit[t][3], "", true);
else
setPadTypeLineEdit(padTypeLabel[t][3], "", padTypeLineEdit[t][3], "", false);
}
if (text == "Circle") {
setPadTypeLineEdit(padTypeLabel[t][0], "d",
padTypeLineEdit[t][0], "", true);
if (isDip)
setPadTypeLineEdit(padTypeLabel[t][1], "d in",
padTypeLineEdit[t][1], "", true);
else
setPadTypeLineEdit(padTypeLabel[t][1], "", padTypeLineEdit[t][1], "", false);
setPadTypeLineEdit(padTypeLabel[t][2], "", padTypeLineEdit[t][2], "", false);
setPadTypeLineEdit(padTypeLabel[t][3], "", padTypeLineEdit[t][3], "", false);
}
break;
}
if (t >= 0)
for (int i = 0; i < maxPadParams; i++)
if (padTypeLineEdit[t][i]->isVisible())
padTypeLineEdit[t][i]->setReadOnly(false);
}
void PackageEditor::selectPushButton(int number)
{
int newGrid;
QString str;
switch (number) {
case CANCEL:
showPackageData();
break;
case CENTER:
centerElement();
updateElement();
break;
case DEC_GRID:
gridNumber -= 2;
case INC_GRID:
gridNumber++;
limit(gridNumber, 0, grids - 1);
newGrid = grid[gridNumber];
scale = double(gridStep) / newGrid;
centerX = newGrid * ((gridWidth / gridStep - 1) / 2);
centerY = newGrid * ((gridHeight / gridStep - 1) / 2);
gridLineEdit->setText(str.setNum(newGrid));
centerElement();
updateElement();
break;
case UPDATE:
updatePackage();
updateElement();
break;
}
update();
}
void PackageEditor::selectRadioButton(int number)
{
static int previousNumber = READ_ONLY_MODE;
if (number == previousNumber)
return;
tmpPackage.clear();
showPackageData();
selectRadioButton(previousNumber, false);
selectRadioButton(number, true);
bool state = false;
if (number != READ_ONLY_MODE)
state = true;
cancelPushButton->setEnabled(state);
updatePushButton->setEnabled(state);
previousNumber = number;
}
void PackageEditor::selectRadioButton(int number, bool state)
{
QString str;
switch (number) {
case ADD_ELLIPSE:
addEllipseHLineEdit->setReadOnly(!state);
addEllipseWLineEdit->setReadOnly(!state);
addEllipseXLineEdit->setReadOnly(!state);
addEllipseYLineEdit->setReadOnly(!state);
break;
case ADD_LINE:
addLineX1LineEdit->setReadOnly(!state);
addLineX2LineEdit->setReadOnly(!state);
addLineY1LineEdit->setReadOnly(!state);
addLineY2LineEdit->setReadOnly(!state);
break;
case ADD_PAD:
addPadOrientationComboBox->setEnabled(state);
addPadTypeComboBox->setEnabled(state);
if (state && package.pads.empty()) {
addPadXLineEdit->setReadOnly(true);
addPadYLineEdit->setReadOnly(true);
addPadXLineEdit->setText("0");
addPadYLineEdit->setText("0");
}
else {
addPadXLineEdit->setReadOnly(!state);
addPadYLineEdit->setReadOnly(!state);
}
break;
case ADD_PADS:
addPadsDxLineEdit->setReadOnly(!state);
addPadsDyLineEdit->setReadOnly(!state);
if (state && package.pads.empty()) {
addPadsFirstXLineEdit->setReadOnly(true);
addPadsFirstYLineEdit->setReadOnly(true);
addPadsFirstXLineEdit->setText("0");
addPadsFirstYLineEdit->setText("0");
}
else {
addPadsFirstXLineEdit->setReadOnly(!state);
addPadsFirstYLineEdit->setReadOnly(!state);
}
addPadsLastLineEdit->setReadOnly(!state);
addPadsOrientationComboBox->setEnabled(state);
addPadsTypeComboBox->setEnabled(state);
break;
case BORDER:
borderBottomLineEdit->setReadOnly(!state);
borderLeftXLineEdit->setReadOnly(!state);
borderRightXLineEdit->setReadOnly(!state);
borderTopYLineEdit->setReadOnly(!state);
break;
case DELETE_ELLIPSES:
deleteEllipsesFirstLineEdit->setReadOnly(!state);
deleteEllipsesLastLineEdit->setText(str.setNum(package.ellipses.size()));
break;
case DELETE_LINES:
deleteLinesFirstLineEdit->setReadOnly(!state);
deleteLinesLastLineEdit->setText(str.setNum(package.lines.size()));
break;
case DELETE_PADS:
deletePadsFirstLineEdit->setReadOnly(!state);
deletePadsLastLineEdit->setText(str.setNum(package.pads.size()));
break;
case NAME:
nameLineEdit->setReadOnly(!state);
break;
case PAD_TYPES:
padType0ShapeComboBox->setEnabled(state);
padType1ShapeComboBox->setEnabled(state);
padType2ShapeComboBox->setEnabled(state);
for (int i = 0; i < maxPadTypes; i++)
for (int j = 0; j < maxPadParams; j++)
if (padTypeLineEdit[i][j]->isVisible())
padTypeLineEdit[i][j]->setReadOnly(!state);
break;
case READ_ONLY_MODE:
break;
case SELECTED_ELLIPSE:
selectedEllipseHLineEdit->setReadOnly(!state);
selectedEllipseWLineEdit->setReadOnly(!state);
selectedEllipseXLineEdit->setReadOnly(!state);
selectedEllipseYLineEdit->setReadOnly(!state);
break;
case SELECTED_LINE:
selectedLineX1LineEdit->setReadOnly(!state);
selectedLineX2LineEdit->setReadOnly(!state);
selectedLineY1LineEdit->setReadOnly(!state);
selectedLineY2LineEdit->setReadOnly(!state);
break;
case SELECTED_PAD:
selectedPadNumberLineEdit->setReadOnly(!state);
selectedPadOrientationComboBox->setEnabled(state);
selectedPadTypeComboBox->setEnabled(state);
selectedPadXLineEdit->setReadOnly(!state);
selectedPadYLineEdit->setReadOnly(!state);
break;
case TYPE:
typeComboBox->setEnabled(state);
break;
}
}
void PackageEditor::setPadTypeLineEdit(QLabel *label, const QString &labelText,
QLineEdit *lineEdit, const QString &lineEditText,
bool state)
{
if (state) {
label->setText(labelText);
lineEdit->setText(lineEditText);
label->show();
lineEdit->show();
}
else {
label->hide();
lineEdit->hide();
label->clear();
lineEdit->clear();
}
}
void PackageEditor::setPadTypeTexts(int padTypeNumber, int n1, int n2, int n3, int n4)
{
int n[maxPadParams] = {n1, n2, n3, n4};
for (int i = 0; i < maxPadParams; i++)
if (n[i] > 0)
padTypeLineEdit[padTypeNumber][i]->setText(QString::number(n[i]));
else
padTypeLineEdit[padTypeNumber][i]->clear();
}
void PackageEditor::setRadioButton(QRadioButton *button, bool state)
{
button->setEnabled(state);
if (!state && button->isChecked())
readOnlyModeRadioButton->click();
}
/*
void PackageEditor::selectToolButton(int number)
{
int tmp;
QString str;
previousCommand = command;
command = number;
switch (command) {
case CREATE_GROUPS:
package.createGroups();
break;
case DECREASE_STEP:
step /= 4;
case INCREASE_STEP:
step *= 2;
limit(step, gridStep, 16 * gridStep);
stepLineEdit->setText(str.setNum(step));
break;
case METER:
meterLineEdit->setText(str.setNum(0));
break;
case MOVE:
package.selectedElement = false;
break;
case MOVE_DOWN:
dy += 2 * step;
case MOVE_UP:
dy -= step;
centerY = (gridY + 400 - dy) / scale + 0.5;
dyLineEdit->setText(str.setNum(dy));
break;
case MOVE_GROUP:
package.points.clear();
break;
case MOVE_LEFT:
dx -= 2 * step;
case MOVE_RIGHT:
dx += step;
centerX = (gridX + 570 - dx) / scale + 0.5;
dxLineEdit->setText(str.setNum(dx));
break;
case PLACE_DEVICE:
selectDevice(package.deviceNameID);
if (package.deviceNameID == -1)
command = SELECT;
break;
case PLACE_NET_NAME:
package.selectedWire = false;
break;
case PLACE_ELEMENTS:
package.placeElements();
break;
case PLACE_LINE:
break;
case PLACE_POLYGON:
if (package.layers.edit == FRONT || package.layers.edit == BACK ||
package.layers.edit == BORDER)
package.points.clear();
break;
case PLACE_SEGMENT:
if (package.layers.edit == FRONT || package.layers.edit == BACK)
package.pointNumber = 0;
break;
case ROUTE_TRACKS:
package.routeTracks();
break;
case SEGMENT_NETS:
if (package.layers.edit == FRONT || package.layers.edit == BACK)
package.segmentNets();
break;
case SELECT:
package.selectedElement = false;
package.showMessage = false;
package.pointNumber = 0;
break;
case SET_VALUE:
package.selectedElement = false;
break;
case SHOW_GROUND_NETS:
package.showGroundNets = true;
std::cerr << "package.showGroundNets = true" << std::endl;
package.showGroundNets ^= 1;
break;
case UPDATE_NETS:
break;
case TABLE_ROUTE:
package.tableRoute();
break;
case WAVE_ROUTE:
stepLineEdit->setText(str.setNum(0));
tmp = package.waveRoute();
stepLineEdit->setText(str.setNum(tmp));
break;
case ZOOM_IN:
gridNumber -= 2;
case ZOOM_OUT:
gridNumber++;
limit(gridNumber, 0, grids - 1);
scale = double(gridStep) / grid[gridNumber];
gridLineEdit->setText(str.setNum(grid[gridNumber]));
break;
}
update();
}
*/
void PackageEditor::showPackageData()
{
QString str;
nameLineEdit->setText(package.name);
typeComboBox->setCurrentText(package.type);
borderBottomLineEdit->setText(str.setNum(package.border.bottomY));
borderLeftXLineEdit->setText(str.setNum(package.border.leftX));
borderRightXLineEdit->setText(str.setNum(package.border.rightX));
borderTopYLineEdit->setText(str.setNum(package.border.topY));
selectedEllipseHLineEdit->clear();
selectedEllipseWLineEdit->clear();
selectedEllipseXLineEdit->clear();
selectedEllipseYLineEdit->clear();
addEllipseHLineEdit->clear();
addEllipseWLineEdit->clear();
addEllipseXLineEdit->clear();
addEllipseYLineEdit->clear();
deleteEllipsesFirstLineEdit->clear();
deleteEllipsesLastLineEdit->clear();
selectedLineX1LineEdit->clear();
selectedLineX2LineEdit->clear();
selectedLineY1LineEdit->clear();
selectedLineY2LineEdit->clear();
addLineX1LineEdit->clear();
addLineX2LineEdit->clear();
addLineY1LineEdit->clear();
addLineY2LineEdit->clear();
deleteLinesFirstLineEdit->clear();
deleteLinesLastLineEdit->clear();
for (int i = 0; i < maxPadTypes; i++) {
if (i < package.padTypesParams.size()) {
PadTypeParams ¶ms = package.padTypesParams[i];
int innerDiameter = 0;
if (package.type == "DIP")
innerDiameter = params.innerDiameter;
QString text = padShape(params);
if (text.isEmpty()) {
for (int j = 0; j < maxPadParams; j++)
padTypeLineEdit[i][j]->clear();
break;
}
selectPadTypeComboBox(i, text);
if (text == "Rectangle")
setPadTypeTexts(i, params.width, params.height, innerDiameter, 0);
if (text == "Rounded rectangle")
setPadTypeTexts(i, params.width, params.height,
params.diameter / 2, innerDiameter);
if (text == "Circle")
setPadTypeTexts(i, params.diameter, innerDiameter, 0, 0);
}
else
for (int j = 0; j < maxPadParams; j++)
padTypeLineEdit[i][j]->clear();
}
selectedPadNumberLineEdit->clear();
selectedPadOrientationComboBox->setCurrentIndex(0);
selectedPadTypeComboBox->setCurrentIndex(0);
selectedPadXLineEdit->clear();
selectedPadYLineEdit->clear();
addPadNumberLineEdit->setText(str.setNum(package.pads.size() + 1));
addPadOrientationComboBox->setCurrentIndex(0);
addPadTypeComboBox->setCurrentIndex(0);
if (package.pads.empty()) {
addPadXLineEdit->setText("0");
addPadYLineEdit->setText("0");
}
else {
addPadXLineEdit->clear();
addPadYLineEdit->clear();
}
addPadsDxLineEdit->clear();
addPadsDyLineEdit->clear();
addPadsFirstLineEdit->setText(str.setNum(package.pads.size() + 1));
if (package.pads.empty()) {
addPadsFirstXLineEdit->setText("0");
addPadsFirstYLineEdit->setText("0");
}
else {
addPadsFirstXLineEdit->clear();
addPadsFirstYLineEdit->clear();
}
addPadsLastLineEdit->clear();
addPadsOrientationComboBox->setCurrentIndex(0);
addPadsTypeComboBox->setCurrentIndex(0);
deletePadsFirstLineEdit->clear();
deletePadsLastLineEdit->clear();
ellipsesLineEdit->setText(str.setNum(package.ellipses.size()));
linesLineEdit->setText(str.setNum(package.lines.size()));
padsLineEdit->setText(str.setNum(package.pads.size()));
}
void PackageEditor::updatePackage()
{
const QString warningMessage = "Parameter value error";
bool ok[16];
int dx;
int dy;
int first;
int firstX;
int firstY;
int last;
int radioButtonNumber = READ_ONLY_MODE;
Ellipse ellipse;
Line line;
Pad pad;
QString str;
for (int i = 0; i < radioButtons; i++) {
if (radioButton[i]->isChecked()) {
radioButtonNumber = i;
break;
}
}
switch (radioButtonNumber) {
case ADD_ELLIPSE:
ellipse.h = addEllipseHLineEdit->text().toInt(&ok[0]);
ellipse.w = addEllipseWLineEdit->text().toInt(&ok[1]);
ellipse.x = addEllipseXLineEdit->text().toInt(&ok[2]);
ellipse.y = addEllipseYLineEdit->text().toInt(&ok[3]);
if (ok[0] && ok [1] && ok[2] && ok[3])
package.ellipses.push_back(ellipse);
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case ADD_LINE:
line.x1 = addLineX1LineEdit->text().toInt(&ok[0]);
line.x2 = addLineX2LineEdit->text().toInt(&ok[1]);
line.y1 = addLineY1LineEdit->text().toInt(&ok[2]);
line.y2 = addLineY2LineEdit->text().toInt(&ok[3]);
if (ok[0] && ok [1] && ok[2] && ok[3])
package.lines.push_back(line);
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case ADD_PAD:
pad.number = package.pads.size() + 1;
pad.orientation = 0; // "Up"
if (addPadOrientationComboBox->currentText() == "Right")
pad.orientation = 1;
pad.typeNumber = addPadTypeComboBox->currentText().toInt(&ok[0]);
if (package.pads.empty()) {
pad.x = 0;
pad.y = 0;
ok[1] = true;
ok[2] = true;
}
else {
pad.x = addPadXLineEdit->text().toInt(&ok[1]);
pad.y = addPadYLineEdit->text().toInt(&ok[2]);
}
if (ok[0] && ok [1] && ok[2] && pad.typeNumber < package.padTypesParams.size()) {
ok[3] = true;
for (auto p : package.pads)
if (pad.x == p.x && pad.y == p.y)
ok[3] = false;
if (!ok[3]) {
QMessageBox::warning(this, tr("Error"), "Pad already exists in this place");
break;
}
pad.diameter = package.padTypesParams[pad.typeNumber].diameter;
pad.height = package.padTypesParams[pad.typeNumber].height;
pad.innerDiameter = package.padTypesParams[pad.typeNumber].innerDiameter;
pad.net = 0;
pad.width = package.padTypesParams[pad.typeNumber].width;
package.pads.push_back(pad);
addPadNumberLineEdit->setText(str.setNum(package.pads.size() + 1));
addPadsFirstLineEdit->setText(str.setNum(package.pads.size() + 1));
addPadXLineEdit->setReadOnly(false);
addPadYLineEdit->setReadOnly(false);
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case ADD_PADS:
dx = addPadsDxLineEdit->text().toInt(&ok[0]);
dy = addPadsDyLineEdit->text().toInt(&ok[1]);
first = package.pads.size() + 1;
if (package.pads.empty()) {
firstX = 0;
firstY = 0;
ok[2] = true;
ok[3] = true;
}
else {
firstX = addPadsFirstXLineEdit->text().toInt(&ok[2]);
firstY = addPadsFirstYLineEdit->text().toInt(&ok[3]);
}
last = addPadsLastLineEdit->text().toInt(&ok[4]);
pad.orientation = 0; // "Up"
if (addPadsOrientationComboBox->currentText() == "Right")
pad.orientation = 1;
pad.typeNumber = addPadsTypeComboBox->currentText().toInt(&ok[5]);
if (ok[0] && ok[1] && ok[2] && ok[3] && ok[4] && ok[5] &&
(abs(dx) > 0 || abs(dy) > 0) && first < last && last <= maxPads &&
pad.typeNumber < package.padTypesParams.size()) {
ok[6] = true;
for (int i = first; i <= last; i++) {
pad.x = firstX + i * dx;
pad.y = firstY + i * dy;
for (auto p : package.pads)
if (pad.x == p.x && pad.y == p.y)
ok[6] = false;
}
if (!ok[6]) {
QMessageBox::warning(this, tr("Error"), "Pad already exists in this place");
break;
}
for (int i = first; i <= last; i++) {
pad.diameter = package.padTypesParams[pad.typeNumber].diameter;
pad.height = package.padTypesParams[pad.typeNumber].height;
pad.innerDiameter = package.padTypesParams[pad.typeNumber].innerDiameter;
pad.net = 0;
pad.number = i;
pad.width = package.padTypesParams[pad.typeNumber].width;
pad.x = firstX + i * dx;
pad.y = firstY + i * dy;
package.pads.push_back(pad);
}
addPadNumberLineEdit->setText(str.setNum(package.pads.size() + 1));
addPadsFirstLineEdit->setText(str.setNum(package.pads.size() + 1));
addPadsFirstXLineEdit->setReadOnly(false);
addPadsFirstYLineEdit->setReadOnly(false);
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case BORDER:
tmpPackage.border.bottomY = borderBottomLineEdit->text().toInt(&ok[0]);
tmpPackage.border.leftX = borderLeftXLineEdit->text().toInt(&ok[1]);
tmpPackage.border.rightX = borderRightXLineEdit->text().toInt(&ok[2]);
tmpPackage.border.topY = borderTopYLineEdit->text().toInt(&ok[3]);
if (ok[0] && ok [1] && ok[2] && ok[3] &&
tmpPackage.border.leftX < tmpPackage.border.rightX) {
if (tmpPackage.border.bottomY > tmpPackage.border.topY)
package.border = tmpPackage.border;
else {
QMessageBox::warning(this, tr("Error"), "topY should be less than bottomY "
"in this coordinate system");
break;
}
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case DELETE_ELLIPSES:
first = deleteEllipsesFirstLineEdit->text().toInt(&ok[0]);
last = package.ellipses.size();
if (ok[0] && first > 0 && first <= last) {
package.ellipses.resize(first - 1);
deleteEllipsesFirstLineEdit->clear();
deleteEllipsesLastLineEdit->setText(str.setNum(package.ellipses.size()));
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case DELETE_LINES:
first = deleteLinesFirstLineEdit->text().toInt(&ok[0]);
last = package.lines.size();
if (ok[0] && first > 0 && first <= last) {
package.lines.resize(first - 1);
deleteLinesFirstLineEdit->clear();
deleteLinesLastLineEdit->setText(str.setNum(package.lines.size()));
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case DELETE_PADS:
first = deletePadsFirstLineEdit->text().toInt(&ok[0]);
last = package.pads.size();
if (ok[0] && first > 0 && first <= last) {
package.pads.resize(first - 1);
deletePadsFirstLineEdit->clear();
deletePadsLastLineEdit->setText(str.setNum(package.pads.size()));
addPadNumberLineEdit->setText(str.setNum(package.pads.size() + 1));
addPadsFirstLineEdit->setText(str.setNum(package.pads.size() + 1));
if (package.pads.empty()) {
addPadXLineEdit->setText("0");
addPadYLineEdit->setText("0");
addPadsFirstXLineEdit->setText("0");
addPadsFirstYLineEdit->setText("0");
}
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case NAME:
package.name = nameLineEdit->text();
break;
case PAD_TYPES:
tmpPackage.padTypesParams.clear();
for (int i = 0; i < maxPadTypes; i++) {
QString text = padTypeShapeComboBox[i]->currentText();
int d = 0;
int h = 0;
int inD = 0;
int w = 0;
if (text == "Rectangle") {
w = padTypeLineEdit[i][0]->text().toInt(&ok[0]);
if (w <= 0)
ok[0] = false;
h = padTypeLineEdit[i][1]->text().toInt(&ok[1]);
if (h <= 0)
ok[1] = false;
if (package.type == "DIP") {
inD = padTypeLineEdit[i][2]->text().toInt(&ok[2]);
if (inD <= 0)
ok[2] = false;
}
else
ok[2] = true;
ok[3] = true;
}
if (text == "Rounded rectangle") {
w = padTypeLineEdit[i][0]->text().toInt(&ok[0]);
if (w <= 0)
ok[0] = false;
h = padTypeLineEdit[i][1]->text().toInt(&ok[1]);
if (h <= 0)
ok[1] = false;
d = 2 * padTypeLineEdit[i][2]->text().toInt(&ok[2]);
if (d <= 0)
ok[2] = false;
if (package.type == "DIP") {
inD = padTypeLineEdit[i][3]->text().toInt(&ok[3]);
if (inD <= 0)
ok[3] = false;
}
else
ok[3] = true;
}
if (text == "Circle") {
d = padTypeLineEdit[i][0]->text().toInt(&ok[0]);
if (d <= 0)
ok[0] = false;
if (package.type == "DIP") {
inD = padTypeLineEdit[i][1]->text().toInt(&ok[1]);
if (inD <= 0)
ok[1] = false;
}
else
ok[1] = true;
ok[2] = true;
ok[3] = true;
}
if (ok[0] && ok [1] && ok[2] && ok[3]) {
PadTypeParams padTypeParams = {d, h, inD, w};
tmpPackage.padTypesParams.push_back(padTypeParams);
}
else
break;
}
if (!tmpPackage.padTypesParams.empty())
package.padTypesParams = tmpPackage.padTypesParams;
break;
case READ_ONLY_MODE:
break;
case SELECTED_ELLIPSE:
if (isEllipseSelected) {
ellipse.h = selectedEllipseHLineEdit->text().toInt(&ok[0]);
ellipse.w = selectedEllipseWLineEdit->text().toInt(&ok[1]);
ellipse.x = selectedEllipseXLineEdit->text().toInt(&ok[2]);
ellipse.y = selectedEllipseYLineEdit->text().toInt(&ok[3]);
if (ok[0] && ok [1] && ok[2] && ok[3]) {
package.ellipses[selectedEllipseIndex] = ellipse;
selectedEllipseHLineEdit->clear();
selectedEllipseWLineEdit->clear();
selectedEllipseXLineEdit->clear();
selectedEllipseYLineEdit->clear();
isEllipseSelected = false;
}
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case SELECTED_LINE:
if (isLineSelected) {
line.x1 = selectedLineX1LineEdit->text().toInt(&ok[0]);
line.x2 = selectedLineX2LineEdit->text().toInt(&ok[1]);
line.y1 = selectedLineY1LineEdit->text().toInt(&ok[2]);
line.y2 = selectedLineY2LineEdit->text().toInt(&ok[3]);
if (ok[0] && ok [1] && ok[2] && ok[3]) {
package.lines[selectedLineIndex] = line;
selectedLineX1LineEdit->clear();
selectedLineX2LineEdit->clear();
selectedLineY1LineEdit->clear();
selectedLineY2LineEdit->clear();
isLineSelected = false;
}
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case SELECTED_PAD:
if (isPadSelected) {
pad.number = selectedPadNumberLineEdit->text().toInt(&ok[0]);
pad.orientation = 0; // "Up"
if (selectedPadOrientationComboBox->currentText() == "Right")
pad.orientation = 1;
pad.typeNumber = selectedPadTypeComboBox->currentText().toInt(&ok[1]);
pad.x = selectedPadXLineEdit->text().toInt(&ok[2]);
pad.y = selectedPadYLineEdit->text().toInt(&ok[3]);
if (ok[0] && ok [1] && ok[2] && ok[3] && pad.number >= 1) {
package.pads[selectedPadIndex] = pad;
selectedPadNumberLineEdit->clear();
selectedPadOrientationComboBox->setCurrentIndex(0);
selectedPadTypeComboBox->setCurrentIndex(0);
selectedPadXLineEdit->clear();
selectedPadYLineEdit->clear();
isPadSelected = false;
}
}
else
QMessageBox::warning(this, tr("Error"), warningMessage);
break;
case TYPE:
package.type = typeComboBox->currentText();
break;
}
ellipsesLineEdit->setText(str.setNum(package.ellipses.size()));
linesLineEdit->setText(str.setNum(package.lines.size()));
padsLineEdit->setText(str.setNum(package.pads.size()));
}
void PackageEditor::updateElement()
{
Element tmpElement(refX, refY, orientation, "", package, "", true, false);
element = tmpElement;
}
| 33.920147 | 96 | 0.588648 | [
"object"
] |
73beb6fe927c4ae6acc1fefcc12ee4974b0ac00b | 658 | cpp | C++ | origin/sequence/algorithm.test/generate.cpp | hiraditya/origin | f417d0688f9cdc7041a8375a66070b8e04c620ca | [
"MIT"
] | 2 | 2015-09-02T07:12:01.000Z | 2017-07-07T02:47:14.000Z | origin/sequence/algorithm.test/generate.cpp | hiraditya/origin | f417d0688f9cdc7041a8375a66070b8e04c620ca | [
"MIT"
] | 3 | 2015-05-04T06:32:43.000Z | 2015-08-30T00:36:02.000Z | origin/sequence/algorithm.test/generate.cpp | hiraditya/origin | f417d0688f9cdc7041a8375a66070b8e04c620ca | [
"MIT"
] | null | null | null | // Copyright (c) 2008-2010 Kent State University
// Copyright (c) 2011-2012 Texas A&M University
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#include <cassert>
#include <iostream>
#include <vector>
#include <origin/sequence/algorithm.hpp>
using namespace std;
using namespace origin;
int
main ()
{
using V = vector<int>;
V v (10);
generate (v, []
{
return 0;
});
assert (all_of (v, [](int n)
{
return n == 0;
}));
}
| 19.939394 | 78 | 0.586626 | [
"vector"
] |
73bf6f54606873bd7360745ae317fe88670b863a | 4,936 | cpp | C++ | src/MLPropertySet.cpp | ngwese/soundplaneclient | 76281c79d8da5ea629ed389aa80d66ac373bda0d | [
"MIT"
] | null | null | null | src/MLPropertySet.cpp | ngwese/soundplaneclient | 76281c79d8da5ea629ed389aa80d66ac373bda0d | [
"MIT"
] | null | null | null | src/MLPropertySet.cpp | ngwese/soundplaneclient | 76281c79d8da5ea629ed389aa80d66ac373bda0d | [
"MIT"
] | null | null | null |
// MadronaLib: a C++ framework for DSP applications.
// Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com
// Distributed under the MIT license: http://madrona-labs.mit-license.org/
#include "MLPropertySet.h"
#pragma mark MLPropertySet
const ml::Value MLPropertySet::nullProperty;
MLPropertySet::MLPropertySet() : mAllowNewProperties(true) {}
MLPropertySet::~MLPropertySet() {
std::list<MLPropertyListener *>::iterator it;
for (it = mpListeners.begin(); it != mpListeners.end(); it++) {
MLPropertyListener *pL = *it;
pL->propertyOwnerClosing();
}
mpListeners.clear();
}
const ml::Value &MLPropertySet::getProperty(ml::Symbol p) const {
static const ml::Value nullProperty; // TODO remove this?
std::map<ml::Symbol, ml::Value>::const_iterator it = mProperties.find(p);
if (it != mProperties.end()) {
return it->second;
} else {
return nullProperty;
}
}
const float MLPropertySet::getFloatProperty(ml::Symbol p) const {
static const float nullFloat = 0.f;
std::map<ml::Symbol, ml::Value>::const_iterator it = mProperties.find(p);
if (it != mProperties.end()) {
return it->second.getFloatValue();
} else {
return nullFloat;
}
}
const ml::Text MLPropertySet::getTextProperty(ml::Symbol p) const {
std::map<ml::Symbol, ml::Value>::const_iterator it = mProperties.find(p);
if (it != mProperties.end()) {
return it->second.getTextValue();
} else {
return ml::Text();
}
}
const ml::Matrix &MLPropertySet::getSignalProperty(ml::Symbol p) const {
std::map<ml::Symbol, ml::Value>::const_iterator it = mProperties.find(p);
if (it != mProperties.end()) {
return it->second.getMatrixValue();
} else {
return ml::Matrix::nullSignal;
}
}
// TODO check for duplicates! That could lead to a crash.
void MLPropertySet::addPropertyListener(MLPropertyListener *pL) {
mpListeners.push_back(pL);
}
void MLPropertySet::removePropertyListener(MLPropertyListener *pToRemove) {
std::list<MLPropertyListener *>::iterator it;
for (it = mpListeners.begin(); it != mpListeners.end(); it++) {
MLPropertyListener *pL = *it;
if (pL == pToRemove) {
mpListeners.erase(it);
return;
}
}
}
void MLPropertySet::broadcastProperty(ml::Symbol p, bool immediate) {
std::list<MLPropertyListener *>::iterator it;
for (it = mpListeners.begin(); it != mpListeners.end(); it++) {
MLPropertyListener *pL = *it;
pL->propertyChanged(p, immediate);
}
}
void MLPropertySet::broadcastPropertyExcludingListener(
ml::Symbol p, bool immediate, MLPropertyListener *pListenerToExclude) {
std::list<MLPropertyListener *>::iterator it;
for (it = mpListeners.begin(); it != mpListeners.end(); it++) {
MLPropertyListener *pL = *it;
if (pL != pListenerToExclude) {
pL->propertyChanged(p, immediate);
}
}
}
void MLPropertySet::broadcastAllProperties() {
std::map<ml::Symbol, ml::Value>::const_iterator it;
for (it = mProperties.begin(); it != mProperties.end(); it++) {
ml::Symbol p = it->first;
// TODO cut down on some of this broadcasting!
// //debug() << "BROADCASTING: " << p << "\n";
broadcastProperty(p, false);
}
}
#pragma mark MLPropertyListener
void MLPropertyListener::updateChangedProperties() {
if (!mpPropertyOwner)
return;
// for all model parameters we know about
std::map<ml::Symbol, PropertyState>::iterator it;
for (it = mPropertyStates.begin(); it != mPropertyStates.end(); it++) {
ml::Symbol key = it->first;
PropertyState &state = it->second;
if (state.mChangedSinceUpdate) {
const ml::Value &newValue = mpPropertyOwner->getProperty(key);
doPropertyChangeAction(key, newValue);
state.mChangedSinceUpdate = false;
state.mValue = newValue;
}
}
}
void MLPropertyListener::updateAllProperties() {
if (!mpPropertyOwner)
return;
mpPropertyOwner->broadcastAllProperties();
// mark all states as changed
std::map<ml::Symbol, PropertyState>::iterator it;
for (it = mPropertyStates.begin(); it != mPropertyStates.end(); it++) {
PropertyState &state = it->second;
state.mChangedSinceUpdate = true;
}
updateChangedProperties();
}
void MLPropertyListener::propertyChanged(ml::Symbol propName, bool immediate) {
if (!mpPropertyOwner)
return;
// if the property does not exist in the map yet, this lookup will add it.
PropertyState &state = mPropertyStates[propName];
// check for change in property. Note that this also compares signals and
// strings, which may possibly be slow.
const ml::Value &ownerValue = mpPropertyOwner->getProperty(propName);
if (ownerValue != state.mValue) {
if (immediate) {
doPropertyChangeAction(propName, ownerValue);
state.mValue = ownerValue;
} else {
state.mChangedSinceUpdate = true;
}
}
}
void MLPropertyListener::propertyOwnerClosing() {
if (!mpPropertyOwner)
return;
mpPropertyOwner = nullptr;
}
| 28.865497 | 79 | 0.68517 | [
"model"
] |
73bf6fae5267a489717874c1c63936a6a0a268ab | 6,238 | cc | C++ | mindspore/ccsrc/minddata/mindrecord/meta/shard_sample.cc | GuoSuiming/mindspore | 48afc4cfa53d970c0b20eedfb46e039db2a133d5 | [
"Apache-2.0"
] | 1 | 2021-03-10T09:05:13.000Z | 2021-03-10T09:05:13.000Z | mindspore/ccsrc/minddata/mindrecord/meta/shard_sample.cc | GuoSuiming/mindspore | 48afc4cfa53d970c0b20eedfb46e039db2a133d5 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/minddata/mindrecord/meta/shard_sample.cc | GuoSuiming/mindspore | 48afc4cfa53d970c0b20eedfb46e039db2a133d5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* 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 "minddata/mindrecord/include/shard_sample.h"
using mindspore::LogStream;
using mindspore::ExceptionType::NoExceptionType;
using mindspore::MsLogLevel::ERROR;
namespace mindspore {
namespace mindrecord {
ShardSample::ShardSample(int n)
: numerator_(0),
denominator_(0),
partition_id_(0),
no_of_samples_(n),
indices_({}),
sampler_type_(kCustomTopNSampler),
offset_(-1) {}
ShardSample::ShardSample(int num, int den)
: numerator_(num),
denominator_(den),
partition_id_(0),
no_of_samples_(0),
indices_({}),
sampler_type_(kCustomTopPercentSampler),
offset_(-1) {}
ShardSample::ShardSample(int num, int den, int par, int no_of_samples, int offset)
: numerator_(num),
denominator_(den),
partition_id_(par),
no_of_samples_(no_of_samples),
indices_({}),
sampler_type_(kCustomTopPercentSampler),
offset_(offset) {}
ShardSample::ShardSample(const std::vector<int64_t> &indices)
: numerator_(0),
denominator_(0),
partition_id_(0),
no_of_samples_(0),
indices_(indices),
sampler_type_(kSubsetSampler) {}
ShardSample::ShardSample(const std::vector<int64_t> &indices, uint32_t seed) : ShardSample(indices) {
sampler_type_ = kSubsetRandomSampler;
shuffle_op_ = std::make_shared<ShardShuffle>(seed);
}
int64_t ShardSample::GetNumSamples(int64_t dataset_size, int64_t num_classes) {
if (sampler_type_ == kCustomTopNSampler) {
return no_of_samples_;
}
if (sampler_type_ == kCustomTopPercentSampler) {
if (dataset_size % denominator_ == 0) {
return dataset_size / denominator_ * numerator_;
} else {
return dataset_size / denominator_ * numerator_ + 1;
}
}
if (sampler_type_ == kSubsetRandomSampler || sampler_type_ == kSubsetSampler) {
return indices_.size();
}
return 0;
}
MSRStatus ShardSample::UpdateTasks(ShardTask &tasks, int taking) {
if (tasks.permutation_.empty()) {
ShardTask new_tasks;
int total_no = static_cast<int>(tasks.Size());
if (sampler_type_ == kSubsetRandomSampler || sampler_type_ == kSubsetSampler) {
for (int i = 0; i < indices_.size(); ++i) {
int index = ((indices_[i] % total_no) + total_no) % total_no;
new_tasks.InsertTask(tasks.GetTaskByID(index)); // different mod result between c and python
}
} else {
int count = 0;
if (nums_per_shard_.empty()) {
for (size_t i = partition_id_ * taking; i < (partition_id_ + 1) * taking; i++) {
if (no_of_samples_ != 0 && count == no_of_samples_) break;
new_tasks.InsertTask(tasks.GetTaskByID(i % total_no)); // rounding up. if overflow, go back to start
count++;
}
} else {
// Get samples within a specific range
size_t i = partition_id_ - 1 >= 0 ? nums_per_shard_[partition_id_ - 1] : 0;
for (; i < nums_per_shard_[partition_id_]; i++) {
if (no_of_samples_ != 0 && count == no_of_samples_) break;
new_tasks.InsertTask(tasks.GetTaskByID(i % total_no));
count++;
}
}
}
std::swap(tasks, new_tasks);
} else {
ShardTask new_tasks;
if (taking > static_cast<int>(tasks.permutation_.size())) {
return FAILED;
}
int total_no = static_cast<int>(tasks.permutation_.size());
int count = 0;
for (size_t i = partition_id_ * taking; i < (partition_id_ + 1) * taking; i++) {
if (no_of_samples_ != 0 && count == no_of_samples_) break;
new_tasks.InsertTask(tasks.GetTaskByID(tasks.permutation_[i % total_no]));
count++;
}
std::swap(tasks, new_tasks);
}
return SUCCESS;
}
MSRStatus ShardSample::Execute(ShardTask &tasks) {
if (offset_ != -1) {
int64_t old_v = 0;
int num_rows_ = static_cast<int>(tasks.Size());
for (int x = 0; x < denominator_; x++) {
int samples_per_buffer_ = (num_rows_ + offset_) / denominator_;
int remainder = (num_rows_ + offset_) % denominator_;
if (x < remainder) samples_per_buffer_++;
if (x < offset_) samples_per_buffer_--;
old_v += samples_per_buffer_;
// nums_per_shard_ is used to save the current shard's ending index
nums_per_shard_.push_back(old_v);
}
}
int no_of_categories = static_cast<int>(tasks.categories);
int total_no = static_cast<int>(tasks.Size()); // make sure task_size
int taking = 0;
if (sampler_type_ == kCustomTopNSampler) { // non sharding case constructor #1
no_of_samples_ = std::min(no_of_samples_, total_no);
taking = no_of_samples_ - no_of_samples_ % no_of_categories;
} else if (sampler_type_ == kSubsetRandomSampler || sampler_type_ == kSubsetSampler) {
if (indices_.size() > total_no) {
MS_LOG(ERROR) << "parameter indices's size is greater than dataset size.";
return FAILED;
}
} else { // constructor TopPercent
if (numerator_ > 0 && denominator_ > 0 && numerator_ <= denominator_) {
if (numerator_ == 1 && denominator_ > 1) { // sharding
taking = (total_no + denominator_ - 1) / denominator_;
} else { // non sharding
taking = total_no * numerator_ / denominator_;
taking -= (taking % no_of_categories);
}
} else {
MS_LOG(ERROR) << "parameter numerator or denominator is illegal";
return FAILED;
}
}
return UpdateTasks(tasks, taking);
}
MSRStatus ShardSample::SufExecute(ShardTask &tasks) {
if (sampler_type_ == kSubsetRandomSampler) {
if (SUCCESS != (*shuffle_op_)(tasks)) {
return FAILED;
}
}
return SUCCESS;
}
} // namespace mindrecord
} // namespace mindspore
| 34.655556 | 111 | 0.661109 | [
"vector"
] |
73bfb73569f448f1228b11dcfc4d13654b856ef4 | 403 | cpp | C++ | C++/number-of-laser-beams-in-a-bank.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 4 | 2018-10-11T17:50:56.000Z | 2018-10-11T21:16:44.000Z | C++/number-of-laser-beams-in-a-bank.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | null | null | null | C++/number-of-laser-beams-in-a-bank.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 4 | 2018-10-11T18:50:32.000Z | 2018-10-12T00:04:09.000Z | // Time: O(m * n)
// Space: O(1)
class Solution {
public:
int numberOfBeams(vector<string>& bank) {
int result = 0, prev = 0;
for (const auto& x : bank) {
const auto& cnt = count(cbegin(x), cend(x), '1');
if (!cnt) {
continue;
}
result += prev * cnt;
prev = cnt;
}
return result;
}
};
| 21.210526 | 61 | 0.426799 | [
"vector"
] |
73c278d33cc9035b0f4da51114f2b0d820196a5f | 1,460 | cpp | C++ | 01_Sorts/07_Bucket_Sort.cpp | premnaaath/DSA | e63598d33f52e398556b71ae92a3f9c3fe29f8a4 | [
"MIT"
] | 6 | 2021-07-10T15:09:22.000Z | 2022-03-29T10:06:49.000Z | 01_Sorts/07_Bucket_Sort.cpp | premnaaath/DSA | e63598d33f52e398556b71ae92a3f9c3fe29f8a4 | [
"MIT"
] | null | null | null | 01_Sorts/07_Bucket_Sort.cpp | premnaaath/DSA | e63598d33f52e398556b71ae92a3f9c3fe29f8a4 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// == Analysis =====================================
// Time Complexity: O(n)
// Space Complexity: O(n)
// Adaptability: True
// Stability: True
// K-Passes: False
// Algorithm:
// Same as CountSort but has linked representation
// CountSort saves frequency of appearance
// Bin/Bucket sort stores the value as a node
class Node
{
public:
int data;
Node *next;
Node(int d) : data(d), next(NULL) {}
};
int FindMax(vector<int> &arr)
{
int max{INT_MIN};
for (int i = 0; i < arr.size(); ++i)
if (arr[i] > max)
max = arr[i];
return max == INT_MIN ? 0 : max;
}
// Also known as Bucket sort
void BinSort(vector<int> &arr)
{
int max = FindMax(arr);
vector<Node *> bin(max + 1, NULL);
for (int i = 0; i < arr.size(); ++i)
{
if (bin[arr[i]] == NULL)
bin[arr[i]] = new Node(arr[i]);
else
{
Node *temp = bin[arr[i]];
while (temp->next)
temp = temp->next;
temp->next = new Node(arr[i]);
}
}
int k{};
for (int i = 0; i <= max; ++i)
{
Node *temp = bin[i];
while (temp)
{
arr[k++] = temp->data;
temp = temp->next;
}
}
}
int main()
{
vector<int> arr{2, 3, 97, 4, 2, 9, 22, 6, 5, 9, 10};
BinSort(arr);
for (auto i : arr)
cout << i << " ";
cout << endl;
return 0;
} | 21.15942 | 56 | 0.480137 | [
"vector"
] |
73c2f923227b52bc2631be028146a408bb8ccea6 | 3,662 | cc | C++ | AbsEnv/TwoCoordIndex.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | AbsEnv/TwoCoordIndex.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | AbsEnv/TwoCoordIndex.cc | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: TwoCoordIndex.cc 483 2010-01-13 14:03:08Z stroili $
//
// Description:
// Class TwoCoordIndex
//
// Implementation of AbsDetIndex for system in which two co-ordinates
// specifies a channel uniquely.
//
// Direct dependencies:
// Inherits from AbsDetIndex.
//
// Implementation dependencies:
// iostream
//
// Author List:
//
// Phil Strother Imperial College
// Stephen J. Gowdy University of Edinburgh
//
// Bugs, questions, etc. to: pd.strother@ic.ac.uk, S.Gowdy@ed.ac.uk
//
//======================================================================
#include "BaBar/BaBar.hh"
//-----------------------
// This Class's Header --
//-----------------------
#include "AbsEnv/TwoCoordIndex.hh"
#include "AbsEnv/AbsEnvTypes.hh"
//-------------
// C Headers --
//-------------
extern "C" {
}
//---------------
// C++ Headers --
//---------------
#include <iostream>
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "ErrLogger/ErrLog.hh"
using std::endl;
using std::ostream;
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
//----------------
// Constructors --
//----------------
TwoCoordIndex::TwoCoordIndex( long x, long y, long ind )
{
itsCoords = new AbsDetCoord(2);
// This is deleted by AbsDetIndex.
(*itsCoords)[0]=x;
(*itsCoords)[1]=y;
index=ind;
theNeighbours=new NeighbourStore;
// This is deleted by AbsDetIndex.
}
TwoCoordIndex::TwoCoordIndex(long theIndex, AbsDetCoord *init)
: AbsDetIndex( theIndex, init )
{
if (itsCoords->size()!=2)
{
ErrMsg( fatal ) << "Constructor called with initial vector of length "
<< init->size() << endmsg;
::abort();
}
}
TwoCoordIndex::TwoCoordIndex( const TwoCoordIndex © )
: AbsDetIndex( copy )
{
}
//--------------
// Destructor --
//--------------
TwoCoordIndex::~TwoCoordIndex()
{
}
//-------------
// Methods --
//-------------
void
TwoCoordIndex::print(ostream& o) const
{
o << index << " " << (*itsCoords)[0] << " " << (*itsCoords)[1] << endl;
}
void
TwoCoordIndex::printAll(ostream& o) const
{
print(o);
}
//-------------
// Operators --
//-------------
//-------------
// Selectors --
//-------------
unsigned
TwoCoordIndex::hash() const
{
return AbsDetIndex::hash();
}
//-------------
// Modifiers --
//-------------
// -----------------------------------------------
// -- Static Data & Function Member Definitions --
// -----------------------------------------------
unsigned
TwoCoordIndex::hashFun(const TwoCoordIndex &theIndex)
{
return theIndex.hash();
}
// -------------------------------------------
// -- Protected Function Member Definitions --
// -------------------------------------------
// -----------------------------------------
// -- Private Function Member Definitions --
// -----------------------------------------
// -----------------------------------
// -- Internal Function Definitions --
// -----------------------------------
| 24.413333 | 77 | 0.41207 | [
"vector"
] |
73cb30e77b991f9571222d2d5581a8e5704dd1c6 | 8,948 | cc | C++ | remote_config/testapp/src/android/android_main.cc | ggfan/quickstart-cpp | bc21e96b2a78acb050d0097e4a3a7fbec7fc4fcc | [
"Apache-2.0"
] | 187 | 2016-05-19T05:22:24.000Z | 2022-03-30T17:42:42.000Z | remote_config/testapp/src/android/android_main.cc | digideskio/quickstart-cpp | f6a448d5c98209d966dbb4df373a508d758bbb70 | [
"Apache-2.0"
] | 68 | 2016-08-12T23:59:06.000Z | 2021-07-21T19:59:29.000Z | remote_config/testapp/src/android/android_main.cc | digideskio/quickstart-cpp | f6a448d5c98209d966dbb4df373a508d758bbb70 | [
"Apache-2.0"
] | 128 | 2016-05-18T20:27:22.000Z | 2022-03-13T17:34:12.000Z | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdarg.h>
#include <stdio.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <pthread.h>
#include <cassert>
#include "main.h" // NOLINT
// This implementation is derived from http://github.com/google/fplutil
extern "C" int common_main(int argc, const char* argv[]);
static struct android_app* g_app_state = nullptr;
static bool g_destroy_requested = false;
static bool g_started = false;
static bool g_restarted = false;
static pthread_mutex_t g_started_mutex;
// Handle state changes from via native app glue.
static void OnAppCmd(struct android_app* app, int32_t cmd) {
g_destroy_requested |= cmd == APP_CMD_DESTROY;
}
// Process events pending on the main thread.
// Returns true when the app receives an event requesting exit.
bool ProcessEvents(int msec) {
struct android_poll_source* source = nullptr;
int events;
int looperId = ALooper_pollAll(msec, nullptr, &events,
reinterpret_cast<void**>(&source));
if (looperId >= 0 && source) {
source->process(g_app_state, source);
}
return g_destroy_requested | g_restarted;
}
// Get the activity.
jobject GetActivity() { return g_app_state->activity->clazz; }
// Get the window context. For Android, it's a jobject pointing to the Activity.
jobject GetWindowContext() { return g_app_state->activity->clazz; }
// Find a class, attempting to load the class if it's not found.
jclass FindClass(JNIEnv* env, jobject activity_object, const char* class_name) {
jclass class_object = env->FindClass(class_name);
if (env->ExceptionCheck()) {
env->ExceptionClear();
// If the class isn't found it's possible NativeActivity is being used by
// the application which means the class path is set to only load system
// classes. The following falls back to loading the class using the
// Activity before retrieving a reference to it.
jclass activity_class = env->FindClass("android/app/Activity");
jmethodID activity_get_class_loader = env->GetMethodID(
activity_class, "getClassLoader", "()Ljava/lang/ClassLoader;");
jobject class_loader_object =
env->CallObjectMethod(activity_object, activity_get_class_loader);
jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
jmethodID class_loader_load_class =
env->GetMethodID(class_loader_class, "loadClass",
"(Ljava/lang/String;)Ljava/lang/Class;");
jstring class_name_object = env->NewStringUTF(class_name);
class_object = static_cast<jclass>(env->CallObjectMethod(
class_loader_object, class_loader_load_class, class_name_object));
if (env->ExceptionCheck()) {
env->ExceptionClear();
class_object = nullptr;
}
env->DeleteLocalRef(class_name_object);
env->DeleteLocalRef(class_loader_object);
}
return class_object;
}
// Vars that we need available for appending text to the log window:
class LoggingUtilsData {
public:
LoggingUtilsData()
: logging_utils_class_(nullptr),
logging_utils_add_log_text_(0),
logging_utils_init_log_window_(0) {}
~LoggingUtilsData() {
JNIEnv* env = GetJniEnv();
assert(env);
if (logging_utils_class_) {
env->DeleteGlobalRef(logging_utils_class_);
}
}
void Init() {
JNIEnv* env = GetJniEnv();
assert(env);
jclass logging_utils_class = FindClass(
env, GetActivity(), "com/google/firebase/example/LoggingUtils");
assert(logging_utils_class != 0);
// Need to store as global references so it don't get moved during garbage
// collection.
logging_utils_class_ =
static_cast<jclass>(env->NewGlobalRef(logging_utils_class));
env->DeleteLocalRef(logging_utils_class);
logging_utils_init_log_window_ = env->GetStaticMethodID(
logging_utils_class_, "initLogWindow", "(Landroid/app/Activity;)V");
logging_utils_add_log_text_ = env->GetStaticMethodID(
logging_utils_class_, "addLogText", "(Ljava/lang/String;)V");
env->CallStaticVoidMethod(logging_utils_class_,
logging_utils_init_log_window_, GetActivity());
}
void AppendText(const char* text) {
if (logging_utils_class_ == 0) return; // haven't been initted yet
JNIEnv* env = GetJniEnv();
assert(env);
jstring text_string = env->NewStringUTF(text);
env->CallStaticVoidMethod(logging_utils_class_, logging_utils_add_log_text_,
text_string);
env->DeleteLocalRef(text_string);
}
private:
jclass logging_utils_class_;
jmethodID logging_utils_add_log_text_;
jmethodID logging_utils_init_log_window_;
};
LoggingUtilsData* g_logging_utils_data;
// Checks if a JNI exception has happened, and if so, logs it to the console.
void CheckJNIException() {
JNIEnv* env = GetJniEnv();
if (env->ExceptionCheck()) {
// Get the exception text.
jthrowable exception = env->ExceptionOccurred();
env->ExceptionClear();
// Convert the exception to a string.
jclass object_class = env->FindClass("java/lang/Object");
jmethodID toString =
env->GetMethodID(object_class, "toString", "()Ljava/lang/String;");
jstring s = (jstring)env->CallObjectMethod(exception, toString);
const char* exception_text = env->GetStringUTFChars(s, nullptr);
// Log the exception text.
__android_log_print(ANDROID_LOG_INFO, FIREBASE_TESTAPP_NAME,
"-------------------JNI exception:");
__android_log_print(ANDROID_LOG_INFO, FIREBASE_TESTAPP_NAME, "%s",
exception_text);
__android_log_print(ANDROID_LOG_INFO, FIREBASE_TESTAPP_NAME,
"-------------------");
// Also, assert fail.
assert(false);
// In the event we didn't assert fail, clean up.
env->ReleaseStringUTFChars(s, exception_text);
env->DeleteLocalRef(s);
env->DeleteLocalRef(exception);
}
}
// Log a message that can be viewed in "adb logcat".
void LogMessage(const char* format, ...) {
static const int kLineBufferSize = 100;
char buffer[kLineBufferSize + 2];
va_list list;
va_start(list, format);
int string_len = vsnprintf(buffer, kLineBufferSize, format, list);
string_len = string_len < kLineBufferSize ? string_len : kLineBufferSize;
// append a linebreak to the buffer:
buffer[string_len] = '\n';
buffer[string_len + 1] = '\0';
__android_log_vprint(ANDROID_LOG_INFO, FIREBASE_TESTAPP_NAME, format, list);
g_logging_utils_data->AppendText(buffer);
CheckJNIException();
va_end(list);
}
// Get the JNI environment.
JNIEnv* GetJniEnv() {
JavaVM* vm = g_app_state->activity->vm;
JNIEnv* env;
jint result = vm->AttachCurrentThread(&env, nullptr);
return result == JNI_OK ? env : nullptr;
}
// Execute common_main(), flush pending events and finish the activity.
extern "C" void android_main(struct android_app* state) {
// native_app_glue spawns a new thread, calling android_main() when the
// activity onStart() or onRestart() methods are called. This code handles
// the case where we're re-entering this method on a different thread by
// signalling the existing thread to exit, waiting for it to complete before
// reinitializing the application.
if (g_started) {
g_restarted = true;
// Wait for the existing thread to exit.
pthread_mutex_lock(&g_started_mutex);
pthread_mutex_unlock(&g_started_mutex);
} else {
g_started_mutex = PTHREAD_MUTEX_INITIALIZER;
}
pthread_mutex_lock(&g_started_mutex);
g_started = true;
// Save native app glue state and setup a callback to track the state.
g_destroy_requested = false;
g_app_state = state;
g_app_state->onAppCmd = OnAppCmd;
// Create the logging display.
g_logging_utils_data = new LoggingUtilsData();
g_logging_utils_data->Init();
// Execute cross platform entry point.
static const char* argv[] = {FIREBASE_TESTAPP_NAME};
int return_value = common_main(1, argv);
(void)return_value; // Ignore the return value.
ProcessEvents(10);
// Clean up logging display.
delete g_logging_utils_data;
g_logging_utils_data = nullptr;
// Finish the activity.
if (!g_restarted) ANativeActivity_finish(state->activity);
g_app_state->activity->vm->DetachCurrentThread();
g_started = false;
g_restarted = false;
pthread_mutex_unlock(&g_started_mutex);
}
| 34.953125 | 80 | 0.711332 | [
"object"
] |
73ceb569dbcc381b2e640b1d7c6f41ce6662b738 | 838 | cpp | C++ | tc 160+/P8XCoinChangeAnother.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/P8XCoinChangeAnother.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/P8XCoinChangeAnother.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
class P8XCoinChangeAnother {
public:
vector<long long> solve(int N, long long coins_sum, long long coins_count) {
if (coins_count > coins_sum) {
return vector<long long>();
}
vector<long long> sol(N, 0);
sol[0] = coins_sum;
long long need = coins_sum - coins_count;
for (int i=1; need>0 && i<N; ++i) {
long long rmv = min(sol[i-1], 2*need);
sol[i] = rmv/2;
sol[i-1] -= rmv/2*2;
need -= rmv/2;
}
if (need > 0) {
return vector<long long>();
}
return sol;
}
};
| 23.277778 | 80 | 0.540573 | [
"vector"
] |
73d24857411955d3f4bd09d455d015019f232723 | 5,329 | cpp | C++ | base32/test/test_base32.cpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | 24 | 2020-07-01T13:45:50.000Z | 2021-11-04T19:54:47.000Z | base32/test/test_base32.cpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | base32/test/test_base32.cpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | #include <fstream>
#include <string>
#include <vector>
#include <catch2/catch.hpp>
#include <mgs/base32.hpp>
#include <mgs/exceptions/invalid_input_error.hpp>
#include <mgs/exceptions/unexpected_eof_error.hpp>
#include "codec_helpers.hpp"
#include "noop_iterator.hpp"
using namespace std::string_literals;
using namespace mgs;
extern std::vector<std::string> testFilePaths;
TEST_CASE("base32")
{
std::vector<std::string> decoded{"a"s, "ab"s, "abc"s, "abcd"s, "abcde"s};
std::vector<std::string> encoded{
"ME======"s, "MFRA===="s, "MFRGG==="s, "MFRGGZA="s, "MFRGGZDF"s};
auto const encoded_twice = "JVDFER2HLJCEM==="s;
SECTION("Common tests")
{
CHECK(base32::encode<std::string>("") == "");
CHECK(base32::decode<std::string>("") == "");
for (auto i = 0u; i < encoded.size(); ++i)
{
test_helpers::basic_codec_tests<base32>(decoded[i], encoded[i]);
test_helpers::test_std_containers<base32>(decoded[i], encoded[i]);
test_helpers::test_input_streams<base32>(decoded[i], encoded[i]);
test_helpers::test_back_and_forth<base32>(decoded[i], encoded[i]);
}
test_helpers::test_encode_twice<base32>(decoded.back(), encoded_twice);
}
SECTION("stream")
{
REQUIRE(testFilePaths.size() == 2);
std::ifstream random_data(testFilePaths[0],
std::ios::binary | std::ios::in);
std::ifstream b32_random_data(testFilePaths[1],
std::ios::binary | std::ios::in);
using iterator = std::istreambuf_iterator<char>;
auto encoder = base32::make_encoder(iterator(random_data), iterator());
auto range = codecs::make_input_range(std::move(encoder));
test_helpers::check_equal(
range.begin(), range.end(), iterator(b32_random_data), iterator());
random_data.seekg(0);
b32_random_data.seekg(0);
auto decoder = base32::make_decoder(iterator(b32_random_data), iterator());
auto range2 = codecs::make_input_range(std::move(decoder));
test_helpers::check_equal(
range2.begin(), range2.end(), iterator{random_data}, iterator());
}
SECTION("invalid input")
{
std::vector<std::string> invalid_chars{"========"s,
"**DA=2=="s,
"M======="s,
"MFR====="s,
"MFRAFA=="s,
"MFRA@==="s};
std::vector<std::string> invalid_eof{"MFA"s, "MFRGGZDFA"s};
for (auto const& elem : invalid_chars)
{
CHECK_THROWS_AS(base32::decode(elem),
mgs::exceptions::invalid_input_error);
}
for (auto const& elem : invalid_eof)
{
CHECK_THROWS_AS(base32::decode(elem),
mgs::exceptions::unexpected_eof_error);
}
}
SECTION("max_remaining_size")
{
SECTION("encoder")
{
SECTION("Small string")
{
auto const decoded = "abcdefghijklm"s;
auto enc = base32::make_encoder(decoded.begin(), decoded.end());
CHECK(enc.max_remaining_size() == 24);
}
SECTION("Huge string")
{
std::string huge_str(10000, 0);
auto enc = base32::make_encoder(huge_str.begin(), huge_str.end());
CHECK(enc.max_remaining_size() == 16000);
}
}
SECTION("decoder")
{
SECTION("Small string")
{
auto const encoded = "MFRGGZA="s;
auto dec = base32::make_decoder(encoded.begin(), encoded.end());
CHECK(dec.max_remaining_size() == 5);
dec.read(test_helpers::noop_iterator{}, 2);
CHECK(dec.max_remaining_size() == 2);
}
SECTION("Huge string")
{
auto const encoded = base32::encode<std::string>(std::string(10000, 0));
auto dec = base32::make_decoder(encoded.begin(), encoded.end());
CHECK(dec.max_remaining_size() == 10000);
}
SECTION("Rounded size")
{
auto encoded = base32::encode<std::string>(std::string(10000, 0));
encoded.pop_back();
auto dec = base32::make_decoder(encoded.begin(), encoded.end());
CHECK(dec.max_remaining_size() == 9995);
}
SECTION("Invalid size")
{
std::string invalid(4, 0);
auto dec = base32::make_decoder(invalid);
CHECK(dec.max_remaining_size() == 0);
}
}
}
SECTION("encoded_size")
{
CHECK(base32::encoded_size(0) == 0);
CHECK(base32::encoded_size(1) == 8);
CHECK(base32::encoded_size(2) == 8);
CHECK(base32::encoded_size(3) == 8);
CHECK(base32::encoded_size(4) == 8);
CHECK(base32::encoded_size(5) == 8);
CHECK(base32::encoded_size(6) == 16);
}
SECTION("max_decoded_size")
{
CHECK(base32::max_decoded_size(0) == 0);
CHECK(base32::max_decoded_size(8) == 5);
CHECK(base32::max_decoded_size(32) == 20);
CHECK(base32::max_decoded_size(1) == -1);
CHECK(base32::max_decoded_size(2) == -1);
CHECK(base32::max_decoded_size(3) == -1);
CHECK(base32::max_decoded_size(4) == -1);
CHECK(base32::max_decoded_size(5) == -1);
CHECK(base32::max_decoded_size(6) == -1);
CHECK(base32::max_decoded_size(7) == -1);
CHECK(base32::max_decoded_size(33) == -1);
CHECK(base32::max_decoded_size(31) == -1);
}
}
| 30.107345 | 80 | 0.587352 | [
"vector"
] |
73d4f1717b382e0c37ad5f4b04ed0087ac34f08a | 10,077 | cpp | C++ | rai/Kin/switch.cpp | ARoefer/rai | d04eb8e918ea00268d42cb9ff1e9384dc585c10e | [
"MIT"
] | null | null | null | rai/Kin/switch.cpp | ARoefer/rai | d04eb8e918ea00268d42cb9ff1e9384dc585c10e | [
"MIT"
] | null | null | null | rai/Kin/switch.cpp | ARoefer/rai | d04eb8e918ea00268d42cb9ff1e9384dc585c10e | [
"MIT"
] | null | null | null | /* ------------------------------------------------------------------
Copyright (c) 2019 Marc Toussaint
email: marc.toussaint@informatik.uni-stuttgart.de
This code is distributed under the MIT License.
Please see <root-path>/LICENSE for details.
-------------------------------------------------------------- */
#include "switch.h"
#include "kin.h"
#include <climits>
#include "contact.h"
//===========================================================================
/* x_{-1} = x_{time=0}
* x_{9}: phase=1 (for stepsPerPhase=10 */
int conv_time2step(double time, uint stepsPerPhase) {
return (floor(time*double(stepsPerPhase) + .500001))-1;
}
double conv_step2time(int step, uint stepsPerPhase) {
return double(step+1)/double(stepsPerPhase);
}
//#define STEP(t) (floor(t*double(stepsPerPhase) + .500001))-1
//===========================================================================
template<> const char* rai::Enum<rai::SwitchType>::names []= {
"noJointLink",
"joint",
"makeDynamic",
"makeKinematic",
"delContact",
"addContact",
nullptr
};
template<> const char* rai::Enum<rai::SwitchInitializationType>::names []= {
"zero",
"copy",
"random",
nullptr
};
//===========================================================================
//
// Kinematic Switch
//
rai::KinematicSwitch::KinematicSwitch()
: symbol(SW_none), jointType(JT_none), init(SWInit_zero), timeOfApplication(-1), fromId(-1), toId(-1), jA(0), jB(0)
{}
rai::KinematicSwitch::KinematicSwitch(SwitchType _symbol, JointType _jointType, int aFrame, int bFrame, SwitchInitializationType _init, int _timeOfApplication, const rai::Transformation& jFrom, const rai::Transformation& jTo)
: symbol(_symbol),
jointType(_jointType),
init(_init),
timeOfApplication(_timeOfApplication),
fromId(aFrame), toId(bFrame),
jA(0), jB(0) {
if(!!jFrom) jA = jFrom;
if(!!jTo) jB = jTo;
}
rai::KinematicSwitch::KinematicSwitch(rai::SwitchType op, rai::JointType type, const char* ref1, const char* ref2, const rai::Configuration& K, rai::SwitchInitializationType _init, int _timeOfApplication, const rai::Transformation& jFrom, const rai::Transformation& jTo)
: KinematicSwitch(op, type, initIdArg(K, ref1), initIdArg(K, ref2), _init, _timeOfApplication, jFrom, jTo)
{}
void rai::KinematicSwitch::setTimeOfApplication(double time, bool before, int stepsPerPhase, uint T) {
if(stepsPerPhase<0) stepsPerPhase=T;
timeOfApplication = (time<0.?0:conv_time2step(time, stepsPerPhase))+(before?0:1);
}
void rai::KinematicSwitch::apply(Configuration& K) {
Frame* from=nullptr, *to=nullptr;
if(fromId!=-1) from=K.frames(fromId);
if(toId!=-1) to=K.frames(toId);
if(symbol==SW_joint || symbol==SW_joint) {
rai::Transformation orgX = to->ensure_X();
//first find link frame above 'to', and make it a root
#if 0 //THIS is the standard version that worked with pnp LGP tests - but is a problem for the crawler
rai::Frame* link = to->getUpwardLink(NoTransformation, false);
if(link->parent) link->unLink();
#else //THIS is the version that works for the crawler; I guess the major difference is 'upward until part break' and 'flip frames'
K.reconfigureRoot(to, true);
#endif
//create a new joint
to->linkFrom(from, false);
Joint* j = new Joint(*to);
j->setType(jointType);
if(!jA.isZero()) j->frame->insertPreLink(jA);
if(!jB.isZero()) { HALT("only to be careful: does the orgX still work?"); j->frame->insertPostLink(jB); }
//initialize to zero, copy, or random
if(init==SWInit_zero) { //initialize the joint with zero transform
j->frame->Q.setZero();
} else if(init==SWInit_copy) { //set Q to the current relative transform, modulo DOFs
j->frame->Q = orgX / j->frame->parent->ensure_X(); //that's important for the initialization of x during the very first komo.setupConfigurations !!
//cout <<j->frame->Q <<' ' <<j->frame->Q.rot.normalization() <<endl;
arr q = j->calc_q_from_Q(j->frame->Q);
j->frame->Q.setZero();
j->calc_Q_from_q(q, 0);
} if(init==SWInit_random) { //random, modulo DOFs
j->frame->Q.setRandom();
arr q = j->calc_q_from_Q(j->frame->Q);
j->frame->Q.setZero();
j->calc_Q_from_q(q, 0);
}
j->frame->_state_updateAfterTouchingQ();
//K.reset_q();
//K.calc_q(); K.checkConsistency();
// {
// static int i=0;
// FILE(STRING("z.switch_"<<i++<<".g")) <<K;
// }
return;
}
if(symbol==SW_noJointLink) {
CHECK_EQ(jointType, JT_none, "");
if(to->parent) to->unLink();
to->linkFrom(from, true);
K.reset_q();
return;
}
if(symbol==makeDynamic) {
CHECK_EQ(jointType, JT_none, "");
CHECK_EQ(to, 0, "");
CHECK(from->inertia, "can only make frames with intertia dynamic");
from->inertia->type=rai::BT_dynamic;
if(from->joint) {
from->joint->H = 1e-1;
}
return;
}
if(symbol==makeKinematic) {
CHECK_EQ(jointType, JT_none, "");
CHECK_EQ(to, 0, "");
CHECK(from->inertia, "can only make frames with intertia kinematic");
from->inertia->type=rai::BT_kinematic;
// if(from->joint){
// from->joint->constrainToZeroVel=false;
// from->joint->H = 1e-1;
// }
return;
}
if(symbol==SW_addContact) {
CHECK_EQ(jointType, JT_none, "");
new rai::Contact(*from, *to);
return;
}
if(symbol==SW_delContact) {
CHECK_EQ(jointType, JT_none, "");
rai::Contact* c = nullptr;
for(rai::Contact* cc:to->contacts) if(&cc->a==from || &cc->b==from) { c=cc; break; }
if(!c) HALT("not found");
delete c;
return;
}
HALT("shouldn't be here!");
}
rai::String rai::KinematicSwitch::shortTag(const rai::Configuration* G) const {
rai::String str;
str <<" timeOfApplication=" <<timeOfApplication;
str <<" symbol=" <<symbol;
str <<" jointType=" <<jointType;
str <<" fromId=" <<(fromId==-1?"nullptr":(G?G->frames(fromId)->name:STRING(fromId)));
str <<" toId=" <<(G?G->frames(toId)->name:STRING(toId)) <<endl;
return str;
}
void rai::KinematicSwitch::write(std::ostream& os, rai::Configuration* K) const {
os <<"SWITCH timeOfApplication=" <<timeOfApplication;
os <<" symbol=" <<symbol;
os <<" jointType=" <<jointType;
os <<" fromId=" <<(int)fromId;
if(K && fromId<-1) os <<"'" <<K->frames(fromId)->name <<"'";
os <<" toId=" <<toId;
if(K && toId<-1) os <<"'" <<K->frames(toId)->name <<"'";
}
//===========================================================================
/*
rai::KinematicSwitch* rai::KinematicSwitch::newSwitch(const Node *specs, const rai::Configuration& world, int stepsPerPhase, uint T) {
if(specs->parents.N<2) return nullptr;
//-- get tags
rai::String& tt=specs->parents(0)->keys.last();
rai::String& type=specs->parents(1)->keys.last();
const char *ref1=nullptr, *ref2=nullptr;
if(specs->parents.N>2) ref1=specs->parents(2)->keys.last().p;
if(specs->parents.N>3) ref2=specs->parents(3)->keys.last().p;
if(tt!="MakeJoint") return nullptr;
rai::KinematicSwitch* sw = newSwitch(type, ref1, ref2, world, stepsPerPhase + 1);
if(specs->isGraph()) {
const Graph& params = specs->graph();
sw->setTimeOfApplication(params.get<double>("time",1.), params.get<bool>("time", false), stepsPerPhase, T);
// sw->timeOfApplication = *stepsPerPhase + 1;
params.get(sw->jA, "from");
params.get(sw->jB, "to");
}
return sw;
}
*/
/*
rai::KinematicSwitch* rai::KinematicSwitch::newSwitch(const rai::String& type, const char* ref1, const char* ref2, const rai::Configuration& world, int _timeOfApplication, const rai::Transformation& jFrom, const rai::Transformation& jTo) {
//-- create switch
rai::KinematicSwitch *sw= new rai::KinematicSwitch();
if(type=="addRigid") { sw->symbol=rai::SW_joint; sw->jointType=rai::JT_rigid; }
// else if(type=="addRigidRel"){ sw->symbol = rai::KinematicSwitch::addJointAtTo; sw->jointType=rai::JT_rigid; }
else if(type=="rigidZero") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_rigid; }
else if(type=="transXActuated") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_transX; }
else if(type=="transXYPhiZero") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_transXYPhi; }
else if(type=="transXYPhiActuated") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_transXYPhi; }
else if(type=="freeZero") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_free; }
else if(type=="freeActuated") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_free; }
else if(type=="ballZero") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_quatBall; }
else if(type=="hingeZZero") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_hingeZ; }
else if(type=="JT_XBall") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_XBall; }
else if(type=="JT_transZ") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_transZ; }
else if(type=="JT_transX") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_transX; }
else if(type=="JT_trans3") { sw->symbol = rai::SW_joint; sw->jointType=rai::JT_trans3; }
else if(type=="makeDynamic") { sw->symbol = rai::makeDynamic; }
else if(type=="makeKinematic") { sw->symbol = rai::makeKinematic; }
else HALT("unknown type: "<< type);
if(ref1) sw->fromId = world.getFrameByName(ref1)->ID;
if(ref2) sw->toId = world.getFrameByName(ref2)->ID;
// if(!ref2){
// CHECK_EQ(sw->symbol, rai::deleteJoint, "");
// rai::Body *b = fromShape->body;
// if(b->hasJoint()==1){
//// CHECK_EQ(b->parentOf.N, 0, "");
// sw->toId = sw->fromId;
// sw->fromId = b->joint()->from->shapes.first()->index;
// }else if(b->parentOf.N==1){
// CHECK_EQ(b->hasJoint(), 0, "");
// sw->toId = b->parentOf(0)->from->shapes.first()->index;
// }else if(b->hasJoint()==0 && b->parentOf.N==0){
// RAI_MSG("No link to delete for shape '" <<ref1 <<"'");
// delete sw;
// return nullptr;
// }else HALT("that's ambiguous");
// }else{
sw->timeOfApplication = _timeOfApplication;
if(!!jFrom) sw->jA = jFrom;
if(!!jTo) sw->jB = jTo;
return sw;
}
*/
| 37.322222 | 270 | 0.618537 | [
"shape",
"transform"
] |
73da0c3820335669aed4b1d92cb9db90d0316056 | 4,621 | cpp | C++ | CommonTools/RecoAlgos/test/FKDTree_t.cpp | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CommonTools/RecoAlgos/test/FKDTree_t.cpp | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CommonTools/RecoAlgos/test/FKDTree_t.cpp | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "Utilities/Testing/interface/CppUnit_testdriver.icpp"
#include "cppunit/extensions/HelperMacros.h"
class TestFKDTree: public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE (TestFKDTree);
CPPUNIT_TEST (test2D);
CPPUNIT_TEST (test3D);
CPPUNIT_TEST_SUITE_END();
public:
/// run all test tokenizer
void test2D();
void test3D();
};
CPPUNIT_TEST_SUITE_REGISTRATION (TestFKDTree);
#include "CommonTools/RecoAlgos/interface/FKDTree.h"
#include "FWCore/Utilities/interface/Exception.h"
void TestFKDTree::test2D()
{
try
{
FKDTree<float, 2> tree;
float minX = 0.2;
float minY = 0.1;
float maxX = 0.7;
float maxY = 0.9;
unsigned int numberOfPointsInTheBox = 1000;
unsigned int numberOfPointsOutsideTheBox = 5000;
std::vector<FKDPoint<float, 2> > points;
std::vector<unsigned int> result;
FKDPoint<float, 2> minPoint(minX, minY);
FKDPoint<float, 2> maxPoint(maxX, maxY);
unsigned int id = 0;
for (unsigned int i = 0; i < numberOfPointsInTheBox; ++i)
{
float x = minX
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(maxX - minX)));
float y = minY
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(maxY - minY)));
points.emplace_back(x, y, id);
id++;
}
for (unsigned int i = 0; i < numberOfPointsOutsideTheBox; ++i)
{
float x = static_cast<float>(rand()) / (static_cast<float>(RAND_MAX));
float y;
if (x <= maxX && x >= minX)
y = maxY
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(1.f - maxY)));
points.emplace_back(x, y, id);
id++;
}
tree.build(points);
tree.search(minPoint,maxPoint,result);
CPPUNIT_ASSERT_EQUAL((unsigned int)tree.size(), numberOfPointsInTheBox+numberOfPointsOutsideTheBox);
CPPUNIT_ASSERT_EQUAL((unsigned int)result.size(), numberOfPointsInTheBox);
} catch (cms::Exception& e)
{
std::cerr << e.what() << std::endl;
CPPUNIT_ASSERT(false);
}
}
void TestFKDTree::test3D()
{
try
{
FKDTree<float, 3> tree;
float minX = 0.2;
float minY = 0.1;
float minZ = 0.1;
float maxX = 0.7;
float maxY = 0.9;
float maxZ = 0.3;
unsigned int numberOfPointsInTheBox = 1000;
unsigned int numberOfPointsOutsideTheBox = 5000;
std::vector<FKDPoint<float, 3> > points;
std::vector<unsigned int> result;
FKDPoint<float, 3> minPoint(minX, minY, minZ);
FKDPoint<float, 3> maxPoint(maxX, maxY, maxZ);
unsigned int id = 0;
for (unsigned int i = 0; i < numberOfPointsInTheBox; ++i)
{
float x = minX
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(maxX - minX)));
float y = minY
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(maxY - minY)));
float z = minZ
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(maxZ - minZ)));
points.emplace_back(x, y, z, id);
id++;
}
for (unsigned int i = 0; i < numberOfPointsOutsideTheBox; ++i)
{
float x = static_cast<float>(rand()) / (static_cast<float>(RAND_MAX));
float y;
if (x <= maxX && x >= minX)
y = maxY
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(1.f - maxY)));
float z = minZ
+ static_cast<float>(rand())
/ (static_cast<float>(RAND_MAX / std::fabs(maxZ - minZ)));
points.emplace_back(x, y, z, id);
id++;
}
tree.build(points);
tree.search(minPoint,maxPoint,result);
CPPUNIT_ASSERT_EQUAL((unsigned int)tree.size(), numberOfPointsInTheBox+numberOfPointsOutsideTheBox);
CPPUNIT_ASSERT_EQUAL((unsigned int)result.size(), numberOfPointsInTheBox);
} catch (cms::Exception& e)
{
std::cerr << e.what() << std::endl;
CPPUNIT_ASSERT(false);
}
}
| 32.314685 | 108 | 0.531487 | [
"vector"
] |
73dc59c896c869d074e9192175c49a0b30da1c9b | 6,467 | cpp | C++ | src/main.cpp | breakeyd/otgTeX | 174dce4ea3a5ff25ddf4b5bcc293ee02820e5fe2 | [
"Apache-2.0"
] | 2 | 2016-05-25T07:11:23.000Z | 2016-05-31T03:46:46.000Z | src/main.cpp | breakeyd/otgTeX | 174dce4ea3a5ff25ddf4b5bcc293ee02820e5fe2 | [
"Apache-2.0"
] | null | null | null | src/main.cpp | breakeyd/otgTeX | 174dce4ea3a5ff25ddf4b5bcc293ee02820e5fe2 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2012 David Breakey
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bps/virtualkeyboard.h>
#include "activeGui.h"
#include GUI_HEADER_FILE
#include "languageTools.h"
#include "qnxExtensions.h"
#include "taskUtils.h"
//shared gui params
float width, height;
screen_context_t screen_cxt;
//local params
int exit_application = 0;
static virtualkeyboard_layout_t keyboardLayout = virtualkeyboard_layout_t(0);
int last_touch[2] = { 0, 0 };
void changeKeyboardType(int newKBType){
(newKBType>=0 && newKBType<8)?:newKBType=0;
keyboardLayout = virtualkeyboard_layout_t(newKBType);
virtualkeyboard_change_options(keyboardLayout, VIRTUALKEYBOARD_ENTER_DEFAULT);
}
int init() {
loadSettings();
if (EXIT_SUCCESS != loadLocalStrings()) {//initialize local translation
fprintf(stderr, "Unable to initialize translation\n");
return EXIT_FAILURE;
}
changeKeyboardType(keyboardLayout);
if (!checkForFirstRun()){
navigator_extend_timeout(1800000,NULL);//we now have 30 minutes to complete installation
if(!guiAlertQuery(gStr("STR_FIRST_RUN_QUERY"))){
fprintf(stderr,"Cancelled first run.\n");
return EXIT_FAILURE;
}
firstRunTasks();
loadSettings();//reload default settings
firstRunComplete();
fprintf(stderr,"Left first use tasks.\n");
navigator_extend_timeout(30000,NULL);//we now have 30 seconds to display a window
}
setTexBin("");
return EXIT_SUCCESS;
}
void term(){
saveSettings();
guiTerminate();//kill the gui
destroyLocalStrings();//destroy local strings
}
void render() {
guiRender();
}
void handleScreenEvent(bps_event_t *event)
{
screen_event_t screen_event = screen_event_get_event(event);
mtouch_event_t mtouch_event;
int screen_val, rc;
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &screen_val);
switch (screen_val) {
case SCREEN_EVENT_KEYBOARD:
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_FLAGS, &screen_val);
if (screen_val & KEY_DOWN) {
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SYM,&screen_val);
guiHandleKeyboard(screen_val);
}
break;
case SCREEN_EVENT_MTOUCH_TOUCH:
rc = screen_get_mtouch_event(screen_event, &mtouch_event, 0);
// fprintf(stderr,"Received touch\n");
if(!rc){
guiHandleTouch(mtouch_event);
}
break;
case SCREEN_EVENT_MTOUCH_MOVE:
rc = screen_get_mtouch_event(screen_event, &mtouch_event, 0);
if (rc)
{
fprintf(stderr, "Error: failed to get mtouch event\n");
}else{
if(last_touch[0] && last_touch[1]) {
guiHandlePan(mtouch_event,last_touch);
// fprintf(stderr,"Pan %d %d -> cursor: %i\n\n",mtouch_event.x,mtouch_event.y,curSelCursor);
}
last_touch[0] = mtouch_event.x;
last_touch[1] = mtouch_event.y;
}
break;
case SCREEN_EVENT_MTOUCH_RELEASE:
last_touch[0] = 0;
last_touch[1] = 0;
break;
}
}
void handleNavigatorEvent(bps_event_t *event){
switch( bps_event_get_code(event) ) {
case NAVIGATOR_EXIT:
exit_application = 1;
break;
case NAVIGATOR_SWIPE_DOWN:
guiHandleSwipeDown();
break;
case NAVIGATOR_WINDOW_INACTIVE:
{
fprintf(stderr,"GUI deactivated\n");
bps_event_t *activation_event = NULL;
//Wait for NAVIGATOR_WINDOW_ACTIVE event
for (;;) {
int rc = bps_get_event(&activation_event, -1);
if(rc){
fprintf(stderr,"Could not receive activation event.\n");
exit_application = 1;
break;
}else{
if (bps_event_get_code(activation_event)
== NAVIGATOR_WINDOW_ACTIVE) {
fprintf(stderr,"GUI activated\n");
break;
}
}
}
}
break;
}
}
int main(int argc, char **argv) {
int rc;
screen_create_context(&screen_cxt, 0);
bps_initialize();//Initialize BPS library
if (BPS_SUCCESS != navigator_request_events(0)) {//...and navigator events...
fprintf(stderr, "navigator_request_events failed\n");
screen_destroy_context(screen_cxt);
return 0;
}
if (BPS_SUCCESS != navigator_rotation_lock(true)) {//lock orientation
fprintf(stderr, "navigator_rotation_lock failed\n");
screen_destroy_context(screen_cxt);
return 0;
}
if (BPS_SUCCESS != dialog_request_events(0)) {//dialog events...
fprintf(stderr, "dialog_request_events failed\n");
screen_destroy_context(screen_cxt);
return 0;
}
if (BPS_SUCCESS != screen_request_events(screen_cxt)) {//tell bps that events will be needed
fprintf(stderr, "screen_request_events failed\n");
screen_destroy_context(screen_cxt);
return 0;
}
if (EXIT_SUCCESS != init()) {//Initialize app data
fprintf(stderr, "Unable to initialize app logic\n");
screen_destroy_context(screen_cxt);
return 0;
}
if (EXIT_SUCCESS != guiInit()) {//Initialize gui
fprintf(stderr, "Unable to initialize gui\n");
screen_destroy_context(screen_cxt);
return 0;
}
render();
while (!exit_application) {
bps_event_t *event = NULL;
for(;;) {
rc = bps_get_event(&event, 0);
if (event) {
int domain = bps_event_get_domain(event);
if (domain == screen_get_domain()) {
handleScreenEvent(event);
} else if ( domain == navigator_get_domain() ){
handleNavigatorEvent(event);
}
render();//only render when events have occured
}else{
break;
}
}
}
screen_stop_events(screen_cxt);
// dialog_stop_events(screen_cxt);
// navigator_stop_events(screen_cxt);
bps_shutdown();
term();
screen_destroy_context(screen_cxt);
return 0;
}
| 29.395455 | 98 | 0.670172 | [
"render"
] |
73df072b5376d6535305d51a8072d4263566a800 | 604 | hpp | C++ | Vector.hpp | AeneasTews/vectors | c02d4167a79e76664431d0f18f08013e543c32ba | [
"MIT"
] | null | null | null | Vector.hpp | AeneasTews/vectors | c02d4167a79e76664431d0f18f08013e543c32ba | [
"MIT"
] | null | null | null | Vector.hpp | AeneasTews/vectors | c02d4167a79e76664431d0f18f08013e543c32ba | [
"MIT"
] | null | null | null | //
// Vector.hpp
// vectorMaths
//
// Created by Aeneas Tews on 02.02.22.
//
#ifndef Vector_hpp
#define Vector_hpp
#include <stdio.h>
#include <string>
#include "Vector2.hpp"
#include "Vector3.hpp"
class Vector {
private:
double *directions;
int size;
public:
Vector(double vector[], int size);
Vector(Vector2 v);
Vector(Vector3 v);
double calcLength();
Vector normalize();
std::string getVector();
void setAxis(int axis, double value);
double getAxis(int axis);
Vector multiply(double scalar);
Vector add(Vector v);
};
#endif /* Vector_hpp */
| 17.257143 | 41 | 0.652318 | [
"vector"
] |
73df21e1021f1ecdca7f76375c69fa0a1e468dac | 13,526 | cpp | C++ | examples/cconv/source/main.cpp | soasis/cuneicode | 0f9f4711b659eaeafeb63a88a9e407ad2400547b | [
"Apache-2.0"
] | 4 | 2021-11-21T00:19:51.000Z | 2022-03-18T16:43:12.000Z | examples/cconv/source/main.cpp | soasis/cuneicode | 0f9f4711b659eaeafeb63a88a9e407ad2400547b | [
"Apache-2.0"
] | 2 | 2021-11-20T22:33:49.000Z | 2021-11-21T08:06:57.000Z | examples/cconv/source/main.cpp | soasis/cuneicode | 0f9f4711b659eaeafeb63a88a9e407ad2400547b | [
"Apache-2.0"
] | null | null | null | // =============================================================================
//
// ztd.cuneicode
// Copyright © 2021 JeanHeyd "ThePhD" Meneide and Shepherd's Oasis, LLC
// Contact: opensource@soasis.org
//
// Commercial License Usage
// Licensees holding valid commercial ztd.cuneicode 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 Shepherd's Oasis, LLC.
// For licensing terms and conditions see your agreement. For
// further information contact opensource@soasis.org.
//
// Apache License Version 2 Usage
// Alternatively, this file may be used under the terms of 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 <ztd/cuneicode.h>
#include <cconv/handler.hpp>
#include <cconv/def.hpp>
#include <cconv/usage.hpp>
#include <cconv/io.hpp>
#include <cconv/options.hpp>
#include <ztd/idk/utf8_startup_hook.hpp>
#include <ztd/idk/size.h>
#include <string>
#include <variant>
#include <memory>
#include <vector>
#include <optional>
#include <set>
#include <clocale>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <algorithm>
ztd::utf8_startup_hook utf8_startup {};
struct cnc_conversion_deleter {
void operator()(cnc_conversion* handle) const {
cnc_delete(handle);
}
};
struct cnc_registry_deleter {
void operator()(cnc_conversion_registry* handle) const {
cnc_delete_registry(handle);
}
};
int main(int argc, char* argv[]) {
std::size_t total_input_read = 0;
std::size_t total_output_written = 0;
options opt;
#if ZTD_IS_ON(ZTD_DEBUG_I_)
try {
#endif // top-level try
std::optional<std::string> maybe_error_message = parse_options(opt, argc, argv);
if (maybe_error_message.has_value()) {
if (!opt.silent) {
const std::string& err = *maybe_error_message;
std::cerr << err << std::endl;
}
return exit_option_failure;
}
if (opt.input_files.empty()) {
opt.input_files.push_back(stdin_read);
}
if (opt.show_version) {
print_version();
return exit_success;
}
if (opt.show_help) {
print_help();
return exit_success;
}
if (opt.verbose) {
std::cout << "[info] cconv v0.0.0 invoked with " << argc << " arguments." << std::endl;
std::cout << "[info] Current working directory is \"" << std::filesystem::current_path().string()
<< "\"." << std::endl;
}
if (opt.verbose && argc > 0) {
std::cout << "[info] 1st command line argument is \"" << argv[0] << "\"." << std::endl;
}
// open the registry
std::unique_ptr<cnc_conversion_registry, cnc_registry_deleter> registry = nullptr;
{
cnc_conversion_registry* raw_registry = registry.get();
cnc_registry_options registry_options = CNC_REGISTRY_OPTIONS_DEFAULT;
cnc_open_error err = cnc_new_registry(&raw_registry, registry_options);
if (err != CNC_OPEN_ERROR_OKAY) {
if (!opt.silent) {
std::cerr << "[error] Could not open a conversion registry (error code: " << err << ")."
<< std::endl;
}
return exit_registry_open_failure;
}
registry.reset(raw_registry);
}
// if we are just listing encodings, do so and then stop here.
if (opt.list_encodings) {
print_encoding_list(registry.get());
return exit_success;
}
// open up the conversion specifier
std::unique_ptr<cnc_conversion, cnc_conversion_deleter> conversion = nullptr;
cnc_conversion_info info = {};
{
cnc_conversion* raw_conversion = conversion.get();
std::size_t from_size = opt.from_code.size();
const ztd_char8_t* from_data = opt.from_code.data();
std::size_t to_size = opt.to_code.size();
const ztd_char8_t* to_data = opt.to_code.data();
cnc_conversion_registry* __registry = registry.get();
cnc_open_error err
= cnc_new_n(__registry, from_size, from_data, to_size, to_data, &raw_conversion, &info);
if (err != CNC_OPEN_ERROR_OKAY) {
if (!opt.silent) {
std::cerr << "[error] Could not open a conversion from \"" << opt.from_code << "\" to \""
<< opt.to_code << "\"." << std::endl;
}
return exit_open_failure;
}
if (opt.verbose) {
std::cout << "[info] Opened a conversion from \""
<< utf8string_view(info.from_code_data, info.from_code_size) << "\" to \""
<< utf8string_view(info.to_code_data, info.to_code_size) << "\"";
if (info.is_indirect) {
std::cout << " (converting indirectly from \""
<< utf8string_view(info.from_code_data, info.from_code_size) << "\" to \""
<< utf8string_view(info.indirect_code_data, info.indirect_code_size) << "\" to \""
<< utf8string_view(info.to_code_data, info.to_code_size) << "\").";
}
else {
std::cout << " (converting directly from \""
<< utf8string_view(info.from_code_data, info.from_code_size) << "\" to \""
<< utf8string_view(info.to_code_data, info.to_code_size) << "\").";
}
std::cout << std::endl;
}
conversion.reset(raw_conversion);
}
// make sure we have an output to write to
std::optional<std::ofstream> maybe_file_output;
utf8string output_file_name;
if (opt.maybe_output_file_name) {
output_file_name = *opt.maybe_output_file_name;
std::string file_name
= std::string(reinterpret_cast<const char*>(output_file_name.data()), output_file_name.size());
if (file_name.find('\0') != std::string::npos) {
if (!opt.silent) {
std::cerr << "[error] File name contains embedded null: cannot open output file \""
<< output_file_name << "\" properly." << std::endl;
}
return exit_file_open_failure;
}
std::ofstream target_output(file_name.c_str(), std::ios::binary | std::ios::app);
if (!target_output.is_open() || !target_output.good()) {
if (!opt.silent) {
std::cerr << "[error] Could not open output file (binary, append) \"" << output_file_name
<< "\"." << std::endl;
}
return exit_file_open_failure;
}
maybe_file_output.emplace(std::move(target_output));
}
else {
output_file_name.assign(reinterpret_cast<const ztd_char8_t*>(+"<stdout>"), 8);
}
std::ostream& output_stream = maybe_file_output.has_value() ? *maybe_file_output : std::cout;
if (opt.verbose) {
std::cout << "[info] Writing to \"" << output_file_name << "\"." << std::endl;
std::cout << "[info] Attempting to convert from \"" << opt.from_code << "\" to \"" << opt.to_code
<< "\" for " << opt.input_files.size() << " inputs." << std::endl;
}
std::size_t buffer_size = opt.maybe_buffer_size.value_or(ZTD_INTERMEDIATE_BUFFER_SUGGESTED_BYTE_SIZE_I_);
std::vector<unsigned char> input {};
std::vector<unsigned char> output(buffer_size);
unsigned char error_output[ZTD_INTERMEDIATE_BUFFER_SUGGESTED_BYTE_SIZE_I_] {};
unsigned char* const initial_error_output_data = error_output;
const size_t initial_error_output_size = ztd_c_array_size(error_output);
{
cnc_conversion* raw_conversion = conversion.get();
for (std::size_t i = 0; i < opt.input_files.size(); ++i) {
std::variant<utf8string, stdin_read_tag>& input_file_or_stdin = opt.input_files[i];
auto success = read_input_into(input, input_file_or_stdin, opt.verbose, opt.silent);
if (success.maybe_return_code) {
return *success.maybe_return_code;
}
const utf8string& input_file_name = success.input_file_name;
if (opt.verbose) {
std::cout << "[info] Read " << input.size() << " bytes from \"" << input_file_name << "\"."
<< std::endl;
}
const unsigned char* const initial_input_data = input.data();
const size_t initial_input_size = input.size();
total_input_read += initial_input_size;
const unsigned char* input_data = initial_input_data;
size_t input_size = initial_input_size;
unsigned char* const initial_output_data = output.data();
const std::size_t initial_output_size = output.size();
for (; input_size > 0;) {
unsigned char* output_data = initial_output_data;
std::size_t output_size = initial_output_size;
std::size_t error_output_written = 0;
const cnc_mcerror convert_err
= cnc_conv(raw_conversion, &output_size, &output_data, &input_size, &input_data);
const std::size_t output_written = initial_output_size - output_size;
switch (convert_err) {
case CNC_MCERROR_INCOMPLETE_INPUT:
if (!opt.silent) {
std::cerr << "[error] Could not convert input data from \"" << opt.from_code
<< "\" to \"" << opt.to_code << "\" because the input data is incomplete."
<< std::endl;
}
return exit_conversion_failure;
case CNC_MCERROR_INVALID_SEQUENCE: {
unsigned char* error_output_data = initial_error_output_data;
size_t error_output_size = initial_error_output_size;
auto handler_visitor = [&](auto&& arg) {
return arg(info, raw_conversion, &error_output_size, &error_output_data, &input_size,
&input_data);
};
// okay, handle it with the handler
bool can_continue_processing = std::visit(handler_visitor, opt.error_handler);
if (!can_continue_processing) {
if (!opt.silent) {
std::cerr << "[error] Could not convert input data from \"" << opt.from_code
<< "\" to \"" << opt.to_code << "\"." << std::endl;
}
return exit_conversion_failure;
}
error_output_written = initial_error_output_size - error_output_size;
} break;
case CNC_MCERROR_OKAY:
case CNC_MCERROR_INSUFFICIENT_OUTPUT:
default:
break;
}
// write bytes exactly by using `.write` instead of formatted I/O
const std::size_t combined_written = (output_written + error_output_written);
const bool must_write_output = output_written != 0;
const bool must_write_error_output = error_output_written != 0;
if (must_write_output) {
output_stream.write(reinterpret_cast<const char*>(initial_output_data),
static_cast<std::streamsize>(output_written));
if (!output_stream) {
if (!opt.silent) {
std::cerr << "[error] Could not write data to output file (\""
<< output_file_name << "\")." << std::endl;
}
return exit_file_write_failure;
}
output_stream.flush();
if (!output_stream) {
if (!opt.silent) {
std::cerr << "[error] Could not flush data to output file (\""
<< output_file_name << "\")." << std::endl;
}
return exit_file_write_failure;
}
if (opt.verbose) {
std::cout << "[info] Wrote " << output_written << " bytes of output to \""
<< output_file_name << "\" with " << input_size << " bytes left to read."
<< std::endl;
}
}
if (must_write_error_output) {
output_stream.write(
reinterpret_cast<const char*>(initial_error_output_data), error_output_written);
if (!output_stream) {
if (!opt.silent) {
std::cerr << "[error] Could not write data produced by the error handler to "
"output file (\""
<< output_file_name << "\")." << std::endl;
}
return exit_file_write_failure;
}
output_stream.flush();
if (!output_stream) {
if (!opt.silent) {
std::cerr << "[error] Could not flush data to output file (\""
<< output_file_name << "\")." << std::endl;
}
return exit_file_write_failure;
}
if (opt.verbose) {
std::cout << "[info] Wrote " << error_output_written << " bytes of error to \""
<< output_file_name << "\" with " << input_size << " bytes left to read."
<< std::endl;
}
}
total_output_written += combined_written;
}
}
}
#if ZTD_IS_ON(ZTD_DEBUG_I_)
}
catch (...) {
if (!opt.silent)
std::cerr
<< "[error] An explosive, unexpected error (exception) occurred and the program must terminate."
<< std::endl;
return 5;
}
#endif // top-level try
if (opt.verbose) {
std::cout << "[info] cconv completed successfully. Read a total of " << total_input_read
<< " bytes and wrote a total of " << total_output_written << " bytes" << std::endl;
}
return exit_success;
}
| 39.899705 | 121 | 0.612376 | [
"vector"
] |
73e47ce3597c5fdbd8e35def63f149dfffa68c3a | 2,105 | cpp | C++ | source/BaseObservable.cpp | vt4a2h/prcxx | 04794048f21cec548fa750b78239f920eef1bb60 | [
"MIT"
] | 1 | 2022-01-04T17:55:55.000Z | 2022-01-04T17:55:55.000Z | source/BaseObservable.cpp | vt4a2h/prcxx | 04794048f21cec548fa750b78239f920eef1bb60 | [
"MIT"
] | null | null | null | source/BaseObservable.cpp | vt4a2h/prcxx | 04794048f21cec548fa750b78239f920eef1bb60 | [
"MIT"
] | null | null | null | //
// MIT License
//
// Copyright (c) 2020-present Vitaly Fanaskov
//
// prcxx -- Yet another C++ property library
// Project home: https://github.com/vt4a2h/prcxx
//
// See LICENSE file for the further details.
//
#include "prcxx/BaseObservable.hpp"
#include "prcxx/ActiveEvaluationChain.hpp"
#include "prcxx/EvaluationChain.hpp"
#include <range/v3/view/filter.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/action/push_back.hpp>
#include <range/v3/algorithm/for_each.hpp>
namespace prcxx {
namespace r = ranges;
namespace rv = r::views;
namespace ra = r::actions;
static const auto validObservers = rv::filter([](auto &&o) { return !o.expired(); });
BaseObservable::BaseObservable(std::any v)
: value(std::move(v))
{}
const Observers &BaseObservable::get_observers() const
{
return this->observers;
}
void BaseObservable::copy_observers_from(const IObservable &observable)
{
auto src = observable.get_observers() | validObservers;
observers.reserve(r::distance(src) + observers.size());
ra::push_back(observers, src);
}
void BaseObservable::invalidate()
{
auto toRefs = rv::transform([](auto &&o) { return o.lock().get(); });
r::for_each(observers | validObservers | toRefs, &IObservable::invalidate);
}
EvaluationChain &BaseObservable::active_chain()
{
return ActiveEvaluationChain::get();
}
void BaseObservable::pre_process_active_chain()
{
observers.clear();
if (!active_chain().empty()) {
if (auto top = active_chain().top(); !top.expired())
observers.emplace_back(top);
} else {
active_chain().push(this->as_weak_ptr());
}
}
void BaseObservable::post_process_active_chain()
{
if (auto wr = active_chain().top(); !wr.expired() && wr.lock().get() == this)
active_chain().pop();
}
IObservableWeakPtr BaseObservable::as_weak_ptr() noexcept
{
return this->weak_from_this();
}
} // namespace prcxx
| 26.64557 | 89 | 0.630879 | [
"transform"
] |
73eeebefed1c2ca2fc254cb6b9e8b7559e9be606 | 1,912 | cxx | C++ | Plugins/Manta/examples/TPlane.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | Plugins/Manta/examples/TPlane.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | Plugins/Manta/examples/TPlane.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | #include "vtkBMPReader.h"
#include "vtkTexture.h"
#include "vtkPlaneSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkProperty.h"
#include "vtkCamera.h"
#include "vtkToolkits.h"
#include <string>
int main()
{
// Load in the texture map. A texture is any unsigned char image. If it
// is not of this type, you will have to map it through a lookup table
// or by using vtkImageShiftScale.
string filename = VTK_DATA_ROOT;
filename += "/Data/masonry.bmp";
vtkBMPReader *bmpReader = vtkBMPReader::New();
bmpReader->SetFileName(filename.c_str());
vtkTexture *atext = vtkTexture::New();
atext->SetInputConnection(bmpReader->GetOutputPort());
atext->InterpolateOn();
// Create a plane source and actor. The vtkPlanesSource generates
// texture coordinates.
vtkPlaneSource *plane = vtkPlaneSource::New();
vtkPolyDataMapper *planeMapper = vtkPolyDataMapper::New();
planeMapper->SetInputConnection(plane->GetOutputPort());
vtkActor *planeActor = vtkActor::New();
planeActor->SetMapper(planeMapper);
planeActor->SetTexture(atext);
// Create the RenderWindow, Renderer and both Actors
vtkRenderer *ren = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(ren);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
// Add the actors to the renderer, set the background and size
ren->AddActor(planeActor);
ren->SetBackground(0.1, 0.2, 0.4);
renWin->SetSize(500, 500);
ren->ResetCamera();
vtkCamera *camera = ren->GetActiveCamera();
camera->Elevation(-30);
camera->Roll(-20);
ren->ResetCameraClippingRange();
iren->Initialize();
renWin->Render();
iren->Start();
}
| 32.40678 | 75 | 0.699268 | [
"render"
] |
73f5f6eb1a194665d1b749d0cd5616504c438198 | 6,819 | cpp | C++ | compute/ARMComputeEx/src/runtime/CL/functions/CLSplitVEx.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | compute/ARMComputeEx/src/runtime/CL/functions/CLSplitVEx.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | compute/ARMComputeEx/src/runtime/CL/functions/CLSplitVEx.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (c) 2017 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "arm_compute/runtime/CL/functions/CLSplitVEx.h"
#include "support/ToolchainSupport.h"
#include "arm_compute/core/Error.h"
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/CL/ICLTensor.h"
#include "arm_compute/core/TensorInfo.h"
#include "arm_compute/core/Types.h"
#include "arm_compute/core/Validate.h"
#include "arm_compute/core/utils/misc/ShapeCalculator.h"
#include "arm_compute/runtime/CL/CLScheduler.h"
#include "src/core/helpers/AutoConfiguration.h"
#include <cassert>
using namespace arm_compute;
namespace
{
Status validate_arguments(const ICLTensor *size_splits, const std::vector<ICLTensor *> &outputs,
unsigned int num_splits)
{
ARM_COMPUTE_RETURN_ERROR_ON_MSG(size_splits->info()->num_dimensions() != 1,
"size_splits must be a 1-D tensor.");
ARM_COMPUTE_RETURN_ERROR_ON_MSG(num_splits != outputs.size(),
"Number of output tensors does not match number of splits.");
return Status{};
}
Status validate_slices(const ITensorInfo *input, const std::vector<ITensorInfo *> &outputs,
uint32_t split_dim)
{
ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input);
ARM_COMPUTE_RETURN_ERROR_ON(split_dim >= input->num_dimensions());
ARM_COMPUTE_RETURN_ERROR_ON(outputs.size() < 2);
// Start/End coordinates
Coordinates start_coords;
Coordinates end_coords;
for (unsigned int d = 0; d < input->num_dimensions(); ++d)
{
end_coords.set(d, -1);
}
unsigned int axis_offset = 0;
// Validate output tensors
for (const auto &output : outputs)
{
ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(output);
// Get output shape
const TensorShape output_shape = output->tensor_shape();
ARM_COMPUTE_RETURN_ERROR_ON(output_shape.total_size() == 0);
const size_t axis_split_step = output_shape[split_dim];
// Output auto inizialitation if not yet initialized
TensorInfo tmp_output_info = *output->clone();
auto_init_if_empty(tmp_output_info,
input->clone()->set_is_resizable(true).set_tensor_shape(output_shape));
// Update coordinate on axis
start_coords.set(split_dim, axis_offset);
end_coords.set(split_dim, axis_offset + axis_split_step);
ARM_COMPUTE_RETURN_ON_ERROR(CLSlice::validate(input, output, start_coords, end_coords));
axis_offset += axis_split_step;
}
return Status{};
}
void configure_slices(const ICLTensor *input, const std::vector<ICLTensor *> &outputs,
std::vector<CLSlice> &_slice_functions, uint32_t split_dim)
{
unsigned int axis_offset = 0;
// Start/End coordinates
Coordinates start_coords;
Coordinates end_coords;
for (unsigned int d = 0; d < input->info()->num_dimensions(); ++d)
{
end_coords.set(d, -1);
}
int out_iter = 0;
for (const auto &output : outputs)
{
const TensorShape output_shape = output->info()->tensor_shape();
auto op_size = output_shape.total_size();
if (!op_size)
{
continue;
}
assert(op_size != 0);
assert(split_dim <= output_shape.num_dimensions());
const size_t axis_split_step = output_shape[split_dim];
// Output auto inizialitation if not yet initialized
TensorInfo tmp_output_info = *output->info()->clone();
auto_init_if_empty(
tmp_output_info,
input->info()->clone()->set_is_resizable(true).set_tensor_shape(output_shape));
// Update coordinate on axis
start_coords.set(split_dim, axis_offset);
end_coords.set(split_dim, axis_offset + axis_split_step);
// Configure slice function
_slice_functions[out_iter].configure(input, output, start_coords, end_coords);
// Set valid region from shape
outputs[out_iter++]->info()->set_valid_region(ValidRegion(Coordinates(), output_shape));
axis_offset += axis_split_step;
}
}
} // namespace
CLSplitVEx::CLSplitVEx()
: _input(nullptr), _size_splits(nullptr), _outputs(), _num_splits(0), _slice_functions()
{
}
void CLSplitVEx::configure(const ICLTensor *input, const ICLTensor *size_splits, uint32_t split_dim,
const std::vector<ICLTensor *> &outputs, unsigned int num_splits)
{
ARM_COMPUTE_ERROR_ON_NULLPTR(input, size_splits);
ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(size_splits, outputs, num_splits));
_input = input;
_size_splits = size_splits;
_outputs = outputs;
_num_splits = num_splits;
// Create tensor slices
_slice_functions.resize(_num_splits);
// Extract output tensor info
std::vector<ITensorInfo *> outputs_info;
for (auto &output : _outputs)
{
ARM_COMPUTE_ERROR_ON_NULLPTR(output);
outputs_info.emplace_back(output->info());
}
// Validate slices
ARM_COMPUTE_ERROR_THROW_ON(validate_slices(_input->info(), outputs_info, split_dim));
// Configure slices
configure_slices(_input, _outputs, _slice_functions, split_dim);
}
void CLSplitVEx::run()
{
// execute the slices
for (unsigned i = 0; i < _outputs.size(); ++i)
{
_slice_functions[i].run();
}
}
| 34.439394 | 100 | 0.7199 | [
"shape",
"vector"
] |
73fee15e9c13b70215ca813c10376938c275c26a | 2,076 | cpp | C++ | applications/DelaunayMeshingApplication/delaunay_meshing_application_variables.cpp | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 2 | 2020-04-30T19:13:08.000Z | 2021-04-14T19:40:47.000Z | applications/DelaunayMeshingApplication/delaunay_meshing_application_variables.cpp | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 1 | 2020-04-30T19:19:09.000Z | 2020-05-02T14:22:36.000Z | applications/DelaunayMeshingApplication/delaunay_meshing_application_variables.cpp | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 1 | 2020-06-12T08:51:24.000Z | 2020-06-12T08:51:24.000Z | //
// Project Name: KratosDelaunayMeshingApplication $
// Created by: $Author: JMCarbonell $
// Last modified by: $Co-Author: $
// Date: $Date: April 2018 $
// Revision: $Revision: 0.0 $
//
//
#include "delaunay_meshing_application_variables.h"
namespace Kratos
{
///@name Type Definitions
///@{
typedef array_1d<double,3> Vector3;
typedef array_1d<double,6> Vector6;
typedef Kratos::weak_ptr<Node<3> > NodeWeakPtrType;
typedef Kratos::weak_ptr<Element> ElementWeakPtrType;
typedef Kratos::weak_ptr<Condition> ConditionWeakPtrType;
typedef WeakPointerVector<Node<3> > NodeWeakPtrVectorType;
typedef WeakPointerVector<Element> ElementWeakPtrVectorType;
typedef WeakPointerVector<Condition> ConditionWeakPtrVectorType;
///@}
///@name Kratos Globals
///@{
//Create Variables
//geometrical definition
KRATOS_CREATE_3D_VARIABLE_WITH_COMPONENTS( OFFSET )
KRATOS_CREATE_VARIABLE(double, SHRINK_FACTOR )
//domain definition
KRATOS_CREATE_VARIABLE(bool, INITIALIZED_DOMAINS )
KRATOS_CREATE_VARIABLE(double, MESHING_STEP_TIME )
KRATOS_CREATE_VARIABLE(std::string, MODEL_PART_NAME )
KRATOS_CREATE_VARIABLE(std::vector<std::string>, MODEL_PART_NAMES )
//boundary definition
KRATOS_CREATE_VARIABLE(int, RIGID_WALL )
//custom neighbor and masters
KRATOS_CREATE_VARIABLE(NodeWeakPtrType, MASTER_NODE )
KRATOS_CREATE_VARIABLE(ElementWeakPtrType, MASTER_ELEMENT )
KRATOS_CREATE_VARIABLE(ConditionWeakPtrType, MASTER_CONDITION )
KRATOS_CREATE_VARIABLE(NodeWeakPtrVectorType, MASTER_NODES )
KRATOS_CREATE_VARIABLE(ElementWeakPtrVectorType, MASTER_ELEMENTS )
KRATOS_CREATE_VARIABLE(ConditionWeakPtrVectorType, MASTER_CONDITIONS )
//condition variables
KRATOS_CREATE_VARIABLE(ConditionContainerType, CHILDREN_CONDITIONS )
//mesher criteria
KRATOS_CREATE_VARIABLE(double, MEAN_ERROR )
///@}
}
| 32.4375 | 74 | 0.705684 | [
"vector"
] |
bab7cee191e8253770906c518f9061a3558a4970 | 1,183 | hpp | C++ | motion_planning/ugv_planning/hybrid_astar_test/include/hybrid_astar_test/navigation/navigation_pure_pursuit.hpp | robin-shaun/xtdrone | f255d001e2b83e2dd54e8086f881c58a4efd53ee | [
"MIT"
] | null | null | null | motion_planning/ugv_planning/hybrid_astar_test/include/hybrid_astar_test/navigation/navigation_pure_pursuit.hpp | robin-shaun/xtdrone | f255d001e2b83e2dd54e8086f881c58a4efd53ee | [
"MIT"
] | null | null | null | motion_planning/ugv_planning/hybrid_astar_test/include/hybrid_astar_test/navigation/navigation_pure_pursuit.hpp | robin-shaun/xtdrone | f255d001e2b83e2dd54e8086f881c58a4efd53ee | [
"MIT"
] | null | null | null | #ifndef HYBRID_ASTAR_TEST_NAVIGATION_NAVIGATION_PURE_PURSUIT_HPP
#define HYBRID_ASTAR_TEST_NAVIGATION_NAVIGATION_PURE_PURSUIT_HPP
#include <ros/ros.h>
#include <Eigen/Dense>
#include <mutex>
#include <thread>
#include <memory>
#include "hybrid_astar_test/subscriber/start_subscriber.hpp"
#include "hybrid_astar_test/subscriber/path_subscriber.hpp"
class PurePursuitControl{
public:
PurePursuitControl(ros::NodeHandle& nh);
~PurePursuitControl();
public:
bool Run();
private:
Eigen::Vector2f CalculationVelocity(const Eigen::Vector3f& last_pose, const Eigen::Vector3f& now_pose, float delta_time);
Eigen::Vector2f CalculationAcceleration(const Eigen::Vector2f& last_v, const Eigen::Vector2f& now_v, const Eigen::Vector3f& last_pose, const Eigen::Vector3f& now_pose);
private:
std::shared_ptr<StartSubscriber> localization_subscriber_ptr_;
std::shared_ptr<PathSubscriber> path_subscriber_ptr_;
private:
ros::NodeHandle nh_;
std::mutex global_mtx_;
Eigen::VectorXf start_point(6);
Eigen::VectorXf robot_localization(7); // x y yaw liner_v angle_v liner_acc angle_acc
std::vector<Eigen::Vector3f> Trajectory;
};
#endif | 29.575 | 172 | 0.775148 | [
"vector"
] |
babccac12bee027aad00008b8f0250ddf02bf651 | 13,030 | hpp | C++ | http/src/network/protocol/http/server/connection/sync.hpp | mistafunk/cpp-netlib | 9412dbaf5996643c1daf579819e8187f04f8827b | [
"BSL-1.0"
] | null | null | null | http/src/network/protocol/http/server/connection/sync.hpp | mistafunk/cpp-netlib | 9412dbaf5996643c1daf579819e8187f04f8827b | [
"BSL-1.0"
] | null | null | null | http/src/network/protocol/http/server/connection/sync.hpp | mistafunk/cpp-netlib | 9412dbaf5996643c1daf579819e8187f04f8827b | [
"BSL-1.0"
] | null | null | null | // Copyright 2009 (c) Dean Michael Berris <dberris@google.com>
// Copyright 2009 (c) Tarroo, Inc.
// Adapted from Christopher Kholhoff's Boost.Asio Example, released under
// the Boost Software License, Version 1.0. (See acccompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NETWORK_HTTP_SERVER_SYNC_CONNECTION_HPP_
#define NETWORK_HTTP_SERVER_SYNC_CONNECTION_HPP_
#ifndef NETWORK_HTTP_SERVER_CONNECTION_BUFFER_SIZE
#define NETWORK_HTTP_SERVER_CONNECTION_BUFFER_SIZE 4096uL
#endif
#include <utility>
#include <iterator>
#include <boost/enable_shared_from_this.hpp>
#include <network/constants.hpp>
#include <network/protocol/http/server/request_parser.hpp>
#include <network/protocol/http/request.hpp>
#include <network/protocol/http/response.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/array.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <functional>
#include <mutex>
namespace network {
namespace http {
#ifndef NETWORK_NO_LIB
extern void parse_version(std::string const& partial_parsed,
boost::fusion::tuple<uint8_t, uint8_t>& version_pair);
extern void parse_headers(
std::string const& input,
std::vector<std::pair<std::string, std::string>>& container);
#endif
class sync_server_connection
: public boost::enable_shared_from_this<sync_server_connection> {
public:
sync_server_connection(boost::asio::io_service& service,
std::function<void(request const&, response&)> handler)
: service_(service),
handler_(handler),
socket_(service_),
wrapper_(service_) {}
boost::asio::ip::tcp::socket& socket() { return socket_; }
void start() {
using boost::asio::ip::tcp;
boost::system::error_code option_error;
// TODO make no_delay an option in server_options.
socket_.set_option(tcp::no_delay(true), option_error);
std::ostringstream ip_stream;
ip_stream << socket_.remote_endpoint().address().to_string() << ':'
<< socket_.remote_endpoint().port();
request_.set_source(ip_stream.str());
socket_.async_read_some(boost::asio::buffer(read_buffer_),
wrapper_.wrap(boost::bind(
&sync_server_connection::handle_read_data,
sync_server_connection::shared_from_this(),
method,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
}
private:
enum state_t {
method,
uri,
version,
headers,
body
};
void handle_read_data(state_t state,
boost::system::error_code const& ec,
std::size_t bytes_transferred) {
if (!ec) {
boost::logic::tribool parsed_ok;
boost::iterator_range<buffer_type::iterator> result_range, input_range;
data_end = read_buffer_.begin();
std::advance(data_end, bytes_transferred);
switch (state) {
case method:
input_range = boost::make_iterator_range(new_start, data_end);
boost::fusion::tie(parsed_ok, result_range) =
parser_.parse_until(request_parser::method_done, input_range);
if (!parsed_ok) {
client_error();
break;
} else if (parsed_ok == true) {
std::string method;
swap(partial_parsed, method);
method.append(boost::begin(result_range), boost::end(result_range));
boost::trim(method);
request_.set_method(method);
new_start = boost::end(result_range);
// Determine whether we're going to need to parse the body of the
// request. All we do is peek at the first character of the method
// to determine whether it's a POST or a PUT.
read_body_ = method.size() ? method[0] == 'P' : false;
} else {
partial_parsed.append(boost::begin(result_range),
boost::end(result_range));
new_start = read_buffer_.begin();
read_more(method);
break;
}
case uri:
input_range = boost::make_iterator_range(new_start, data_end);
boost::fusion::tie(parsed_ok, result_range) =
parser_.parse_until(request_parser::uri_done, input_range);
if (!parsed_ok) {
client_error();
break;
} else if (parsed_ok == true) {
std::string destination;
swap(partial_parsed, destination);
destination.append(boost::begin(result_range),
boost::end(result_range));
boost::trim(destination);
request_.set_destination(destination);
new_start = boost::end(result_range);
} else {
partial_parsed.append(boost::begin(result_range),
boost::end(result_range));
new_start = read_buffer_.begin();
read_more(uri);
break;
}
case version:
input_range = boost::make_iterator_range(new_start, data_end);
boost::fusion::tie(parsed_ok, result_range) =
parser_.parse_until(request_parser::version_done, input_range);
if (!parsed_ok) {
client_error();
break;
} else if (parsed_ok == true) {
boost::fusion::tuple<uint8_t, uint8_t> version_pair;
partial_parsed.append(boost::begin(result_range),
boost::end(result_range));
parse_version(partial_parsed, version_pair);
request_.set_version_major(boost::fusion::get<0>(version_pair));
request_.set_version_minor(boost::fusion::get<1>(version_pair));
new_start = boost::end(result_range);
partial_parsed.clear();
} else {
partial_parsed.append(boost::begin(result_range),
boost::end(result_range));
new_start = read_buffer_.begin();
read_more(version);
break;
}
case headers:
input_range = boost::make_iterator_range(new_start, data_end);
boost::fusion::tie(parsed_ok, result_range) =
parser_.parse_until(request_parser::headers_done, input_range);
if (!parsed_ok) {
client_error();
break;
} else if (parsed_ok == true) {
partial_parsed.append(boost::begin(result_range),
boost::end(result_range));
std::vector<std::pair<std::string, std::string>> headers;
parse_headers(partial_parsed, headers);
for (std::vector<
std::pair<std::string, std::string>>::const_iterator it =
headers.begin();
it != headers.end(); ++it) {
request_.append_header(it->first, it->second);
}
new_start = boost::end(result_range);
if (read_body_) {} else {
response response_;
handler_(request_, response_);
flatten_response();
std::vector<boost::asio::const_buffer> response_buffers(
output_buffers_.size());
std::transform(output_buffers_.begin(),
output_buffers_.end(),
response_buffers.begin(),
[](buffer_type const& buffer) {
return boost::asio::const_buffer(buffer.data(), buffer.size());
});
boost::asio::async_write(
socket_,
response_buffers,
wrapper_.wrap(
boost::bind(&sync_server_connection::handle_write,
sync_server_connection::shared_from_this(),
boost::asio::placeholders::error)));
}
return;
} else {
partial_parsed.append(boost::begin(result_range),
boost::end(result_range));
new_start = read_buffer_.begin();
read_more(headers);
break;
}
default:
BOOST_ASSERT(
false &&
"This is a bug, report to the cpp-netlib devel mailing list!");
std::abort();
}
} else {
error_encountered = boost::in_place<boost::system::system_error>(ec);
}
}
void handle_write(boost::system::error_code const& ec) {
// First thing we do is clear out the output buffers.
output_buffers_.clear();
if (ec) {
// TODO maybe log the error here.
}
}
void client_error() {
static char const bad_request[] =
"HTTP/1.0 400 Bad Request\r\nConnection: close\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nBad Request.";
boost::asio::async_write(
socket(),
boost::asio::buffer(bad_request, strlen(bad_request)),
wrapper_.wrap(
boost::bind(&sync_server_connection::client_error_sent,
sync_server_connection::shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
}
void client_error_sent(boost::system::error_code const& ec,
std::size_t bytes_transferred) {
if (!ec) {
boost::system::error_code ignored;
socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored);
socket().close(ignored);
} else {
error_encountered = boost::in_place<boost::system::system_error>(ec);
}
}
void read_more(state_t state) {
socket_.async_read_some(boost::asio::buffer(read_buffer_),
wrapper_.wrap(boost::bind(
&sync_server_connection::handle_read_data,
sync_server_connection::shared_from_this(),
state,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
}
void flatten_response() {
uint16_t status = http::status(response_);
std::string status_message = http::status_message(response_);
headers_wrapper::container_type headers = network::headers(response_);
std::ostringstream status_line;
status_line << status << constants::space() << status_message
<< constants::space() << constants::http_slash()
<< "1.1" // TODO: make this a constant
<< constants::crlf();
segmented_write(status_line.str());
std::ostringstream header_stream;
auto it = std::begin(headers), end = std::end(headers);
for (; it != end; ++it) {
const auto& header = *it;
//for (auto const &header : headers) {
header_stream << header.first << constants::colon() << constants::space()
<< header.second << constants::crlf();
}
header_stream << constants::crlf();
segmented_write(header_stream.str());
bool done = false;
while (!done) {
buffer_type buffer;
response_.get_body([&done, &buffer](std::string::const_iterator start,
size_t length) {
if (!length)
done = true;
else {
std::string::const_iterator past_end = start;
std::advance(past_end, length);
std::copy(start, past_end, buffer.begin());
}
},
buffer.size());
if (!done)
output_buffers_.emplace_back(std::move(buffer));
}
}
void segmented_write(std::string data) {
while (!boost::empty(data)) {
buffer_type buffer;
auto end = std::copy_n(boost::begin(data), buffer.size(), buffer.begin());
data.erase(0, std::distance(buffer.begin(), end));
output_buffers_.emplace_back(std::move(buffer));
}
}
boost::asio::io_service& service_;
std::function<void(request const&, response&)> handler_;
boost::asio::ip::tcp::socket socket_;
boost::asio::io_service::strand wrapper_;
typedef boost::array<char,
NETWORK_HTTP_SERVER_CONNECTION_BUFFER_SIZE> buffer_type;
buffer_type read_buffer_;
buffer_type::iterator new_start, data_end;
request_parser parser_;
request request_;
response response_;
std::list<buffer_type> output_buffers_;
std::string partial_parsed;
boost::optional<boost::system::system_error> error_encountered;
bool read_body_;
};
} // namespace http
} // namespace network
#endif // NETWORK_HTTP_SERVER_SYNC_CONNECTION_HPP_
| 38.895522 | 126 | 0.587644 | [
"vector",
"transform"
] |
babd08ae8a7cab7c1c13d4aeab700baa723437c1 | 7,255 | cc | C++ | mindspore/ccsrc/backend/optimizer/somas/somas_solver_pre.cc | peng-zhihui/mindspore | 4e0bc761b228cece8b24a280f15b0915959071dc | [
"Apache-2.0"
] | 55 | 2020-12-17T10:26:06.000Z | 2022-03-28T07:18:26.000Z | mindspore/ccsrc/backend/optimizer/somas/somas_solver_pre.cc | 77zmf/mindspore | 4e0bc761b228cece8b24a280f15b0915959071dc | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/backend/optimizer/somas/somas_solver_pre.cc | 77zmf/mindspore | 4e0bc761b228cece8b24a280f15b0915959071dc | [
"Apache-2.0"
] | 14 | 2021-01-29T02:39:47.000Z | 2022-03-23T05:00:26.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
* 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 <cstdio>
#include <fstream>
#include <memory>
#include <string>
#include <utility>
#include "backend/optimizer/somas/somas_solver_core.h"
#include "backend/optimizer/somas/somas_solver_pre.h"
namespace mindspore {
namespace somas {
Status SomasSolverPre::Solving(const session::KernelGraph *graph,
std::unordered_map<size_t, SomasSolverTensorDescPtr> *ptensors,
std::vector<DynamicBitSet> *pConstraints, const vector<vector<size_t>> &continuous_v,
bool bVerifySolution, bool ball, SortingType sorting, FittingType fitting,
AlgorithmType algorithm) {
Status retval = SUCCESS;
try {
std::unordered_map<size_t, SomasSolverTensorDescPtr> &tensors = *ptensors;
MS_LOG(INFO) << "Filling in constraints matrix..";
uint32_t continuous_cnt = 0;
// creating S Lists
for (auto &aux : continuous_v) {
for (uint32_t i = 0; i < aux.size() - 1; i++) {
uint32_t index1 = aux[i];
uint32_t index2 = aux[i + 1];
if (NULL == tensors[index1]) {
MS_LOG(WARNING) << "NULL tensor received in continuous constraint (tensor index " << index1 << ")";
return FAILED;
}
if (NULL == tensors[index2]) {
MS_LOG(WARNING) << "NULL tensor received in continuous constraint (tensor index " << index2 << ")";
return FAILED;
}
if (tensors[index1]->right_)
MS_LOG(WARNING) << "Warning:tensor " << index1
<< " already has a right tensor (id: " << tensors[index1]->right_->index_;
if (tensors[index2]->left_)
MS_LOG(WARNING) << "Warning:tensor " << index2
<< " already has a left tensor (id: " << tensors[index2]->left_->index_;
tensors[index1]->right_ = tensors[index2];
tensors[index2]->left_ = tensors[index1];
continuous_cnt++;
}
}
continuous_cnt++;
std::shared_ptr<SomasSolverCore> pSolver = std::make_shared<SomasSolverCore>(tensors, pConstraints);
pSolver->SetAlgorithmStrategy(algorithm);
pSolver->SetSortingStrategy(sorting);
pSolver->SetFittingStrategy(fitting);
pSolver->SetAllStrategies(ball);
pSolver->VerifySolution(bVerifySolution);
if (SUCCESS == (pSolver->MemoryAllocationSolver())) {
max_offset_ = pSolver->GetUpperbound();
const double giga = 1024. * 1024. * 1024.;
MS_LOG(INFO) << "SomasSolver::Solving SUCCESS";
MS_LOG(INFO) << "SomasSolver::Solving RESULT: " << max_offset_ << " (" << max_offset_ / (giga) << " GB)";
}
auto context_ptr = MsContext::GetInstance();
MS_EXCEPTION_IF_NULL(context_ptr);
bool save_graphs = context_ptr->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG);
if (save_graphs) {
Log(graph, tensors, pConstraints, continuous_v);
}
} catch (const std::exception &e) {
MS_LOG(EXCEPTION) << "SomasSolver::Solving FAILED: " << e.what();
retval = FAILED;
}
return retval;
}
void SomasSolverPre::Log(const session::KernelGraph *graph,
const unordered_map<size_t, SomasSolverTensorDescPtr> &tensors,
std::vector<DynamicBitSet> *pConstraints, const vector<vector<size_t>> &continuous_v) {
MS_LOG(INFO) << "SomasSolver::Log Writing somas-input.txt..";
auto context_ptr = MsContext::GetInstance();
MS_EXCEPTION_IF_NULL(context_ptr);
auto save_graphs_path = context_ptr->get_param<std::string>(MS_CTX_SAVE_GRAPHS_PATH);
std::string filename = save_graphs_path + "/" + "somas_solver_input_" + std::to_string(graph->graph_id()) + ".ir";
if (filename.size() > PATH_MAX) {
MS_LOG(ERROR) << "File path " << filename << " is too long.";
return;
}
char real_path[PATH_MAX] = {0};
#if defined(_WIN32) || defined(_WIN64)
if (_fullpath(real_path, filename.c_str(), PATH_MAX) == nullptr) {
MS_LOG(DEBUG) << "dir " << filename << " does not exit.";
}
#else
if (realpath(filename.c_str(), real_path) == nullptr) {
MS_LOG(DEBUG) << "Dir " << filename << " does not exit.";
}
#endif
std::string path_string = real_path;
ChangeFileMode(path_string, S_IRWXU);
std::ofstream ofs_1(real_path);
if (!ofs_1.is_open()) {
MS_LOG(ERROR) << "Open log file '" << real_path << "' failed!";
return;
}
for (auto &t : tensors) {
ofs_1 << "T " << t.second->index_ << " " << t.second->size_ << " " << t.second->lifelong_ << std::endl;
}
for (auto &t1 : tensors) {
for (auto &t2 : tensors) {
size_t idx1 = t1.first;
size_t idx2 = t2.first;
if ((idx1 != idx2) && (*pConstraints)[idx1].IsBitTrue(idx2) == false) {
ofs_1 << "C " << idx1 << " " << idx2 << std::endl;
}
}
}
for (auto &s : continuous_v) {
ofs_1 << "S";
for (auto idx : s) {
ofs_1 << " " << idx;
}
ofs_1 << std::endl;
}
ofs_1.close();
MS_LOG(INFO) << "SomasSolver::Log Writing somas-output.txt..";
std::string out_filename =
save_graphs_path + "/" + "somas_solver_output_" + std::to_string(graph->graph_id()) + ".ir";
if (out_filename.size() > PATH_MAX) {
MS_LOG(ERROR) << "File path " << out_filename << " is too long.";
return;
}
#if defined(_WIN32) || defined(_WIN64)
if (_fullpath(real_path, out_filename.c_str(), PATH_MAX) == nullptr) {
MS_LOG(DEBUG) << "dir " << out_filename << " does not exit.";
}
#else
if (realpath(out_filename.c_str(), real_path) == nullptr) {
MS_LOG(DEBUG) << "Dir " << out_filename << " does not exit.";
}
#endif
path_string = real_path;
ChangeFileMode(path_string, S_IRWXU);
std::ofstream ofs_2(real_path);
if (!ofs_2.is_open()) {
MS_LOG(ERROR) << "Open log file '" << real_path << "' failed!";
return;
}
for (auto &t : tensors) {
SomasSolverTensorDescPtr tensor = t.second;
int continuous = 0;
if (tensor->left_ == NULL && tensor->right_ != NULL)
continuous = 1;
else if (tensor->left_ != NULL && tensor->right_ != NULL)
continuous = 2;
else if (tensor->left_ != NULL && tensor->right_ == NULL)
continuous = 3;
const size_t alignment = 512;
bool size_aligned = tensor->size_ % alignment == 0;
bool offset_aligned = tensor->offset_ % alignment == 0;
ofs_2 << std::endl
<< "tensor_id=" << tensor->index_ << "\tsize=" << tensor->size_ << "\toffset=" << tensor->offset_
<< "\tcontinuous=" << continuous << "\tsize_aligned=" << size_aligned
<< "\toffset_aligned=" << offset_aligned;
}
ofs_2.close();
MS_LOG(INFO) << "SomasSolver::Log done";
}
} // namespace somas
} // namespace mindspore
| 36.827411 | 116 | 0.624259 | [
"vector"
] |
babd6396343815ecdfc8fce4706ee3b6f968d198 | 462 | cpp | C++ | Algorithms/300.Longest-Increasing-Subsequence/solution.cpp | moranzcw/LeetCode_Solutions | 49a7e33b83d8d9ce449c758717f74a69e72f808e | [
"MIT"
] | 178 | 2017-07-09T23:13:11.000Z | 2022-02-26T13:35:06.000Z | Algorithms/300.Longest-Increasing-Subsequence/solution.cpp | cfhyxxj/LeetCode-NOTES | 455d33aae54d065635d28ebf37f815dc4ace7e63 | [
"MIT"
] | 1 | 2020-10-10T16:38:03.000Z | 2020-10-10T16:38:03.000Z | Algorithms/300.Longest-Increasing-Subsequence/solution.cpp | cfhyxxj/LeetCode-NOTES | 455d33aae54d065635d28ebf37f815dc4ace7e63 | [
"MIT"
] | 82 | 2017-08-19T07:14:39.000Z | 2022-02-17T14:07:55.000Z | class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int maxlen = 0;
vector<int> dp(nums.size());
for(int i=0;i<nums.size();i++){
int max_dp = 0;
for(int j=0;j<i;j++){
if(nums[i] > nums[j])
max_dp = max(dp[j], max_dp);
}
dp[i] = max_dp + 1;
maxlen = max(dp[i], maxlen);
}
return maxlen;
}
};
| 24.315789 | 48 | 0.398268 | [
"vector"
] |
bac54e0428059d3c86900a52b5ed8591c0c032f1 | 6,644 | hpp | C++ | deps/boost/include/boost/hana/fwd/concept/iterable.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 995 | 2018-06-22T10:39:18.000Z | 2022-03-25T01:22:14.000Z | deps/boost/include/boost/hana/fwd/concept/iterable.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 32 | 2018-06-23T14:19:37.000Z | 2022-03-29T10:20:37.000Z | deps/boost/include/boost/hana/fwd/concept/iterable.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 172 | 2018-06-22T11:12:00.000Z | 2022-03-29T07:44:33.000Z | /*!
@file
Forward declares `boost::hana::Iterable`.
@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_FWD_CONCEPT_ITERABLE_HPP
#define BOOST_HANA_FWD_CONCEPT_ITERABLE_HPP
#include <boost/hana/config.hpp>
BOOST_HANA_NAMESPACE_BEGIN
//! @ingroup group-concepts
//! @defgroup group-Iterable Iterable
//! The `Iterable` concept represents data structures supporting external
//! iteration.
//!
//! Intuitively, an `Iterable` can be seen as a kind of container whose
//! elements can be pulled out one at a time. An `Iterable` also provides
//! a way to know when the _container_ is empty, i.e. when there are no
//! more elements to pull out.
//!
//! Whereas `Foldable` represents data structures supporting internal
//! iteration with the ability to accumulate a result, the `Iterable`
//! concept allows inverting the control of the iteration. This is more
//! flexible than `Foldable`, since it allows iterating over only some
//! part of the structure. This, in turn, allows `Iterable` to work on
//! infinite structures, while trying to fold such a structure would
//! never finish.
//!
//!
//! Minimal complete definition
//! ---------------------------
//! `at`, `drop_front` and `is_empty`
//!
//!
//! @anchor Iterable-lin
//! The linearization of an `Iterable`
//! ----------------------------------
//! Intuitively, for an `Iterable` structure `xs`, the _linearization_ of
//! `xs` is the sequence of all the elements in `xs` as if they had been
//! put in a (possibly infinite) list:
//! @code
//! linearization(xs) = [x1, x2, x3, ...]
//! @endcode
//!
//! The `n`th element of the linearization of an `Iterable` can be
//! accessed with the `at` function. In other words, `at(xs, n) == xn`.
//!
//! Note that this notion is precisely the extension of the [linearization]
//! (@ref Foldable-lin) notion of `Foldable`s to the infinite case. This
//! notion is useful for expressing various properties of `Iterable`s,
//! and is used for that elsewhere in the documentation.
//!
//!
//! Compile-time `Iterable`s
//! ------------------------
//! A _compile-time_ `Iterable` is an `Iterable` for which `is_empty`
//! returns a compile-time `Logical`. These structures allow iteration
//! to be done at compile-time, in the sense that the "loop" doing the
//! iteration can be unrolled because the total length of the structure
//! is kown at compile-time.
//!
//! In particular, note that being a compile-time `Iterable` has nothing
//! to do with being finite or infinite. For example, it would be possible
//! to create a sequence representing the Pythagorean triples as
//! `integral_constant`s. Such a sequence would be infinite, but iteration
//! on the sequence would still be done at compile-time. However, if one
//! tried to iterate over _all_ the elements of the sequence, the compiler
//! would loop indefinitely, in contrast to your program looping
//! indefinitely if the sequence was a runtime one.
//!
//! __In the current version of the library, only compile-time `Iterable`s
//! are supported.__ While it would be possible in theory to support
//! runtime `Iterable`s, doing it efficiently is the subject of some
//! research. In particular, follow [this issue][1] for the current
//! status of runtime `Iterable`s.
//!
//!
//! Laws
//! ----
//! First, we require the equality of two `Iterable`s to be related to the
//! equality of the elements in their linearizations. More specifically,
//! if `xs` and `ys` are two `Iterable`s of data type `It`, then
//! @code
//! xs == ys => at(xs, i) == at(ys, i) for all i
//! @endcode
//!
//! This conveys that two `Iterable`s must have the same linearization
//! in order to be considered equal.
//!
//! Secondly, since every `Iterable` is also a `Searchable`, we require
//! the models of `Iterable` and `Searchable` to be consistent. This is
//! made precise by the following laws. For any `Iterable` `xs` with a
//! linearization of `[x1, x2, x3, ...]`,
//! @code
//! any_of(xs, equal.to(z)) <=> xi == z
//! @endcode
//! for some _finite_ index `i`. Furthermore,
//! @code
//! find_if(xs, pred) == just(the first xi such that pred(xi) is satisfied)
//! @endcode
//! or `nothing` if no such `xi` exists.
//!
//!
//! Refined concepts
//! ----------------
//! 1. `Searchable` (free model)\n
//! Any `Iterable` gives rise to a model of `Searchable`, where the keys
//! and the values are both the elements in the structure. Searching for
//! a key is just doing a linear search through the elements of the
//! structure.
//! @include example/iterable/searchable.cpp
//!
//! 2. `Foldable` for finite `Iterable`s\n
//! Every finite `Iterable` gives rise to a model of `Foldable`. For
//! these models to be consistent, we require the models of both `Foldable`
//! and `Iterable` to have the same linearization.
//!
//! @note
//! As explained above, `Iterable`s are also `Searchable`s and their
//! models have to be consistent. By the laws presented here, it also
//! means that the `Foldable` model for finite `Iterable`s has to be
//! consistent with the `Searchable` model.
//!
//! For convenience, finite `Iterable`s must only provide a definition of
//! `length` to model the `Foldable` concept; defining the more powerful
//! `unpack` or `fold_left` is not necessary (but still possible). The
//! default implementation of `unpack` derived from `Iterable` + `length`
//! uses the fact that `at(xs, i)` denotes the `i`th element of `xs`'s
//! linearization, and that the linearization of a finite `Iterable` must
//! be the same as its linearization as a `Foldable`.
//!
//!
//! Concrete models
//! ---------------
//! `hana::tuple`, `hana::string`, `hana::range`
//!
//!
//! [1]: https://github.com/boostorg/hana/issues/40
template <typename It>
struct Iterable;
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_FWD_CONCEPT_ITERABLE_HPP
| 44.293333 | 84 | 0.621162 | [
"model"
] |
bac9c3313fe2e5c84c1305045a0c729b115093bc | 22,831 | cpp | C++ | CUInstantiation/CUInstantiationPass.cpp | elouanj/discopop | 02102e25bf72b020fd407522c6e01fe270d539f3 | [
"BSD-3-Clause"
] | 15 | 2020-12-10T01:24:31.000Z | 2022-02-16T14:14:46.000Z | CUInstantiation/CUInstantiationPass.cpp | elouanj/discopop | 02102e25bf72b020fd407522c6e01fe270d539f3 | [
"BSD-3-Clause"
] | 11 | 2020-10-19T19:21:54.000Z | 2022-03-18T23:00:17.000Z | CUInstantiation/CUInstantiationPass.cpp | elouanj/discopop | 02102e25bf72b020fd407522c6e01fe270d539f3 | [
"BSD-3-Clause"
] | 11 | 2020-10-26T10:32:31.000Z | 2021-12-21T09:33:26.000Z | /*
* This file is part of the DiscoPoP software (http://www.discopop.tu-darmstadt.de)
*
* Copyright (c) 2020, Technische Universitaet Darmstadt, Germany
*
* This software may be modified and distributed under the terms of
* the 3-Clause BSD License. See the LICENSE file in the package base
* directory for details.
*
*/
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/ilist.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/RegionIterator.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Pass.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"
#include "llvm-c/Core.h"
#include "llvm/Analysis/DominanceFrontier.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/PassRegistry.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/LegacyPassManager.h"
#include "DPUtils.h"
#include <map>
#include <set>
#include <utility>
#include <iomanip>
#include <algorithm>
#include <string.h>
using namespace llvm;
using namespace std;
using namespace dputil;
// using LID = int32_t;
namespace {
static cl::opt<std::string> InputFilename("input", cl::desc("<input file>"), cl::Optional);
static cl::opt<std::string> FileMapping("filemapping", cl::desc("<filemapping file>"), cl::Optional);
struct compare {
bool operator() (const pair<string,int>& lhs, const pair<string,int>& rhs) const{
return ((lhs.first<rhs.first) || (lhs.second < rhs.second));
}
};
// Data structures for reading input
static map<LID, vector<pair<string,int>>> callLineToFNameMap; // location of function calls to a (functio name,PIDIndex)
static map<LID, set<pair<string,int>,compare>> readLineToVarNameMap; // location of loads to instrument with variable names in the input
static map<LID, set<pair<string,int>,compare>> writeLineToVarNameMap; // location of stores to instrument with variable names in the input
int32_t fileID;
static int PIDIndex;
struct CUInstantiation : public ModulePass {
static char ID;
LLVMContext* ThisModuleContext;
//structures to get list of global variables
Module *ThisModule;
// used to get variable names. Originally appeared in DiscoPoP code!
//map<string, int> signature;
// Callbacks to run-time library
Function *CUInstFinalize, *CUInstInitialize;
Function *CUInstRead, *CUInstWrite;
Function *CUInstCallBefore;
Function *CUInstCallAfter;
// Basic types
Type *Void;
IntegerType *Int32, *Int64;
PointerType *CharPtr;
//DiscoPoP Data structures
map<string, MDNode*> Structs;
map<string, Value*> VarNames;
//DiscoPoP Functions
string determineVariableName(Instruction* I);
Type* pointsToStruct(PointerType* PTy);
string getOrInsertVarName(string varName, IRBuilder<>& builder);
string findStructMemberName(MDNode* structNode, unsigned idx, IRBuilder<>& builder);
bool isaCallOrInvoke(Instruction* BI);
void setupDataTypes();
void setupCallbacks();
string getFunctionName(Instruction *instruction);
void readLineNumberPairs(const char* fileName);
void insertInitializeInst(Function &F);
void insertFinalizeInst(Instruction *inst);
void instrumentLoadInst(Instruction *inst, int pidIndex);
void instrumentStoreInst(Instruction *inst, int pidIndex);
void instrumentCallInst(Instruction *inst, int index, int lastCall);
//Output function
//string xmlEscape(string data);
//void secureStream();
//string getLineNumbersString(set<int> LineNumbers);
//void closeOutputFiles();
vector<string> split(const string &s, const char delim);
LID encodeLID(const string s);
int isLastCall(LID line, string fName, int index);
bool doInitialization(Module &M);
virtual bool runOnModule(Module &M);
StringRef getPassName() const;
void getAnalysisUsage(AnalysisUsage &Info) const;
CUInstantiation() : ModulePass(ID) {}
}; // end of struct CUInstantiation
} // end of anonymous namespace
/***************************** DiscoPoP Functions ***********************************/
string CUInstantiation::determineVariableName(Instruction* I) {
assert(I && "Instruction cannot be NULL \n");
int index = isa<StoreInst>(I) ? 1 : 0;
Value* operand = I->getOperand(index);
IRBuilder<> builder(I);
if (operand == NULL) {
return getOrInsertVarName("", builder);
}
if (operand->hasName()) {
//// we've found a global variable
if (isa<GlobalVariable>(*operand)) {
//MOHAMMAD ADDED THIS FOR CHECKING
return string(operand->getName());
}
if (isa<GetElementPtrInst>(*operand)) {
GetElementPtrInst* gep = cast<GetElementPtrInst>(operand);
Value* ptrOperand = gep->getPointerOperand();
PointerType *PTy = cast<PointerType>(ptrOperand->getType());
// we've found a struct/class
Type* structType = pointsToStruct(PTy);
if (structType && gep->getNumOperands() > 2) {
Value* constValue = gep->getOperand(2);
if (constValue && isa<ConstantInt>(*constValue)) {
ConstantInt* idxPtr = cast<ConstantInt>(gep->getOperand(2));
uint64_t memberIdx = *(idxPtr->getValue().getRawData());
string strName(structType->getStructName().data());
map<string, MDNode*>::iterator it = Structs.find(strName);
if (it != Structs.end()) {
std::string ret = findStructMemberName(it->second, memberIdx, builder);
if (ret.size() > 0)
return ret;
else
return getOrInsertVarName("", builder);
//return ret;
}
}
}
// we've found an array
if (PTy->getElementType()->getTypeID() == Type::ArrayTyID && isa<GetElementPtrInst>(*ptrOperand)) {
return determineVariableName((Instruction*)ptrOperand);
}
return determineVariableName((Instruction*)gep);
}
return string(operand->getName().data());
//return getOrInsertVarName(string(operand->getName().data()), builder);
}
if (isa<LoadInst>(*operand) || isa<StoreInst>(*operand)) {
return determineVariableName((Instruction*)(operand));
}
// if we cannot determine the name, then return *
return "";//getOrInsertVarName("*", builder);
}
Type* CUInstantiation::pointsToStruct(PointerType* PTy) {
assert(PTy);
Type* structType = PTy;
if (PTy->getTypeID() == Type::PointerTyID) {
while (structType->getTypeID() == Type::PointerTyID) {
structType = cast<PointerType>(structType)->getElementType();
}
}
return structType->getTypeID() == Type::StructTyID ? structType : NULL;
}
string CUInstantiation::getOrInsertVarName(string varName, IRBuilder<>& builder) {
Value* valName = NULL;
std::string vName = varName;
map<string, Value*>::iterator pair = VarNames.find(varName);
if (pair == VarNames.end()) {
valName = builder.CreateGlobalStringPtr(StringRef(varName.c_str()), ".str");
VarNames[varName] = valName;
}
else {
vName = pair->first;
}
return vName;
}
string CUInstantiation::findStructMemberName(MDNode* structNode, unsigned idx, IRBuilder<>& builder) {
assert(structNode);
assert(structNode->getOperand(10));
MDNode* memberListNodes = cast<MDNode>(structNode->getOperand(10));
if (idx < memberListNodes->getNumOperands()) {
assert(memberListNodes->getOperand(idx));
MDNode* member = cast<MDNode>(memberListNodes->getOperand(idx));
if (member->getOperand(3)) {
//getOrInsertVarName(string(member->getOperand(3)->getName().data()), builder);
//return string(member->getOperand(3)->getName().data());
getOrInsertVarName(dyn_cast<MDString>(member->getOperand(3))->getString(), builder);
return dyn_cast<MDString>(member->getOperand(3))->getString();
}
}
return NULL;
}
bool CUInstantiation::isaCallOrInvoke(Instruction* BI) {
return (BI != NULL) && ((isa<CallInst>(BI) && (!isa<DbgDeclareInst>(BI))) || isa<InvokeInst>(BI));
}
string CUInstantiation::getFunctionName(Instruction *instruction){
string name;
Function* f;
Value* v;
if(isa<CallInst>(instruction)){
f = (cast<CallInst>(instruction))->getCalledFunction();
v = (cast<CallInst>(instruction))->getCalledValue();
}
else {
f = (cast<InvokeInst>(instruction))->getCalledFunction();
v = (cast<InvokeInst>(instruction))->getCalledValue();
}
// For ordinary function calls, F has a name.
// However, sometimes the function being called
// in IR is encapsulated by "bitcast()" due to
// the way of compiling and linking. In this way,
// getCalledFunction() method returns NULL.
// Also, getName() returns NULL if this is an indirect function call.
if(f){
name = f->getName();
}
else{ // get name of the indirect function which is called
Value* sv = v->stripPointerCasts();
StringRef fname = sv->getName();
name = fname;
}
return name;
}
void CUInstantiation::setupDataTypes() {
Void = const_cast<Type*>(Type::getVoidTy(*ThisModuleContext));
Int32 = const_cast<IntegerType*>(IntegerType::getInt32Ty(*ThisModuleContext));
Int64 = const_cast<IntegerType*>(IntegerType::getInt64Ty(*ThisModuleContext));
CharPtr = const_cast<PointerType*>(Type::getInt8PtrTy(*ThisModuleContext));
}
void CUInstantiation::setupCallbacks() {
/* function name
* return value type
* arg types
* NULL
*/
CUInstInitialize = cast<Function>(ThisModule->getOrInsertFunction("__CUInstantiationInitialize",
Void,
CharPtr));
CUInstFinalize = cast<Function>(ThisModule->getOrInsertFunction("__CUInstantiationFinalize",
Void));
CUInstRead = cast<Function>(ThisModule->getOrInsertFunction("__CUInstantiationRead",
Void,
Int32,
Int32,
Int64,
CharPtr,
CharPtr));
CUInstWrite = cast<Function>(ThisModule->getOrInsertFunction("__CUInstantiationWrite",
Void,
Int32,
Int32,
Int64,
CharPtr,
CharPtr));
CUInstCallBefore = cast<Function>(ThisModule->getOrInsertFunction("__CUInstantiationCallBefore",
Void,
Int32));
CUInstCallAfter = cast<Function>(ThisModule->getOrInsertFunction("__CUInstantiationCallAfter",
Void,
Int32,
Int32));
}
bool CUInstantiation::doInitialization(Module &M) {
// Export M to the outside
ThisModule = &M;
ThisModuleContext = &(M.getContext());
PIDIndex = 0;
setupDataTypes();
setupCallbacks();
return true;
}
/*********************************** End of DiscoPoP Functions ***********************************/
// string split
vector<string> CUInstantiation::split(const string &s, const char delim) {
stringstream ss(s);
string tmp;
vector<string> out;
while (getline(ss, tmp, delim)) {
out.emplace_back(tmp);
}
return out;
}
/* *********************** Helper functions ************************ */
void CUInstantiation::readLineNumberPairs(const char* fileName)
{
ifstream inputFileStream;
inputFileStream.open(fileName);
if(!inputFileStream.is_open()){
errs() << "Unable to open the input file\n";
exit(0);
}
string line;
while (std::getline(inputFileStream, line))
{
istringstream iss(line);
string FName;
string callLines;
string deps;
iss >> FName;
iss >> callLines;
iss >> deps;
for(auto i:split(callLines, ',')){
callLineToFNameMap[encodeLID(i)].push_back(pair<string,int>(FName,PIDIndex));
}
for(auto dep:split(deps, ',')){
vector<string> i = split(dep, '|');
pair<string,int> p(i.back(),PIDIndex);
if(i[1] == "RAW"){
readLineToVarNameMap[encodeLID(i.front())].insert(p); // i.front is the read location and i.back variable name
writeLineToVarNameMap[encodeLID(i[2])].insert(p); // i[2] is the write location and i.back variable name
} else if(i[1] == "WAR"){
writeLineToVarNameMap[encodeLID(i.front())].insert(p); // i.front is the write location and i.back variable name
readLineToVarNameMap[encodeLID(i[2])].insert(p); // i[2] is the read location and i.back variable name
} else if(i[1] == "WAW"){
writeLineToVarNameMap[encodeLID(i.front())].insert(p); // i.front is the write location and i.back variable name
writeLineToVarNameMap[encodeLID(i[2])].insert(p); // i[2] is the write location and i.back variable name
}
}
PIDIndex++;
}
}
// encode string to LID
LID CUInstantiation::encodeLID(const string s) {
vector<string> tmp = split(s, ':');
return (static_cast<LID>(stoi(tmp[0])) << LIDSIZE) + static_cast<LID>(stoi(tmp[1]));
}
/* *********************** End of helper functions ************************ */
void CUInstantiation::insertInitializeInst(Function &F){
string allFunctionIndices = "";
for(auto i:callLineToFNameMap){
for(auto j:i.second){
allFunctionIndices += to_string(j.second) + " ";
}
}
BasicBlock &entryBB = F.getEntryBlock();
int32_t lid = 0;
vector<Value*> args;
IRBuilder<> builder(&*entryBB.begin());
Value *vName = builder.CreateGlobalStringPtr(StringRef(allFunctionIndices.c_str()), ".str");
args.push_back(vName);
// We always want to insert __CUInstInitialize at the beginning
// of the main function to initialize our data structures in the instrumentation library, but we need the first valid LID to
// get the entry line of the function.
for (BasicBlock::iterator BI = entryBB.begin(), EI = entryBB.end(); BI != EI; ++BI) {
lid = getLID(&*BI, fileID);
if (lid > 0 && !isa<PHINode>(&*BI)) {
//IRBuilder<> IRB(entryBB.begin());
//CallInst::Create(CUInstInitialize, args, "")->insertAfter(BI);
CallInst::Create(CUInstInitialize, args, "", &*BI);
break;
}
}
assert((lid > 0) && "Function entry is not instrumented because LID are all invalid for the entry block.");
}
void CUInstantiation::insertFinalizeInst(Instruction *before){
CallInst::Create(CUInstFinalize, "", before);
}
void CUInstantiation::instrumentLoadInst(Instruction *toInstrument, int pidIndex){
vector<Value*> args;
int32_t lid = getLID(toInstrument, fileID);
if (lid == 0) return;
args.push_back(ConstantInt::get(Int32, lid));
args.push_back(ConstantInt::get(Int32, pidIndex));
Value* memAddr = PtrToIntInst::CreatePointerCast(cast<LoadInst>(toInstrument)->getPointerOperand(),
Int64, "", toInstrument);
args.push_back(memAddr);
IRBuilder<> builder(toInstrument);
Value *fName;
if(toInstrument->getParent()->getParent()->hasName()){
fName = builder.CreateGlobalStringPtr(string(toInstrument->getParent()->getParent()->getName().data()).c_str(), ".str");
args.push_back(fName);
} else {
fName = builder.CreateGlobalStringPtr(string("NULL").c_str(), ".str");
args.push_back(fName);
}
string varName = determineVariableName(toInstrument);
//if (varName.find(".addr") != varName.npos)
// varName.erase(varName.find(".addr"), 5);
Value *vName = builder.CreateGlobalStringPtr(varName.c_str(), ".str");
args.push_back(vName);
CallInst::Create(CUInstRead, args, "", toInstrument);
}
void CUInstantiation::instrumentStoreInst(Instruction *toInstrument, int pidIndex){
vector<Value*> args;
int32_t lid = getLID(toInstrument, fileID);
if (lid == 0) return;
args.push_back(ConstantInt::get(Int32, lid));
args.push_back(ConstantInt::get(Int32, pidIndex));
Value* memAddr = PtrToIntInst::CreatePointerCast(cast<StoreInst>(toInstrument)->getPointerOperand(),
Int64, "", toInstrument);
args.push_back(memAddr);
IRBuilder<> builder(toInstrument);
Value *fName;
if(toInstrument->getParent()->getParent()->hasName()){
fName = builder.CreateGlobalStringPtr(string(toInstrument->getParent()->getParent()->getName().data()).c_str(), ".str");
args.push_back(fName);
} else {
fName = builder.CreateGlobalStringPtr(string("NULL").c_str(), ".str");
args.push_back(fName);
}
string varName = determineVariableName(toInstrument);
//if (varName.find(".addr") != varName.npos)
// varName.erase(varName.find(".addr"), 5);
Value *vName = builder.CreateGlobalStringPtr(varName.c_str(), ".str");
args.push_back(vName);
CallInst::Create(CUInstWrite, args, "", toInstrument);
}
void CUInstantiation::instrumentCallInst(Instruction *toInstrument, int index, int lastCall){
vector<Value*> args;
args.push_back(ConstantInt::get(Int32, index));
//IRBuilder<> builder(toInstrument);
//Value *vName = builder.CreateGlobalStringPtr(StringRef(fName.c_str()), ".str");
//args.push_back(vName);
//it creates a call "CUInstCallBefore" and inserts it before the toInstrument instruction
CallInst::Create(CUInstCallBefore, args, "", toInstrument);
if(lastCall == 1)
args.push_back(ConstantInt::get(Int32, 1));
else
args.push_back(ConstantInt::get(Int32, 0));
//it first creates a call "CUInstCallAfter" and then inserts it after the toInstrument instruction
CallInst::Create(CUInstCallAfter, args, "")->insertAfter(toInstrument);
}
void CUInstantiation::getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<LoopInfoWrapperPass>();
}
int CUInstantiation::isLastCall(LID line, string fName, int index){
for(auto j:callLineToFNameMap)
for(auto i:j.second){
if(i.first == fName && i.second == index){
return 0;
}
}
return 1;
}
bool CUInstantiation::runOnModule(Module &M){
StringRef inputFileName = InputFilename;
if (inputFileName.empty()) //input is not given
{
errs() << "Input file name empty\n";
exit(0);
}
const char* fileName = inputFileName.data();
readLineNumberPairs(fileName);
for (Module::iterator func = ThisModule->begin(), E = ThisModule->end(); func != E; ++func)
{
determineFileID(*func, fileID);
if (func->hasName() && func->getName().equals("main")){
insertInitializeInst(*func);
}
for (inst_iterator i = inst_begin(*func); i!=inst_end(*func); ++i)
{
Instruction *inst = &*i;
LID line = getLID(inst, fileID);
if(isa<LoadInst>(inst)){
if(readLineToVarNameMap.find(line) != readLineToVarNameMap.end()){
string varName = determineVariableName(inst);
for(auto i:readLineToVarNameMap[line]){
if(i.first == varName){
instrumentLoadInst(inst, i.second);
}
}
}
} else if(isa<StoreInst>(inst)){
if(writeLineToVarNameMap.find(line) != writeLineToVarNameMap.end()){
string varName = determineVariableName(inst);
for(auto i:writeLineToVarNameMap[line]){
if(i.first == varName){
instrumentStoreInst(inst, i.second);
}
}
}
} else if(isaCallOrInvoke(inst)){
if(callLineToFNameMap.find(line) != callLineToFNameMap.end()){
string fName = getFunctionName(inst);
int ind = 0;
for(auto i:callLineToFNameMap[line]){
if(i.first == fName){
int temp = i.second;
callLineToFNameMap[line].erase(callLineToFNameMap[line].begin() + ind);
int isLast = isLastCall(line, fName, temp);
instrumentCallInst(inst, temp, isLast);
break;
}
ind++;
}
}
}
else if (isa<ReturnInst>(inst)) {
if (func->getName().equals("main")) { // returning from main
insertFinalizeInst(inst);
}
}
}
}
return false;
}
char CUInstantiation::ID = 0;
static RegisterPass<CUInstantiation> X("CUInstantiation", "CUInstantiation: determine computation units instances that can run in parallel.", false, false);
static void loadPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
{
PM.add(new LoopInfoWrapperPass());
PM.add(new CUInstantiation());
}
static RegisterStandardPasses CUGenerationLoader_Ox(PassManagerBuilder::EP_OptimizerLast, loadPass);
static RegisterStandardPasses CUGenerationLoader_O0(PassManagerBuilder::EP_EnabledOnOptLevel0, loadPass);
ModulePass *createCUInstantiationPass()
{
initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
initializeRegionInfoPassPass(*PassRegistry::getPassRegistry());
return new CUInstantiation();
}
StringRef CUInstantiation::getPassName() const
{
return "CUInstantiation";
}
| 34.750381 | 156 | 0.61999 | [
"vector"
] |
baca828556d2482967a905678867355d5f29e5af | 11,498 | hpp | C++ | libelement.CLI/include/compile_command.hpp | ultraleap/Element | 6fe9ab800a9152482e719a7dc17d296bad464eb6 | [
"Apache-2.0"
] | 12 | 2019-12-17T18:27:04.000Z | 2021-06-04T08:46:05.000Z | libelement.CLI/include/compile_command.hpp | ultraleap/Element | 6fe9ab800a9152482e719a7dc17d296bad464eb6 | [
"Apache-2.0"
] | 12 | 2020-10-27T14:30:37.000Z | 2022-01-05T16:50:53.000Z | libelement.CLI/include/compile_command.hpp | ultraleap/Element | 6fe9ab800a9152482e719a7dc17d296bad464eb6 | [
"Apache-2.0"
] | 6 | 2020-01-10T23:45:48.000Z | 2021-07-01T22:58:01.000Z | #pragma once
#include <element/element.h>
#include <interpreter_internal.hpp>
#include <iostream>
#include <fstream>
#include "command.hpp"
#include "compiler_message.hpp"
#include "lmnt/opcodes.h"
#include "lmnt/archive.h"
#include "lmnt/interpreter.h"
#include "lmnt/compiler.hpp"
#include "lmnt/jit.h"
namespace libelement::cli
{
struct compile_command_arguments
{
std::string name;
std::string parameters;
std::string return_type;
std::string expression;
std::string output_path;
[[nodiscard]] std::string as_string() const
{
std::stringstream sst;
sst << "compile --name \"" << name
<< "\" --return-type \"" << return_type
<< "\" --expression \"" << expression
<< "\" --output-path \"" << output_path << "\"";
if (!parameters.empty())
sst << " --parameters \"" << parameters << "\"";
return sst.str();
}
};
class compile_command final : public command
{
public:
compile_command(common_command_arguments common_arguments,
compile_command_arguments custom_arguments)
: command(std::move(common_arguments))
, custom_arguments{ std::move(custom_arguments) }
{}
[[nodiscard]] compiler_message execute(const compilation_input& compilation_input) const override
{
const auto result = setup(compilation_input);
if (result != ELEMENT_OK)
return compiler_message(error_conversion(result),
"Failed to setup context",
compilation_input.get_log_json()); // todo
return compile(compilation_input);
}
[[nodiscard]] compiler_message compile(const compilation_input& compilation_input) const
{
const auto def = fmt::format("{}{}:{} = {}",
custom_arguments.name,
custom_arguments.parameters,
custom_arguments.return_type,
custom_arguments.expression);
element_result result = element_interpreter_load_string(context, def.c_str(), "<cli>");
if (result != ELEMENT_OK) {
return compiler_message(error_conversion(result),
"Failed to load: " + def + " at runtime with element_result " + std::to_string(result),
compilation_input.get_log_json());
}
element_declaration* decl = nullptr;
result = element_interpreter_find(context, custom_arguments.name.c_str(), &decl);
if (result != ELEMENT_OK) {
return compiler_message(error_conversion(result),
"Failed to find: " + custom_arguments.name + " with element_result " + std::to_string(result),
compilation_input.get_log_json());
}
element_instruction* compiled_function = nullptr;
result = element_interpreter_compile_declaration(context, nullptr, decl, &compiled_function);
if (result != ELEMENT_OK) {
return compiler_message(error_conversion(result),
"Failed to compile: " + custom_arguments.name + " at runtime with element_result " + std::to_string(result),
compilation_input.get_log_json());
}
size_t inputs_size = 0;
result = element_instruction_get_inputs_size(compiled_function, &inputs_size);
if (result != ELEMENT_OK) {
return compiler_message(error_conversion(result),
"Failed to get inputs size of: " + custom_arguments.name + " with element_result " + std::to_string(result),
compilation_input.get_log_json());
}
size_t outputs_size = 0;
result = element_instruction_get_size(compiled_function, &outputs_size);
if (result != ELEMENT_OK) {
return compiler_message(error_conversion(result),
"Failed to get outputs size of: " + custom_arguments.name + " with element_result " + std::to_string(result),
compilation_input.get_log_json());
}
auto response = generate_response(ELEMENT_ERROR_UNKNOWN, element_outputs{}, compilation_input.get_log_json());
if (common_arguments.target == Target::LMNT || common_arguments.target == Target::LMNTJit)
response = compile_lmnt(compilation_input, compiled_function, inputs_size, outputs_size, custom_arguments.output_path);
element_instruction_delete(&compiled_function);
return response;
}
[[nodiscard]] std::string as_string() const override
{
std::stringstream ss;
ss << custom_arguments.as_string() << " " << common_arguments.as_string();
return ss.str();
}
static void configure(CLI::App& app,
const std::shared_ptr<common_command_arguments>& common_arguments,
callback callback)
{
const auto arguments = std::make_shared<compile_command_arguments>();
auto* command = app.add_subcommand("compile")->fallthrough();
command->add_option("-n,--name", arguments->name, "Name of the resulting LMNT function.")
->required();
command->add_option("-r,--return-type", arguments->return_type, "Return type of the resulting LMNT function.")
->required();
command->add_option("-e,--expression", arguments->expression, "Expression to evaluate.")
->required();
command->add_option("-o,--output-path", arguments->output_path, "Path to output generated file to.")
->required();
command->add_option("-p,--parameters", arguments->parameters, "Parameters to the resulting LMNT function.");
command->callback([callback, common_arguments, arguments]() {
compile_command cmd(*common_arguments, *arguments);
callback(cmd);
});
}
private:
static std::vector<char> create_archive(
const char* def_name,
uint16_t args_count,
uint16_t rvals_count,
uint16_t stack_count,
const std::vector<lmnt_value>& constants,
const std::vector<lmnt_instruction>& function,
const lmnt_def_flags flags)
{
const size_t name_len = strlen(def_name);
const size_t name_len_padded = LMNT_ROUND_UP(0x02 + name_len + 1, 4) - 2;
const size_t instr_count = function.size();
const size_t consts_count = constants.size();
const size_t data_count = 0;
assert(name_len_padded <= 0xFD);
assert(instr_count <= 0x3FFFFFF0);
assert(consts_count <= 0x3FFFFFFF);
const size_t header_len = 0x1C;
const size_t strings_len = 0x02 + name_len_padded;
const size_t defs_len = 0x10;
const size_t code_len = 0x04 + instr_count * sizeof(lmnt_instruction);
const lmnt_loffset data_sec_count = 0;
const size_t data_len = 0x04 + data_sec_count * (0x08 + 0x04 * data_count);
const size_t consts_len = consts_count * sizeof(lmnt_value);
const size_t total_size = header_len + strings_len + defs_len + code_len + data_len + consts_len;
std::vector<char> buf;
buf.resize(total_size);
size_t idx = 0;
const char header[] = {
'L', 'M', 'N', 'T',
0x00, 0x00, 0x00, 0x00,
char(strings_len & 0xFF), char((strings_len >> 8) & 0xFF), char((strings_len >> 16) & 0xFF), char((strings_len >> 24) & 0xFF), // strings length
char(defs_len & 0xFF), char((defs_len >> 8) & 0xFF), char((defs_len >> 16) & 0xFF), char((defs_len >> 24) & 0xFF), // defs length
char(code_len & 0xFF), char((code_len >> 8) & 0xFF), char((code_len >> 16) & 0xFF), char((code_len >> 24) & 0xFF), // code length
char(data_len & 0xFF), char((data_len >> 8) & 0xFF), char((data_len >> 16) & 0xFF), char((data_len >> 24) & 0xFF), // data length
char(consts_len & 0xFF), char((consts_len >> 8) & 0xFF), char((consts_len >> 16) & 0xFF), char((consts_len >> 24) & 0xFF) // constants_length
};
memcpy(buf.data() + idx, header, sizeof(header));
idx += sizeof(header);
buf[idx] = name_len_padded & 0xFF;
idx += 2;
memcpy(buf.data() + idx, def_name, name_len);
idx += name_len;
for (size_t i = name_len; i < name_len_padded; ++i)
buf[idx++] = '\0';
const char def[] = {
0x00, 0x00, // defs[0].name
static_cast<char>(flags & 0xFF), static_cast<char>((flags >> 8) & 0xFF), // defs[0].flags
0x00, 0x00, 0x00, 0x00, // defs[0].code
static_cast<char>(stack_count & 0xFF), static_cast<char>((stack_count >> 8) & 0xFF), // defs[0].stack_count_unaligned
static_cast<char>(args_count & 0xFF), static_cast<char>((args_count >> 8) & 0xFF), // defs[0].args_count
static_cast<char>(rvals_count & 0xFF), static_cast<char>((rvals_count >> 8) & 0xFF), // defs[0].rvals_count
0x00, 0x00, // defs[0].default_args_index
};
memcpy(buf.data() + idx, def, sizeof(def));
idx += sizeof(def);
memcpy(buf.data() + idx, (const char*)(&instr_count), sizeof(uint32_t));
idx += sizeof(uint32_t);
memcpy(buf.data() + idx, function.data(), instr_count * sizeof(lmnt_instruction));
idx += instr_count * sizeof(lmnt_instruction);
memcpy(buf.data() + idx, (const char*)(&data_sec_count), sizeof(lmnt_loffset));
idx += sizeof(lmnt_loffset);
memcpy(buf.data() + idx, constants.data(), consts_count * sizeof(lmnt_value));
idx += consts_count * sizeof(lmnt_value);
assert(idx == total_size);
return buf;
}
compiler_message compile_lmnt(
const compilation_input& compilation_input,
element_instruction* instruction,
size_t inputs_size,
size_t outputs_size,
std::string output_path) const
{
element_lmnt_compiler_ctx lmnt_ctx;
element_lmnt_compiled_function lmnt_output;
std::vector<element_value> constants;
auto result = element_lmnt_compile_function(lmnt_ctx, instruction->instruction, constants, inputs_size, lmnt_output);
if (result != ELEMENT_OK) {
printf("RUH ROH: %d\n", result);
return generate_response(result, "failed to compile LMNT function", compilation_input.get_log_json());
}
for (size_t i = 0; i < constants.size(); ++i) {
printf("Constant[%04zX]: %f\n", i, constants[i]);
}
for (const auto& in : lmnt_output.instructions) {
printf("Instruction: %s %04X %04X %04X\n", lmnt_get_opcode_info(in.opcode)->name, in.arg1, in.arg2, in.arg3);
}
auto lmnt_archive_data = create_archive(
custom_arguments.name.c_str(),
uint16_t(inputs_size),
uint16_t(outputs_size),
uint16_t(lmnt_output.total_stack_count()),
constants,
lmnt_output.instructions,
lmnt_output.flags);
{
std::ofstream ofs(output_path, std::ios::out | std::ios::binary);
ofs.write(lmnt_archive_data.data(), lmnt_archive_data.size());
}
return generate_response(result, "", compilation_input.get_log_json());
}
compile_command_arguments custom_arguments;
};
} // namespace libelement::cli | 42.272059 | 158 | 0.608193 | [
"vector"
] |
bacda10c1a078f95b320f33e46d6f027734fc642 | 15,197 | cc | C++ | webkit/tools/test_shell/simple_appcache_system.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | webkit/tools/test_shell/simple_appcache_system.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | webkit/tools/test_shell/simple_appcache_system.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:25:45.000Z | 2020-11-04T07:25:45.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/tools/test_shell/simple_appcache_system.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/synchronization/waitable_event.h"
#include "webkit/appcache/appcache_interceptor.h"
#include "webkit/appcache/web_application_cache_host_impl.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
using WebKit::WebApplicationCacheHost;
using WebKit::WebApplicationCacheHostClient;
using appcache::WebApplicationCacheHostImpl;
using appcache::AppCacheBackendImpl;
using appcache::AppCacheInterceptor;
// SimpleFrontendProxy --------------------------------------------------------
// Proxies method calls from the backend IO thread to the frontend UI thread.
class SimpleFrontendProxy
: public base::RefCountedThreadSafe<SimpleFrontendProxy>,
public appcache::AppCacheFrontend {
public:
explicit SimpleFrontendProxy(SimpleAppCacheSystem* appcache_system)
: system_(appcache_system) {
}
void clear_appcache_system() { system_ = NULL; }
virtual void OnCacheSelected(int host_id,
const appcache::AppCacheInfo& info) OVERRIDE {
if (!system_)
return;
if (system_->is_io_thread()) {
system_->ui_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleFrontendProxy::OnCacheSelected, this, host_id,
info));
} else if (system_->is_ui_thread()) {
system_->frontend_impl_.OnCacheSelected(host_id, info);
} else {
NOTREACHED();
}
}
virtual void OnStatusChanged(const std::vector<int>& host_ids,
appcache::Status status) OVERRIDE {
if (!system_)
return;
if (system_->is_io_thread())
system_->ui_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleFrontendProxy::OnStatusChanged, this, host_ids,
status));
else if (system_->is_ui_thread())
system_->frontend_impl_.OnStatusChanged(host_ids, status);
else
NOTREACHED();
}
virtual void OnEventRaised(const std::vector<int>& host_ids,
appcache::EventID event_id) OVERRIDE {
if (!system_)
return;
if (system_->is_io_thread())
system_->ui_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleFrontendProxy::OnEventRaised, this, host_ids,
event_id));
else if (system_->is_ui_thread())
system_->frontend_impl_.OnEventRaised(host_ids, event_id);
else
NOTREACHED();
}
virtual void OnProgressEventRaised(const std::vector<int>& host_ids,
const GURL& url,
int num_total, int num_complete) OVERRIDE {
if (!system_)
return;
if (system_->is_io_thread())
system_->ui_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleFrontendProxy::OnProgressEventRaised, this,
host_ids, url, num_total, num_complete));
else if (system_->is_ui_thread())
system_->frontend_impl_.OnProgressEventRaised(
host_ids, url, num_total, num_complete);
else
NOTREACHED();
}
virtual void OnErrorEventRaised(const std::vector<int>& host_ids,
const std::string& message) OVERRIDE {
if (!system_)
return;
if (system_->is_io_thread())
system_->ui_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleFrontendProxy::OnErrorEventRaised, this, host_ids,
message));
else if (system_->is_ui_thread())
system_->frontend_impl_.OnErrorEventRaised(
host_ids, message);
else
NOTREACHED();
}
virtual void OnLogMessage(int host_id,
appcache::LogLevel log_level,
const std::string& message) OVERRIDE {
if (!system_)
return;
if (system_->is_io_thread())
system_->ui_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleFrontendProxy::OnLogMessage, this, host_id,
log_level, message));
else if (system_->is_ui_thread())
system_->frontend_impl_.OnLogMessage(
host_id, log_level, message);
else
NOTREACHED();
}
virtual void OnContentBlocked(int host_id,
const GURL& manifest_url) OVERRIDE {}
private:
friend class base::RefCountedThreadSafe<SimpleFrontendProxy>;
virtual ~SimpleFrontendProxy() {}
SimpleAppCacheSystem* system_;
};
// SimpleBackendProxy --------------------------------------------------------
// Proxies method calls from the frontend UI thread to the backend IO thread.
class SimpleBackendProxy
: public base::RefCountedThreadSafe<SimpleBackendProxy>,
public appcache::AppCacheBackend {
public:
explicit SimpleBackendProxy(SimpleAppCacheSystem* appcache_system)
: system_(appcache_system), event_(true, false) {
get_status_callback_ =
base::Bind(&SimpleBackendProxy::GetStatusCallback,
base::Unretained(this));
start_update_callback_ =
base::Bind(&SimpleBackendProxy::StartUpdateCallback,
base::Unretained(this));
swap_cache_callback_=
base::Bind(&SimpleBackendProxy::SwapCacheCallback,
base::Unretained(this));
}
virtual void RegisterHost(int host_id) OVERRIDE {
if (system_->is_ui_thread()) {
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleBackendProxy::RegisterHost, this, host_id));
} else if (system_->is_io_thread()) {
system_->backend_impl_->RegisterHost(host_id);
} else {
NOTREACHED();
}
}
virtual void UnregisterHost(int host_id) OVERRIDE {
if (system_->is_ui_thread()) {
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleBackendProxy::UnregisterHost, this, host_id));
} else if (system_->is_io_thread()) {
system_->backend_impl_->UnregisterHost(host_id);
} else {
NOTREACHED();
}
}
virtual void SetSpawningHostId(int host_id, int spawning_host_id) OVERRIDE {
if (system_->is_ui_thread()) {
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleBackendProxy::SetSpawningHostId, this, host_id,
spawning_host_id));
} else if (system_->is_io_thread()) {
system_->backend_impl_->SetSpawningHostId(host_id, spawning_host_id);
} else {
NOTREACHED();
}
}
virtual void SelectCache(int host_id,
const GURL& document_url,
const int64 cache_document_was_loaded_from,
const GURL& manifest_url) OVERRIDE {
if (system_->is_ui_thread()) {
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleBackendProxy::SelectCache, this, host_id,
document_url, cache_document_was_loaded_from,
manifest_url));
} else if (system_->is_io_thread()) {
system_->backend_impl_->SelectCache(host_id, document_url,
cache_document_was_loaded_from,
manifest_url);
} else {
NOTREACHED();
}
}
virtual void GetResourceList(
int host_id,
std::vector<appcache::AppCacheResourceInfo>* resource_infos) OVERRIDE {
if (system_->is_ui_thread()) {
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleBackendProxy::GetResourceList, this, host_id,
resource_infos));
} else if (system_->is_io_thread()) {
system_->backend_impl_->GetResourceList(host_id, resource_infos);
} else {
NOTREACHED();
}
}
virtual void SelectCacheForWorker(
int host_id,
int parent_process_id,
int parent_host_id) OVERRIDE {
NOTIMPLEMENTED(); // Workers are not supported in test_shell.
}
virtual void SelectCacheForSharedWorker(
int host_id,
int64 appcache_id) OVERRIDE {
NOTIMPLEMENTED(); // Workers are not supported in test_shell.
}
virtual void MarkAsForeignEntry(
int host_id,
const GURL& document_url,
int64 cache_document_was_loaded_from) OVERRIDE {
if (system_->is_ui_thread()) {
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(&SimpleBackendProxy::MarkAsForeignEntry, this, host_id,
document_url, cache_document_was_loaded_from));
} else if (system_->is_io_thread()) {
system_->backend_impl_->MarkAsForeignEntry(
host_id, document_url,
cache_document_was_loaded_from);
} else {
NOTREACHED();
}
}
virtual appcache::Status GetStatus(int host_id) OVERRIDE {
if (system_->is_ui_thread()) {
status_result_ = appcache::UNCACHED;
event_.Reset();
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&SimpleBackendProxy::GetStatus),
this, host_id));
event_.Wait();
} else if (system_->is_io_thread()) {
system_->backend_impl_->GetStatusWithCallback(
host_id, get_status_callback_, NULL);
} else {
NOTREACHED();
}
return status_result_;
}
virtual bool StartUpdate(int host_id) OVERRIDE {
if (system_->is_ui_thread()) {
bool_result_ = false;
event_.Reset();
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&SimpleBackendProxy::StartUpdate),
this, host_id));
event_.Wait();
} else if (system_->is_io_thread()) {
system_->backend_impl_->StartUpdateWithCallback(
host_id, start_update_callback_, NULL);
} else {
NOTREACHED();
}
return bool_result_;
}
virtual bool SwapCache(int host_id) OVERRIDE {
if (system_->is_ui_thread()) {
bool_result_ = false;
event_.Reset();
system_->io_message_loop()->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&SimpleBackendProxy::SwapCache),
this, host_id));
event_.Wait();
} else if (system_->is_io_thread()) {
system_->backend_impl_->SwapCacheWithCallback(
host_id, swap_cache_callback_, NULL);
} else {
NOTREACHED();
}
return bool_result_;
}
void GetStatusCallback(appcache::Status status, void* param) {
status_result_ = status;
event_.Signal();
}
void StartUpdateCallback(bool result, void* param) {
bool_result_ = result;
event_.Signal();
}
void SwapCacheCallback(bool result, void* param) {
bool_result_ = result;
event_.Signal();
}
void SignalEvent() {
event_.Signal();
}
private:
friend class base::RefCountedThreadSafe<SimpleBackendProxy>;
virtual ~SimpleBackendProxy() {}
SimpleAppCacheSystem* system_;
base::WaitableEvent event_;
bool bool_result_;
appcache::Status status_result_;
appcache::GetStatusCallback get_status_callback_;
appcache::StartUpdateCallback start_update_callback_;
appcache::SwapCacheCallback swap_cache_callback_;
};
// SimpleAppCacheSystem --------------------------------------------------------
// This class only works for a single process browser.
static const int kSingleProcessId = 1;
// A not so thread safe singleton, but should work for test_shell.
SimpleAppCacheSystem* SimpleAppCacheSystem::instance_ = NULL;
SimpleAppCacheSystem::SimpleAppCacheSystem()
: io_message_loop_(NULL), ui_message_loop_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(
backend_proxy_(new SimpleBackendProxy(this))),
ALLOW_THIS_IN_INITIALIZER_LIST(
frontend_proxy_(new SimpleFrontendProxy(this))),
backend_impl_(NULL), service_(NULL), db_thread_("AppCacheDBThread") {
DCHECK(!instance_);
instance_ = this;
}
static void SignalEvent(base::WaitableEvent* event) {
event->Signal();
}
SimpleAppCacheSystem::~SimpleAppCacheSystem() {
DCHECK(!io_message_loop_ && !backend_impl_ && !service_);
frontend_proxy_->clear_appcache_system(); // in case a task is in transit
instance_ = NULL;
if (db_thread_.IsRunning()) {
// We pump a task thru the db thread to ensure any tasks previously
// scheduled on that thread have been performed prior to return.
base::WaitableEvent event(false, false);
db_thread_.message_loop()->PostTask(
FROM_HERE, base::Bind(&SignalEvent, &event));
event.Wait();
}
}
void SimpleAppCacheSystem::InitOnUIThread(
const base::FilePath& cache_directory) {
DCHECK(!ui_message_loop_);
ui_message_loop_ = MessageLoop::current();
cache_directory_ = cache_directory;
}
void SimpleAppCacheSystem::InitOnIOThread(
net::URLRequestContext* request_context) {
if (!is_initailized_on_ui_thread())
return;
DCHECK(!io_message_loop_);
io_message_loop_ = MessageLoop::current();
if (!db_thread_.IsRunning())
db_thread_.Start();
// Recreate and initialize per each IO thread.
service_ = new appcache::AppCacheService(NULL);
backend_impl_ = new appcache::AppCacheBackendImpl();
service_->Initialize(cache_directory_,
db_thread_.message_loop_proxy(),
SimpleResourceLoaderBridge::GetCacheThread());
service_->set_request_context(request_context);
backend_impl_->Initialize(service_, frontend_proxy_.get(), kSingleProcessId);
AppCacheInterceptor::EnsureRegistered();
}
void SimpleAppCacheSystem::CleanupIOThread() {
DCHECK(is_io_thread());
delete backend_impl_;
delete service_;
backend_impl_ = NULL;
service_ = NULL;
io_message_loop_ = NULL;
// Just in case the main thread is waiting on it.
backend_proxy_->SignalEvent();
}
WebApplicationCacheHost* SimpleAppCacheSystem::CreateCacheHostForWebKit(
WebApplicationCacheHostClient* client) {
if (!is_initailized_on_ui_thread())
return NULL;
DCHECK(is_ui_thread());
// The IO thread needs to be running for this system to work.
SimpleResourceLoaderBridge::EnsureIOThread();
if (!is_initialized())
return NULL;
return new WebApplicationCacheHostImpl(client, backend_proxy_.get());
}
void SimpleAppCacheSystem::SetExtraRequestBits(
net::URLRequest* request, int host_id, ResourceType::Type resource_type) {
if (is_initialized()) {
DCHECK(is_io_thread());
AppCacheInterceptor::SetExtraRequestInfo(
request, service_, kSingleProcessId, host_id, resource_type);
}
}
void SimpleAppCacheSystem::GetExtraResponseBits(
net::URLRequest* request, int64* cache_id, GURL* manifest_url) {
if (is_initialized()) {
DCHECK(is_io_thread());
AppCacheInterceptor::GetExtraResponseInfo(
request, cache_id, manifest_url);
}
}
| 32.472222 | 80 | 0.649931 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.