hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f41386ed732c16e12d9272c3610a72b476cb478e | 1,584 | cpp | C++ | Source/Life/Systems/Persistent/AiSystem.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | 5 | 2022-02-09T21:19:03.000Z | 2022-03-03T01:53:03.000Z | Source/Life/Systems/Persistent/AiSystem.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | Source/Life/Systems/Persistent/AiSystem.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | #include "Life/Systems/Persistent/AiSystem.h"
#include "Systems/Public/SystemsWorld.h"
#include "Life/AI/Reasoner/UtilityAiReasoner.h"
#include "Life/Components/AiComponent.h"
#include "Life/Components/CameraRelationComponent.h"
#include "Life/Components/GodComponent.h"
#include "Life/Resources/LifeSettings.h"
struct Meta
{
float Difference = 0;
float DecideDelay = 0;
};
void AiSystem(USystemsWorld& Systems)
{
const auto* Settings = Systems.Resource<ULifeSettings>();
if (IsValid(Settings) == false)
{
return;
}
const auto& LOD = Settings->AiLOD;
const auto DeltaTime = Systems.GetWorld()->GetDeltaSeconds();
const auto TimePassed = Settings->TimeScale * DeltaTime;
Systems.Query<UAiComponent, UCameraRelationComponent>().ForEach(
[&](auto& QueryItem)
{
const auto* Actor = QueryItem.Get<0>();
auto* Ai = QueryItem.Get<1>();
if (IsValid(Ai->Reasoner) == false)
{
return;
}
const auto* CameraRelation = QueryItem.Get<2>();
const auto Found = IterStdConst(LOD)
.Map<Meta>(
[&](const auto& Info)
{
const auto Difference =
FMath::Abs(Info.Distance - CameraRelation->Distance);
return CameraRelation->bIsVisible
? Meta{Difference, Info.DecideDelay}
: Meta{Difference, Info.DecideOffscreenDelay};
})
.ComparedBy([](const auto& A, const auto& B)
{ return A.Difference < B.Difference; });
if (Found.IsSet())
{
Ai->TryDecide(Systems, Found.GetValue().DecideDelay, TimePassed);
}
});
}
| 25.967213 | 69 | 0.649621 | PsichiX |
f415f4bd939960f2b217cc981dc313b67abed267 | 1,365 | cpp | C++ | morse/DotNet/graph_simplex/SIRom.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | 1 | 2019-12-24T15:52:45.000Z | 2019-12-24T15:52:45.000Z | morse/DotNet/graph_simplex/SIRom.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | morse/DotNet/graph_simplex/SIRom.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "SIRom.h"
#include "../graph/Graph.h"
#include "../SystemFunction/ISystemFunctionDerivate.h"
#include <math.h>
SIRom::SIRom(Graph* graph, ISystemFunctionDerivate* function) : CRom(graph), graph(graph), function(function)
{
input = function->getInput();
output = function->getOutput();
dimension = graph->getDimention();
cout<<"SI Rom for dimension = "<<dimension<<endl;
}
SIRom::~SIRom(void)
{
cout<<"SIRom dispose"<<endl;
}
double SIRom::cost(Node* node) {
for (int i=0; i<dimension; i++) {
input[i] = graph->toExternal(graph->getCells(node)[i], i) + graph->getEps()[i]/2;
}
function->evaluate();
return log(Abs(exhaussDet())) * factor;
}
double inline SIRom::getAt(int i, int j) {
return output[i+j*dimension + dimension];
}
double inline SIRom::Abs(double x) {
return (x>0)?x:-x;
}
double inline SIRom::exhaussDet() {
//gaus method for triangle matrix
switch (dimension) {
case 1:
return getAt(0,0);
case 2:
return getAt(0,0)*getAt(1,1)-getAt(1,0)*getAt(0,1);
case 3:
//maple generated
return getAt(0,0)*getAt(1,1)*getAt(2,2)
-getAt(0,0)*getAt(1,2)*getAt(2,1)
+getAt(1,0)*getAt(0,2)*getAt(2,1)
-getAt(1,0)*getAt(0,1)*getAt(2,2)
+getAt(2,0)*getAt(0,1)*getAt(1,2)
-getAt(2,0)*getAt(0,2)*getAt(1,1);
default:
ASSERT(false);
}
return 0;
}
| 21.328125 | 109 | 0.634432 | jonnyzzz |
f41663583ff9e6b610256f6729cc0c92d8be0f41 | 92 | cpp | C++ | node_modules/lzz-gyp/lzz-source/smtc_Access.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/smtc_Access.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/smtc_Access.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // smtc_Access.cpp
//
#include "smtc_Access.h"
#define LZZ_INLINE inline
#undef LZZ_INLINE
| 13.142857 | 25 | 0.76087 | SuperDizor |
f41d35b2f4ee2ad35d042e78b16825068ac41d7e | 2,046 | cpp | C++ | Ch 15/15.34_35_36_37_38/main.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 15/15.34_35_36_37_38/main.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 15/15.34_35_36_37_38/main.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | // 15.34 针对图15.3(pp565)构建的表达式:
// (a) 列举出在处理表达式的过程中执行的所有构造函数
// Query q = Query("fiery") & Query("bird") | Query("wind");
// 1: Query::Query(const std::string &s) where s = "fiery", "bird" and "wind"
// 2: WordQuery::WordQuery(const std::string &s) where s = "fiery", "bird" and "wind"
// 3: AndQuery::AndQuery(const Query &left, const Query &right)
// 4: BinaryQuery::BinayQuery(const Query &l, const Query &r, std::string s) where s = "&"
// 5: Query::Query(std::shared_ptr<Query_base> query) 2 times
// 6: OrQuery::OrQuery(const Query &left, const Query &right)
// 7: BinaryQuery::BinaryQuery(const Query &l, const Query &r, std::string s) where s = "|"
// 8: Quer::Query(std::shared_ptr<Query_base> query) 2 times
//
// (b) 列举出cout<<q所调用的rep
//
// Query::rep()
// BinaryQuery::rep()
// Query::rep()
// WordQuery::rep()
// Query::rep()
// BinaryQuery::rep()
// Query::rep()
// WordQuery::rep()
// Query::rep()
// WordQuery::rep()
// ((fiery & bird) | wind)
//
// (c) 列举出q.eval()所调用的eval
//
// 15.35 实现Query类和Query_base类,其中需要定义rep无需定义eval
//
// 15.36 在构造函数和rep成员中添加打印语句,运行代码以检验(a)(b)的回答是否正确
// 需要定义eval
/*
(a)
WordQuery::WordQuery(wind)
Query::Query(const std::sting &s) where s= wind
WordQuery::WordQuery(bird)
Query::Query(const std::sting &s) where s= bird
WordQuery::WordQuery(fiery)
Query::Query(const std::sting &s) where s= fiery
BinayQuery::BinaryQuery() where s=&
AndQuery::AndQuery()
BinayQuery::BinaryQuery() where s=|
OrQuery::OrQuery()
(b)
Query::rep()
BinaryQuery::rep()
Query::rep()
WordQuery::rep()
Query::rep()
BinaryQuery::rep()
Query::rep()
WordQuery::rep()
Query::rep()
WordQuery::rep()
((fiery & bird) | wind)
*/
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <fstream>
#include "queryresult.h"
#include "textquery.h"
#include "query_base.h"
#include "query.h"
#include "andquery.h"
#include "orquery.h"
int main()
{
std::ifstream file("data/story.txt");
TextQuery tQuery(file);
Query q = Query("fiery") & Query("bird") | Query("wind");
std::cout << q << std::endl;
return 0;
} | 25.575 | 91 | 0.668133 | Felon03 |
f41d5caa99623ed28364db2edb2e52236fad31b4 | 6,498 | cxx | C++ | tomviz/Module.cxx | yijiang1/tomviz | 93bf1b0f3ebc1d55db706184339a94660fb08d91 | [
"BSD-3-Clause"
] | null | null | null | tomviz/Module.cxx | yijiang1/tomviz | 93bf1b0f3ebc1d55db706184339a94660fb08d91 | [
"BSD-3-Clause"
] | null | null | null | tomviz/Module.cxx | yijiang1/tomviz | 93bf1b0f3ebc1d55db706184339a94660fb08d91 | [
"BSD-3-Clause"
] | 1 | 2021-01-14T02:25:32.000Z | 2021-01-14T02:25:32.000Z | /******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "Module.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "pqProxiesWidget.h"
#include "pqView.h"
#include "Utilities.h"
#include "vtkNew.h"
#include "vtkSmartPointer.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMTransferFunctionManager.h"
#include "vtkSMViewProxy.h"
namespace tomviz
{
class Module::MInternals
{
vtkSmartPointer<vtkSMProxy> DetachedColorMap;
vtkSmartPointer<vtkSMProxy> DetachedOpacityMap;
public:
vtkWeakPointer<vtkSMProxy> ColorMap;
vtkWeakPointer<vtkSMProxy> OpacityMap;
vtkSMProxy* detachedColorMap()
{
if (!this->DetachedColorMap)
{
static unsigned int colorMapCounter=0;
colorMapCounter++;
vtkSMSessionProxyManager* pxm = ActiveObjects::instance().proxyManager();
vtkNew<vtkSMTransferFunctionManager> tfmgr;
this->DetachedColorMap = tfmgr->GetColorTransferFunction(QString("ModuleColorMap%1")
.arg(colorMapCounter).toLatin1().data(),
pxm);
this->DetachedOpacityMap = vtkSMPropertyHelper(this->DetachedColorMap,
"ScalarOpacityFunction").GetAsProxy();
}
return this->DetachedColorMap;
}
vtkSMProxy* detachedOpacityMap()
{
this->detachedColorMap();
return this->DetachedOpacityMap;
}
};
//-----------------------------------------------------------------------------
Module::Module(QObject* parentObject) : Superclass(parentObject),
UseDetachedColorMap(false),
Internals(new Module::MInternals())
{
}
//-----------------------------------------------------------------------------
Module::~Module()
{
}
//-----------------------------------------------------------------------------
bool Module::initialize(DataSource* dataSource, vtkSMViewProxy* view)
{
this->View = view;
this->ADataSource = dataSource;
if (this->View && this->ADataSource)
{
// FIXME: we're connecting this too many times. Fix it.
tomviz::convert<pqView*>(view)->connect(
this->ADataSource, SIGNAL(dataChanged()), SLOT(render()));
}
return (this->View && this->ADataSource);
}
//-----------------------------------------------------------------------------
vtkSMViewProxy* Module::view() const
{
return this->View;
}
//-----------------------------------------------------------------------------
DataSource* Module::dataSource() const
{
return this->ADataSource;
}
//-----------------------------------------------------------------------------
void Module::addToPanel(pqProxiesWidget* panel)
{
if (this->UseDetachedColorMap)
{
// add color map to the panel, since it's detached from the dataSource.
vtkSMProxy* lut = this->colorMap();
QStringList list;
list
<< "Mapping Data"
<< "EnableOpacityMapping"
<< "RGBPoints"
<< "ScalarOpacityFunction"
<< "UseLogScale";
panel->addProxy(lut, "Module Color Map", list, true);
}
}
//-----------------------------------------------------------------------------
void Module::setUseDetachedColorMap(bool val)
{
this->UseDetachedColorMap = val;
if (this->isColorMapNeeded() == false)
{
return;
}
if (this->UseDetachedColorMap)
{
this->Internals->ColorMap = this->Internals->detachedColorMap();
this->Internals->OpacityMap = this->Internals->detachedOpacityMap();
tomviz::rescaleColorMap(this->Internals->ColorMap, this->dataSource());
}
else
{
this->Internals->ColorMap = NULL;
this->Internals->OpacityMap = NULL;
}
this->updateColorMap();
}
//-----------------------------------------------------------------------------
vtkSMProxy* Module::colorMap() const
{
return this->useDetachedColorMap()? this->Internals->ColorMap.GetPointer():
this->dataSource()->colorMap();
}
//-----------------------------------------------------------------------------
vtkSMProxy* Module::opacityMap() const
{
Q_ASSERT(this->Internals->ColorMap || !this->UseDetachedColorMap);
return this->useDetachedColorMap()? this->Internals->OpacityMap.GetPointer():
this->dataSource()->opacityMap();
}
//-----------------------------------------------------------------------------
bool Module::serialize(pugi::xml_node& ns) const
{
if (this->isColorMapNeeded())
{
ns.append_attribute("use_detached_colormap").set_value(this->UseDetachedColorMap? 1 : 0);
if (this->UseDetachedColorMap)
{
pugi::xml_node nodeL = ns.append_child("ColorMap");
pugi::xml_node nodeS = ns.append_child("OpacityMap");
// using detached color map, so we need to save the local color map.
if (tomviz::serialize(this->colorMap(), nodeL) == false ||
tomviz::serialize(this->opacityMap(), nodeS) == false)
{
return false;
}
}
}
return true;
}
//-----------------------------------------------------------------------------
bool Module::deserialize(const pugi::xml_node& ns)
{
if (this->isColorMapNeeded())
{
bool dcm = ns.attribute("use_detached_colormap").as_int(0) == 1;
if (dcm && ns.child("ColorMap"))
{
if (!tomviz::deserialize(this->Internals->detachedColorMap(), ns.child("ColorMap")))
{
qCritical("Failed to deserialze ColorMap");
return false;
}
}
if (dcm && ns.child("OpacityMap"))
{
if (!tomviz::deserialize(this->Internals->detachedOpacityMap(), ns.child("OpacityMap")))
{
qCritical("Failed to deserialze OpacityMap");
return false;
}
}
this->setUseDetachedColorMap(dcm);
}
return true;
}
//-----------------------------------------------------------------------------
} // end of namespace tomviz
| 30.223256 | 103 | 0.544629 | yijiang1 |
f420330cd14e6e035795bb4f65932d3ceb96aeb6 | 14,297 | cpp | C++ | nntrainer/src/databuffer.cpp | dongju-chae/nntrainer | 9742569355e1d787ccb4818b7c827bc95662cbe9 | [
"Apache-2.0"
] | 1 | 2022-03-27T18:56:11.000Z | 2022-03-27T18:56:11.000Z | nntrainer/src/databuffer.cpp | dongju-chae/nntrainer | 9742569355e1d787ccb4818b7c827bc95662cbe9 | [
"Apache-2.0"
] | 2 | 2021-04-19T11:42:07.000Z | 2021-04-21T10:26:04.000Z | nntrainer/src/databuffer.cpp | dongju-chae/nntrainer | 9742569355e1d787ccb4818b7c827bc95662cbe9 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2019 Samsung Electronics Co., Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @file databuffer.cpp
* @date 04 December 2019
* @brief This is buffer object to handle big data
* @see https://github.com/nnstreamer/nntrainer
* @author Jijoong Moon <jijoong.moon@samsung.com>
* @bug No known bugs except for NYI items
*
*/
#include <cassert>
#include <climits>
#include <condition_variable>
#include <cstring>
#include <databuffer.h>
#include <databuffer_util.h>
#include <functional>
#include <iomanip>
#include <mutex>
#include <nntrainer_error.h>
#include <nntrainer_log.h>
#include <parse_util.h>
#include <sstream>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <util_func.h>
std::exception_ptr globalExceptionPtr = nullptr;
namespace nntrainer {
constexpr char USER_DATA[] = "user_data";
std::mutex data_lock;
std::mutex readyTrainData;
std::mutex readyValData;
std::mutex readyTestData;
std::condition_variable cv_train;
std::condition_variable cv_val;
std::condition_variable cv_test;
DataBuffer::DataBuffer(DataBufferType type) :
train_running(),
val_running(),
test_running(),
train_thread(),
val_thread(),
test_thread(),
data_buffer_type(type),
user_data(nullptr) {
SET_VALIDATION(false);
class_num = 0;
cur_train_bufsize = 0;
cur_val_bufsize = 0;
cur_test_bufsize = 0;
train_bufsize = 0;
val_bufsize = 0;
test_bufsize = 0;
max_train = 0;
max_val = 0;
max_test = 0;
rest_train = 0;
rest_val = 0;
rest_test = 0;
batch_size = 0;
train_running = false;
val_running = false;
test_running = false;
trainReadyFlag = DATA_NOT_READY;
valReadyFlag = DATA_NOT_READY;
testReadyFlag = DATA_NOT_READY;
rng.seed(getSeed());
};
int DataBuffer::rangeRandom(int min, int max) {
std::uniform_int_distribution<int> dist(min, max);
return dist(rng);
}
int DataBuffer::run(BufferType type) {
int status = ML_ERROR_NONE;
switch (type) {
case BufferType::BUF_TRAIN:
if (trainReadyFlag == DATA_ERROR)
return ML_ERROR_INVALID_PARAMETER;
if (validation[DATA_TRAIN]) {
this->train_running = true;
this->train_thread = std::thread(&DataBuffer::updateData, this, type);
if (globalExceptionPtr) {
try {
std::rethrow_exception(globalExceptionPtr);
} catch (const std::exception &ex) {
std::cout << ex.what() << "\n";
return ML_ERROR_INVALID_PARAMETER;
}
}
} else {
ml_loge("Error: Training Data Set is not valid");
return ML_ERROR_INVALID_PARAMETER;
}
break;
case BufferType::BUF_VAL:
if (valReadyFlag == DATA_ERROR)
return ML_ERROR_INVALID_PARAMETER;
if (validation[DATA_VAL]) {
this->val_running = true;
this->val_thread = std::thread(&DataBuffer::updateData, this, type);
if (globalExceptionPtr) {
try {
std::rethrow_exception(globalExceptionPtr);
} catch (const std::exception &ex) {
std::cout << ex.what() << "\n";
return ML_ERROR_INVALID_PARAMETER;
}
}
} else {
ml_loge("Error: Validation Data Set is not valid");
return ML_ERROR_INVALID_PARAMETER;
}
break;
case BufferType::BUF_TEST:
if (testReadyFlag == DATA_ERROR)
return ML_ERROR_INVALID_PARAMETER;
if (validation[DATA_TEST]) {
this->test_running = true;
this->test_thread = std::thread(&DataBuffer::updateData, this, type);
if (globalExceptionPtr) {
try {
std::rethrow_exception(globalExceptionPtr);
} catch (const std::exception &ex) {
std::cout << ex.what() << "\n";
return ML_ERROR_INVALID_PARAMETER;
}
}
} else {
ml_loge("Error: Test Data Set is not valid");
return ML_ERROR_INVALID_PARAMETER;
}
break;
default:
ml_loge("Error: Not Supported Data Type");
status = ML_ERROR_INVALID_PARAMETER;
break;
}
return status;
}
int DataBuffer::clear(BufferType type) {
int status = ML_ERROR_NONE;
NN_EXCEPTION_NOTI(DATA_NOT_READY);
switch (type) {
case BufferType::BUF_TRAIN: {
train_running = false;
if (validation[DATA_TRAIN] && true == train_thread.joinable())
train_thread.join();
this->train_data.clear();
this->train_data_label.clear();
this->cur_train_bufsize = 0;
this->rest_train = max_train;
} break;
case BufferType::BUF_VAL: {
val_running = false;
if (validation[DATA_VAL] && true == val_thread.joinable())
val_thread.join();
this->val_data.clear();
this->val_data_label.clear();
this->cur_val_bufsize = 0;
this->rest_val = max_val;
} break;
case BufferType::BUF_TEST: {
test_running = false;
if (validation[DATA_TEST] && true == test_thread.joinable())
test_thread.join();
this->test_data.clear();
this->test_data_label.clear();
this->cur_test_bufsize = 0;
this->rest_test = max_test;
} break;
default:
ml_loge("Error: Not Supported Data Type");
status = ML_ERROR_INVALID_PARAMETER;
break;
}
return status;
}
int DataBuffer::clear() {
unsigned int i;
int status = ML_ERROR_NONE;
for (i = (int)BufferType::BUF_TRAIN; i <= (int)BufferType::BUF_TEST; ++i) {
BufferType type = static_cast<BufferType>(i);
status = this->clear(type);
if (status != ML_ERROR_NONE) {
ml_loge("Error: error occurred during clearing");
return status;
}
}
return status;
}
bool DataBuffer::getDataFromBuffer(BufferType type, float *out, float *label) {
using QueueType = std::vector<std::vector<float>>;
auto wait_for_data_fill = [](std::mutex &ready_mutex,
std::condition_variable &cv, DataStatus &flag,
const unsigned int batch_size,
QueueType &queue) {
while (true) {
std::unique_lock<std::mutex> ul(ready_mutex);
cv.wait(ul, [&]() -> bool { return flag; });
if (flag == DATA_ERROR || flag == DATA_END)
return queue.size() < batch_size ? false : true;
if (flag == DATA_READY && queue.size() >= batch_size)
return true;
}
throw std::logic_error("[getDataFromBuffer] control should not reach here");
};
auto fill_bundled_data_from_queue =
[](std::mutex &q_lock, QueueType &q, const unsigned int batch_size,
const unsigned int feature_size, float *buf) {
for (unsigned int b = 0; b < batch_size; ++b)
std::copy(q[b].begin(), q[b].begin() + feature_size,
buf + b * feature_size);
q_lock.lock();
q.erase(q.begin(), q.begin() + batch_size);
q_lock.unlock();
};
/// facade that wait for the databuffer to be filled and pass it to outparam
/// note that batch_size is passed as an argument because it can vary by
/// BufferType::BUF_TYPE later...
auto fill_out_params =
[&](std::mutex &ready_mutex, std::condition_variable &cv, DataStatus &flag,
QueueType &data_q, QueueType &label_q, const unsigned int batch_size,
unsigned int &cur_bufsize) {
if (!wait_for_data_fill(ready_mutex, cv, flag, batch_size, data_q)) {
return false;
}
fill_bundled_data_from_queue(data_lock, data_q, batch_size,
this->input_dim.getFeatureLen(), out);
fill_bundled_data_from_queue(data_lock, label_q, batch_size,
this->class_num, label);
cur_bufsize -= batch_size;
return true;
};
switch (type) {
case BufferType::BUF_TRAIN:
if (!fill_out_params(readyTrainData, cv_train, trainReadyFlag, train_data,
train_data_label, batch_size, cur_train_bufsize))
return false;
break;
case BufferType::BUF_VAL:
if (!fill_out_params(readyValData, cv_val, valReadyFlag, val_data,
val_data_label, batch_size, cur_val_bufsize))
return false;
break;
case BufferType::BUF_TEST:
if (!fill_out_params(readyTestData, cv_test, testReadyFlag, test_data,
test_data_label, batch_size, cur_test_bufsize))
return false;
break;
default:
ml_loge("Error: Not Supported Data Type");
return false;
break;
}
return true;
}
int DataBuffer::setClassNum(unsigned int num) {
int status = ML_ERROR_NONE;
if (num <= 0) {
ml_loge("Error: number of class should be bigger than 0");
SET_VALIDATION(false);
return ML_ERROR_INVALID_PARAMETER;
}
if (class_num != 0 && class_num != num) {
ml_loge("Error: number of class should be same with number of label label");
SET_VALIDATION(false);
return ML_ERROR_INVALID_PARAMETER;
}
class_num = num;
return status;
}
int DataBuffer::setBufSize(unsigned int size) {
int status = ML_ERROR_NONE;
train_bufsize = size;
val_bufsize = size;
test_bufsize = size;
return status;
}
int DataBuffer::setBatchSize(unsigned int size) {
int status = ML_ERROR_NONE;
if (size == 0) {
ml_loge("Error: batch size must be greater than 0");
SET_VALIDATION(false);
return ML_ERROR_INVALID_PARAMETER;
}
batch_size = size;
return status;
}
int DataBuffer::init() {
if (batch_size == 0) {
ml_loge("Error: batch size must be greater than 0");
SET_VALIDATION(false);
return ML_ERROR_INVALID_PARAMETER;
}
/** for now, train_bufsize, val_bufsize and test_bufsize are same value */
if (train_bufsize < batch_size) {
if (train_bufsize > 1) {
ml_logw("Dataset buffer size reset to be at least batch size");
}
train_bufsize = batch_size;
val_bufsize = batch_size;
test_bufsize = batch_size;
}
if (!class_num) {
ml_loge("Error: number of class must be set");
SET_VALIDATION(false);
return ML_ERROR_INVALID_PARAMETER;
}
if (!this->input_dim.getFeatureLen()) {
ml_loge("Error: feature size must be set");
SET_VALIDATION(false);
return ML_ERROR_INVALID_PARAMETER;
}
this->cur_train_bufsize = 0;
this->cur_val_bufsize = 0;
this->cur_test_bufsize = 0;
readyTrainData.lock();
trainReadyFlag = DATA_NOT_READY;
readyTrainData.unlock();
readyValData.lock();
valReadyFlag = DATA_NOT_READY;
readyValData.unlock();
readyTestData.lock();
testReadyFlag = DATA_NOT_READY;
readyTestData.unlock();
return ML_ERROR_NONE;
}
int DataBuffer::setFeatureSize(TensorDim indim) {
int status = ML_ERROR_NONE;
input_dim = indim;
return status;
}
void DataBuffer::displayProgress(const int count, BufferType type, float loss) {
int barWidth = 20;
float max_size = max_train;
switch (type) {
case BufferType::BUF_TRAIN:
max_size = max_train;
break;
case BufferType::BUF_VAL:
max_size = max_val;
break;
case BufferType::BUF_TEST:
max_size = max_test;
break;
default:
ml_loge("Error: Not Supported Data Type");
break;
}
std::stringstream ssInt;
ssInt << count * batch_size;
std::string str = ssInt.str();
int len = str.length();
if (max_size == 0) {
int pad_left = (barWidth - len) / 2;
int pad_right = barWidth - pad_left - len;
std::string out_str =
std::string(pad_left, ' ') + str + std::string(pad_right, ' ');
std::cout << " [ ";
std::cout << out_str;
std::cout << " ] "
<< " ( Training Loss: " << loss << " )\r";
} else {
float progress;
if (batch_size > max_size)
progress = 1.0;
else
progress = (((float)(count * batch_size)) / max_size);
int pos = barWidth * progress;
std::cout << " [ ";
for (int l = 0; l < barWidth; ++l) {
if (l <= pos)
std::cout << "=";
else
std::cout << " ";
}
std::cout << " ] " << int(progress * 100.0) << "% ( Training Loss: " << loss
<< " )\r";
}
std::cout.flush();
}
int DataBuffer::setProperty(std::vector<void *> values) {
int status = ML_ERROR_NONE;
std::vector<std::string> properties;
for (unsigned int i = 0; i < values.size(); ++i) {
char *key_ptr = (char *)values[i];
std::string key = key_ptr;
std::string value;
/** Handle the user_data as a special case */
if (key == USER_DATA) {
/** This ensures that a valid user_data element is passed by the user */
if (i + 1 >= values.size())
return ML_ERROR_INVALID_PARAMETER;
this->user_data = values[i + 1];
/** As values of i+1 is consumed, increase i by 1 */
i++;
} else {
properties.push_back(key);
continue;
}
}
status = setProperty(properties);
return status;
}
int DataBuffer::setProperty(std::vector<std::string> values) {
int status = ML_ERROR_NONE;
for (unsigned int i = 0; i < values.size(); ++i) {
std::string key;
std::string value;
status = getKeyValue(values[i], key, value);
NN_RETURN_STATUS();
unsigned int type = parseDataProperty(key);
if (value.empty())
return ML_ERROR_INVALID_PARAMETER;
status = setProperty(static_cast<PropertyType>(type), value);
NN_RETURN_STATUS();
}
return status;
}
int DataBuffer::setProperty(const PropertyType type, std::string &value) {
int status = ML_ERROR_NONE;
unsigned int size = 0;
switch (type) {
case PropertyType::buffer_size:
status = setUint(size, value);
NN_RETURN_STATUS();
status = this->setBufSize(size);
NN_RETURN_STATUS();
break;
default:
ml_loge("Error: Unknown Data Buffer Property Key");
status = ML_ERROR_INVALID_PARAMETER;
break;
}
return status;
}
int DataBuffer::setGeneratorFunc(BufferType type, datagen_cb func) {
return ML_ERROR_NOT_SUPPORTED;
}
int DataBuffer::setDataFile(DataType type, std::string path) {
return ML_ERROR_NOT_SUPPORTED;
}
} /* namespace nntrainer */
| 27.441459 | 80 | 0.650206 | dongju-chae |
f421a9c67194078f59b1357e593efd2c97a4777d | 5,110 | cpp | C++ | src/ClientLib/VisualEntity.cpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | src/ClientLib/VisualEntity.cpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | src/ClientLib/VisualEntity.cpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#include <ClientLib/VisualEntity.hpp>
#include <ClientLib/LocalLayerEntity.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/World.hpp>
namespace bw
{
VisualEntity::VisualEntity(Ndk::World& renderWorld, LocalLayerEntityHandle layerEntityHandle, int baseRenderOrder) :
m_entity(renderWorld.CreateEntity()),
m_layerEntity(std::move(layerEntityHandle)),
m_baseRenderOrder(baseRenderOrder)
{
m_entity->AddComponent<Ndk::NodeComponent>();
m_entity->AddComponent<Ndk::GraphicsComponent>();
m_layerEntity->RegisterVisualEntity(this);
}
VisualEntity::VisualEntity(Ndk::World& renderWorld, LocalLayerEntityHandle layerEntityHandle, const Nz::Node& parentNode, int baseRenderOrder) :
VisualEntity(renderWorld, std::move(layerEntityHandle), baseRenderOrder)
{
m_entity->GetComponent<Ndk::NodeComponent>().SetParent(parentNode);
}
VisualEntity::VisualEntity(VisualEntity&& entity) noexcept :
m_hoveringRenderables(std::move(entity.m_hoveringRenderables)),
m_entity(std::move(entity.m_entity)),
m_layerEntity(std::move(entity.m_layerEntity)),
m_baseRenderOrder(entity.m_baseRenderOrder)
{
m_layerEntity->NotifyVisualEntityMoved(&entity, this);
}
VisualEntity::~VisualEntity()
{
if (m_layerEntity)
m_layerEntity->UnregisterVisualEntity(this);
}
void VisualEntity::Update(const Nz::Vector2f& position, const Nz::Quaternionf& rotation, const Nz::Vector2f& scale)
{
auto& visualNode = m_entity->GetComponent<Ndk::NodeComponent>();
visualNode.SetPosition(position);
visualNode.SetRotation(rotation);
visualNode.SetScale(scale);
Nz::Vector2f absolutePosition = Nz::Vector2f(visualNode.GetPosition(Nz::CoordSys_Global));
absolutePosition.x = std::floor(absolutePosition.x);
absolutePosition.y = std::floor(absolutePosition.y);
visualNode.SetPosition(absolutePosition, Nz::CoordSys_Global);
if (!m_hoveringRenderables.empty())
{
auto& visualGfx = m_entity->GetComponent<Ndk::GraphicsComponent>();
Nz::Vector3f absoluteScale = visualNode.GetScale(Nz::CoordSys_Global);
Nz::Vector2f positiveScale(std::abs(absoluteScale.x), std::abs(absoluteScale.y));
const Nz::Boxf& aabb = visualGfx.GetAABB();
float halfHeight = aabb.height / 2.f;
Nz::Vector3f center = aabb.GetCenter();
for (auto& hoveringRenderable : m_hoveringRenderables)
{
auto& node = hoveringRenderable.entity->GetComponent<Ndk::NodeComponent>();
node.SetPosition(center.x, center.y - (halfHeight + hoveringRenderable.offset) * absoluteScale.y);
node.SetScale(positiveScale);
}
}
}
void VisualEntity::AttachHoveringRenderables(std::initializer_list<Nz::InstancedRenderableRef> renderables, std::initializer_list<Nz::Matrix4f> offsetMatrices, float hoverOffset, std::initializer_list<int> renderOrders)
{
std::size_t renderableCount = renderables.size();
assert(renderableCount == offsetMatrices.size());
assert(renderableCount == renderOrders.size());
assert(renderables.size() > 0);
auto& hoveringRenderable = m_hoveringRenderables.emplace_back();
hoveringRenderable.entity = m_entity->GetWorld()->CreateEntity();
hoveringRenderable.entity->AddComponent<Ndk::NodeComponent>();
hoveringRenderable.offset = hoverOffset;
auto& gfxComponent = hoveringRenderable.entity->AddComponent<Ndk::GraphicsComponent>();
auto renderableIt = renderables.begin();
auto renderOrderIt = renderOrders.begin();
auto matrixIt = offsetMatrices.begin();
for (std::size_t i = 0; i < renderableCount; ++i)
gfxComponent.Attach(*renderableIt++, *matrixIt++, m_baseRenderOrder + *renderOrderIt++);
}
void VisualEntity::AttachRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder)
{
m_entity->GetComponent<Ndk::GraphicsComponent>().Attach(std::move(renderable), offsetMatrix, m_baseRenderOrder + renderOrder);
}
void VisualEntity::DetachRenderable(const Nz::InstancedRenderableRef& renderable)
{
m_entity->GetComponent<Ndk::GraphicsComponent>().Detach(renderable);
}
void VisualEntity::UpdateRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix)
{
m_entity->GetComponent<Ndk::GraphicsComponent>().UpdateLocalMatrix(renderable, offsetMatrix);
}
void VisualEntity::UpdateRenderableRenderOrder(const Nz::InstancedRenderableRef& renderable, int renderOrder)
{
m_entity->GetComponent<Ndk::GraphicsComponent>().UpdateRenderOrder(renderable, m_baseRenderOrder + renderOrder);
}
void VisualEntity::DetachHoveringRenderables(std::initializer_list<Nz::InstancedRenderableRef> renderables)
{
for (auto it = m_hoveringRenderables.begin(); it != m_hoveringRenderables.end(); ++it)
{
auto& hoveringRenderable = *it;
if (std::equal(hoveringRenderable.renderables.begin(), hoveringRenderable.renderables.end(), renderables.begin(), renderables.end()))
{
m_hoveringRenderables.erase(it);
break;
}
}
}
}
| 38.421053 | 220 | 0.76908 | ImperatorS79 |
f4258645452b668d1edcc886ed26b657edee8127 | 8,535 | cpp | C++ | NYUCodebase/hw05/Entity.cpp | MarcNYU/Game-Files | 43781cae89ea02d18930b1b2ead04db400c7f1dd | [
"Artistic-2.0"
] | null | null | null | NYUCodebase/hw05/Entity.cpp | MarcNYU/Game-Files | 43781cae89ea02d18930b1b2ead04db400c7f1dd | [
"Artistic-2.0"
] | null | null | null | NYUCodebase/hw05/Entity.cpp | MarcNYU/Game-Files | 43781cae89ea02d18930b1b2ead04db400c7f1dd | [
"Artistic-2.0"
] | null | null | null | //
// Entity.cpp
// NYUCodebase
//
// Created by Marcus Williams on 2/20/15.
// Copyright (c) 2015 Ivan Safrin. All rights reserved.
//
#include <SDL.h>
#include <SDL_opengl.h>
#include <SDL_image.h>
#include <vector>
#include "Entity.h"
// 60 FPS (1.0f/60.0f)
#define FIXED_TIMESTEP 0.0166666f
#define MAX_TIMESTEPS 6
float timeLeftOver = 0.0f;
void Entity::Render(float elapsed) {
// sprite.u = 0.1;//increment .1
// sprite.v = 0.0;//0
// sprite.v = 0.23;//1
// sprite.v = 0.45;//2
// sprite.v = 0.7;//3
if (name == "player") {
sprite.width = 0.104;
sprite.height = 0.22;
sprite.Draw(scale);
std::vector<float> idel_r_s = {0.0, 0.1};
std::vector<float> idel_r = {0.1, 0.1, 0.1, 0.1, 0.3};
std::vector<float> run_r_s = {0.1, 0.2, 0.1, 0.0};
std::vector<float> run_r = {0.1, 0.2, 0.1, 0.0};
std::vector<float> jump_r_s = {0.3, 0.4};
std::vector<float> jump_r = {0.3, 0.4};
std::vector<float> idel_l_s = {0.9, 0.8};
std::vector<float> idel_l = {0.8, 0.8, 0.8, 0.8, 0.6};
std::vector<float> run_l_s = {0.8, 0.7, 0.8, 0.9};
std::vector<float> run_l = {0.8, 0.7, 0.8, 0.9};
std::vector<float> jump_l_s = {0.6, 0.5};
std::vector<float> jump_l = {0.6, 0.5};
animationElapsed += elapsed;
if(animationElapsed > 1.0/framesPerSecond) {
currentIndex++;
animationElapsed = 0.0;
}
const Uint8 *keys = SDL_GetKeyboardState(NULL);
if (keys[SDL_SCANCODE_SPACE]) {
if(keys[SDL_SCANCODE_RIGHT]) {
if (collidedBottom) {
//Rigth Running Animation
sprite.v = 0.45;
for (currentIndex; currentIndex < run_r_s.size(); currentIndex++) {
sprite.u = run_r_s[currentIndex];
}
if(currentIndex > run_r_s.size()) {
currentIndex = 0;
}
}
} else if(keys[SDL_SCANCODE_LEFT]) {
if (collidedBottom) {
//Left Running Animation
sprite.v = 0.45;
for (currentIndex; currentIndex < run_l_s.size(); currentIndex++) {
sprite.u = run_l_s[currentIndex];
}
}
} else if(keys[SDL_SCANCODE_UP]) {
if (direction_x < 0.0) {
//Left Jump
sprite.v = 0.45;
for (currentIndex; currentIndex < jump_l_s.size(); currentIndex++) {
sprite.u = jump_l_s[currentIndex];
}
} else
//Right Jump
sprite.v = 0.45;
for (currentIndex; currentIndex < jump_r_s.size(); currentIndex++) {
sprite.u = jump_r_s[currentIndex];
}
}
else {
if (collidedBottom) {
if (direction_x < 0.0) {
//Left Idel
sprite.v = 0.0;
for (currentIndex; currentIndex < idel_l_s.size(); currentIndex++) {
sprite.u = idel_l_s[currentIndex];
}
} else
//Right Idel
sprite.v = 0.0;
for (currentIndex; currentIndex < idel_r_s.size(); currentIndex++) {
sprite.u = idel_r_s[currentIndex];
}
} else {
if (direction_x < 0.0) {
//Left Fall
sprite.v = 0.0;
sprite.u = 0.7;
} else
//Right Fall
sprite.v = 0.0;
sprite.u = 0.2;
}
}
if (!collidedBottom) {
if (direction_x < 0.0) {
//Left Fall
sprite.v = 0.0;
sprite.u = 0.7;
} else
//Right Fall
sprite.v = 0.0;
sprite.u = 0.2;
}
} else {
if(keys[SDL_SCANCODE_RIGHT]) {
if (collidedBottom) {
//Rigth Running Animation
sprite.v = 0.45;
for (currentIndex; currentIndex < run_r.size(); currentIndex++) {
sprite.u = run_r[currentIndex];
}
}
} else if(keys[SDL_SCANCODE_LEFT]) {
if (collidedBottom) {
//Left Running Animation
sprite.v = 0.45;
for (currentIndex; currentIndex < run_l.size(); currentIndex++) {
sprite.u = run_l[currentIndex];
}
}
} else if(keys[SDL_SCANCODE_UP]) {
if (direction_x < 0.0) {
//Left Jump
sprite.v = 0.45;
for (currentIndex; currentIndex < jump_l.size(); currentIndex++) {
sprite.u = jump_l[currentIndex];
}
} else
//Right Jump
sprite.v = 0.45;
for (currentIndex; currentIndex < jump_r.size(); currentIndex++) {
sprite.u = jump_r[currentIndex];
}
}
else {
if (collidedBottom) {
if (direction_x < 0.0) {
//Left Idel
sprite.v = 0.0;
for (currentIndex; currentIndex < idel_l.size(); currentIndex++) {
sprite.u = idel_l[currentIndex];
}
} else
//Right Idel
sprite.v = 0.0;
for (currentIndex; currentIndex < idel_r.size(); currentIndex++) {
sprite.u = idel_r[currentIndex];
}
} else {
if (direction_x < 0.0) {
//Left Fall
sprite.v = 0.0;
sprite.u = 0.7;
} else
//Right Fall
sprite.v = 0.0;
sprite.u = 0.2;
}
}
if (!collidedBottom) {
if (direction_x < 0.0) {
//Left Fall
sprite.v = 0.0;
sprite.u = 0.7;
} else
//Right Fall
sprite.v = 0.0;
sprite.u = 0.2;
}
}
}
else if (name == "robot") {
}
}
void Entity::Update(float elapsed) {
float fixedElapsed = elapsed + timeLeftOver;
if(fixedElapsed > FIXED_TIMESTEP * MAX_TIMESTEPS) {
fixedElapsed = FIXED_TIMESTEP * MAX_TIMESTEPS;
}
while (fixedElapsed >= FIXED_TIMESTEP ) {
fixedElapsed -= FIXED_TIMESTEP;
FixedUpdate();
}
timeLeftOver = fixedElapsed;
if (direction_x > 0.0) {
acceleration_x = 1.0;
} else if (direction_x < 0.0) {
acceleration_x = -1.0;
}
}
float lerp(float v0, float v1, float t) {
return (1.0-t)*v0 + t*v1;
}
void Entity::FixedUpdate() {
velocity_x = lerp(velocity_x, 0.0f, FIXED_TIMESTEP * friction_x);
velocity_y = lerp(velocity_y, 0.0f, FIXED_TIMESTEP * friction_y);
velocity_x += acceleration_x * FIXED_TIMESTEP;
velocity_y += acceleration_y * FIXED_TIMESTEP;
x += velocity_x * FIXED_TIMESTEP;
y += velocity_y * FIXED_TIMESTEP;
}
bool Entity::collidesWith(Entity *entity) {
//Bottom Collison
if (y-height/2 < entity->height) {
collidedBottom = true;
return true;
}
//Right Collison
if (x+width/2 > entity->width) {
collidedRight = true;
return true;
}
//Left Collison
if (x-width/2 < entity->width) {
collidedLeft = true;
return true;
}
//Top Collison
if (y+height/2 > entity->height) {
collidedTop = true;
return true;
}
return false;
}
void Bullet::Update(float elapsed) {
x += elapsed;
}
void animatePlayer (SheetSprite sprite) {
}
| 33.869048 | 92 | 0.433626 | MarcNYU |
f426c5c78aad426b12e5e4cdc10c6b6639c68785 | 12,185 | cpp | C++ | src/application/CLI.cpp | DavHau/Riner | f9e9815b713572f03497f0e4e66c3f82a0241b66 | [
"MIT"
] | 4 | 2019-07-24T03:24:08.000Z | 2022-03-04T07:41:08.000Z | src/application/CLI.cpp | DavHau/Riner | f9e9815b713572f03497f0e4e66c3f82a0241b66 | [
"MIT"
] | 3 | 2019-07-30T22:10:39.000Z | 2020-06-15T15:57:08.000Z | src/application/CLI.cpp | DavHau/Riner | f9e9815b713572f03497f0e4e66c3f82a0241b66 | [
"MIT"
] | 6 | 2019-07-30T21:33:07.000Z | 2022-03-21T20:53:11.000Z | //
//
#include "CLI.h"
#include <string>
#include <src/algorithm/Algorithm.h>
#include <src/pool/Pool.h>
#include <sstream>
#include <src/util/StringUtils.h>
#include <src/application/Registry.h>
#include <src/util/FileUtils.h>
#include <src/config/TutorialConfig.h>
#include <src/common/Json.h>
namespace riner {
namespace {
constexpr auto endl = '\n';
constexpr auto json_indent = 4;
}
std::string commandHelp(const CommandInfos &infos, bool useJson) {
if (useJson) {
nl::json j;
for (auto &pair : infos) {
j.emplace_back();
auto &jinfo = j.back();
auto &jnames = jinfo["commands"];
for (auto &name : pair.first) {
jnames.push_back(name);
}
jinfo["help_text"] = pair.second;
}
return j.dump(json_indent);
}
else {
std::vector<std::string> concat_names; //{"--help, -h", "--config", ...}
size_t longest_concat = 0;
for (auto &pair : infos) {
concat_names.emplace_back();
auto &concat_name = concat_names.back();
for (auto &name : pair.first)
concat_name += ", " + name;
if (concat_name.length() > 2)
concat_name = concat_name.c_str() + 2; //skip first comma
if (longest_concat < concat_name.length())
longest_concat = concat_name.length();
}
std::stringstream ss;
for (size_t i = 0; i < infos.size(); ++i) {
auto &info = infos.at(i);
auto &help_text = info.second;
std::string concat_name = concat_names.at(i);
//add space for alignment
while (concat_name.length() < longest_concat) {
concat_name = " " + concat_name;
}
ss << concat_name << " " << help_text << endl;
}
return ss.str();
}
}
std::string commandList(bool useJson) {
if (useJson) {
return nl::json {
{"devices", nl::json::parse(commandListDevices(useJson))},
{"algoImpls", nl::json::parse(commandListAlgoImpls(useJson))},
{"poolImpls", nl::json::parse(commandListPoolImpls(useJson))},
}.dump(json_indent);
}
else {
std::stringstream ss;
ss << commandListDevices(useJson);
ss << commandListAlgoImpls(useJson);
ss << commandListPoolImpls(useJson);
return ss.str();
}
}
//returns empty string if n == 1, "s" otherwise. use for appending plural 's' to word(s)
std::string maybePluralS(int n) {
return n == 1 ? "" : "s";
}
std::string commandListDevices(bool useJson) {
VLOG(5) << "creating compute...";
ComputeModule compute(Config{});
VLOG(5) << "creating compute...done";
auto &allIds = compute.getAllDeviceIds();
size_t i = 0;
if (useJson) {
nl::json j;
for (auto &id : allIds) {
j.push_back(nl::json{
{"index", i},
{"name", id.getName()},
{"vendor", stringFromVendorEnum(id.getVendor())},
});
++i;
}
return j.dump(json_indent);
}
else { //readable
std::stringstream ss;
ss << allIds.size() << " available device" << maybePluralS(allIds.size()) << ": " << endl;
for (auto &id : allIds) {
ss << "\tindex: " << i << ", name: '" << id.getName() << "', vendor: '"
<< stringFromVendorEnum(id.getVendor()) << "'" << endl;
++i;
}
return ss.str();
}
}
std::string commandListAlgoImpls(bool useJson) {
auto all = Registry{}.listAlgoImpls();
size_t i = 0;
if (useJson) {
nl::json j;
for (auto &e : all) {
j.push_back(nl::json{
{"name", e.name},
{"powType", e.powType},
});
++i;
}
return j.dump(json_indent);
}
else {
std::stringstream ss;
ss << all.size() << " available algoImpl" << maybePluralS(all.size()) << ": " << endl;
for (auto &listing : all) {
ss << "\t'" << listing.name << "'\t\t(for PowType '" << listing.powType << "')" << endl;
++i;
}
return ss.str();
}
}
std::string commandListPoolImpls(bool useJson) {
auto all = Registry{}.listPoolImpls();
size_t i = 0;
if (useJson) {
nl::json j;
for (auto &e : all) {
j.push_back(nl::json{
{"name", e.name},
{"powType", e.powType},
{"protocolType", e.protocolType},
{"protocolTypeAlias", e.protocolTypeAlias},
});
}
return j.dump(json_indent);
}
else {
std::stringstream ss;
ss << all.size() << " available poolImpl" << maybePluralS(all.size()) << ": " << endl;
for (auto &e : all) {
ss << "\t'" << e.name << "'\t\t(for PowType '" << e.powType << "'\t protocol names: ";
ss << "'" << e.protocolType << "'";
if (e.protocolTypeAlias != "") { //if it has an alias
ss << ", '" << e.protocolTypeAlias << "'";
}
ss << ")" << endl;
++i;
}
return ss.str();
}
}
optional<size_t> argIndex(const std::string &argName, int argc, const char **argv) {
for (int i = 1; i < argc; ++i) {
std::string arg = partBefore("=", argv[i]);
if (toLower(arg) == toLower(argName))
return i;
}
return nullopt;
}
optional<std::string> argValueAfterEqualsSign(const std::string &argName, int argc, const char **argv) {
for (int i = 1; i < argc; ++i) {
std::string raw_arg = argv[i];
std::string arg = raw_arg;
auto firstEqPos = arg.find_first_of('=');
optional<std::string> value;
if (firstEqPos != std::string::npos) {
arg = raw_arg.substr(0, firstEqPos - 0);
value = raw_arg.substr(firstEqPos + 1);
}
if (toLower(arg) == toLower(argName)) {
return value;
}
}
return nullopt;
}
CommandLineArgs commandRunTutorial(const CommandLineArgs &orig) {
//generate tutorial_config if it doesn't already exist
RNR_EXPECTS(orig.argc > 0);
std::string exec_dir = stripDirFromPath(orig.argv[0]);
std::string path = exec_dir + '/' + "tutorial_config.textproto";
if (!file::fileExists(path)) {
LOG(INFO) << "creating tutorial config at '" << path << "'";
file::writeStringIntoFile(path, tutorial_config);
}
else {
LOG(INFO) << "tutorial config file already exists => not recreating it";
}
std::vector<const char *> new_argv;
for (auto &arg : orig.strings) {
if (startsWith(arg, "--config=")) {//filter out existing --config command
LOG(INFO) << "replacing existing '--config' command";
continue;
}
if (startsWith(arg, "--run-tutorial")) {
continue;
}
new_argv.push_back(arg.c_str());
}
std::string config_arg = "--config=" + path;
LOG(INFO) << "adding '" << config_arg << "' to command line args";
new_argv.push_back(config_arg.c_str());
auto result = copyArgsAndExpandSingleDashCombinedArgs(new_argv.size(), new_argv.data());
LOG(INFO) << "running riner with args: " << result.allArgsAsOneString;
return result;
}
CommandLineArgs copyArgsAndExpandSingleDashCombinedArgs(int argc, const char **argv) {
CommandLineArgs res;
res.argc = 0;
if (argc <= 0)
return res;
for (int i = 0; i < argc; ++i) {
std::string arg = argv[i];
bool singleMinus = arg.size() >= 2 && arg[0] == '-' && arg[1] != '-';
//whether its something like -v=0
bool equalsSignAt2 = arg.size() >= 3 && arg[2] == '=';
if (singleMinus && !equalsSignAt2) {
//it is something like -abcd
for (char c : arg) {
if (c != '=' && c != '-')
res.strings.push_back(std::string("-") + c);
}
} else { //its something like --something or -a=something
res.strings.push_back(arg);
}
}
//fill other members of result struct
res.argc = (int) res.strings.size();
for (auto &str : res.strings) {
bool isFirstPathArg = &str == &res.strings.front();
bool isLastArg = &str == &res.strings.back();
if (!isFirstPathArg) {
res.allArgsAsOneString += str;
if (!isLastArg)
res.allArgsAsOneString += " ";
}
res.ptrs.push_back(str.c_str());
res.argv = res.ptrs.data();
}
return res;
}
size_t reportUnsupportedCommands(const CommandInfos &infos, int argc, const char **argv) {
std::vector<std::string> supported; //names of supported args
for (auto &pair : infos)
for (auto &cmd : pair.first)
supported.push_back(cmd);
std::vector<std::string> unsupported; //e.g. {arg0, arg4, arg8}
std::string concat_unsupported; //e.g. "arg0, arg4, arg8"
//skip first arg
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
arg = partBefore("=", arg); //take only the part of the arg before a possible '='
bool is_supported = false;
for (auto &supp : supported) {
is_supported |= arg == supp;
}
if (!is_supported) {
unsupported.push_back(arg);
concat_unsupported += ", " + arg;
}
}
//remove leading comma
if (concat_unsupported.size() > 2)
concat_unsupported = concat_unsupported.c_str() + 2;
if (!unsupported.empty()) {
for (auto &arg : unsupported)
std::cout << "argument " << arg << " not supported." << endl;
#ifndef NDEBUG
std::string start = unsupported.size() == 1 ? "if the argument (" : "if one of the arguments (";
std::cout << start << concat_unsupported <<
") is actually supported, please add it to the listing in the main() function." << endl;
#endif
}
return unsupported.size();
}
optional<std::string> getValueAfterArgWithEqualsSign(const std::vector<std::string> &argNames, int argc, const char **argv) {
for (auto &name : argNames) {
if (auto optValue = argValueAfterEqualsSign(name, argc, argv))
return optValue;
}
return nullopt;
}
bool hasArg(const std::vector<std::string> &argNames, int argc, const char **argv) {
for (auto &name : argNames) {
if (argIndex(name, argc, argv))
return true;
}
return false;
}
optional<std::string> getPathAfterArg(const std::string &minusminusArg, int argc, const char **argv) {
//minusminusArg is something like "--config"
if (auto i = argIndex(minusminusArg, argc, argv)) {
int next = *i + 1;
if (next < argc)
return std::string{argv[next]};
}
return nullopt;
}
}
| 34.036313 | 129 | 0.484366 | DavHau |
f426c7fb7989198be11cb85888de17a85fd4bdcf | 19,085 | cxx | C++ | Libraries/VtkVgModelView/vtkVgEventModel.cxx | PinkDiamond1/vivia | 70f7fbed4b33b14d34de35c69b2b14df3514d720 | [
"BSD-3-Clause"
] | 14 | 2016-09-16T12:33:05.000Z | 2021-02-14T02:16:33.000Z | Libraries/VtkVgModelView/vtkVgEventModel.cxx | PinkDiamond1/vivia | 70f7fbed4b33b14d34de35c69b2b14df3514d720 | [
"BSD-3-Clause"
] | 44 | 2016-10-06T22:12:57.000Z | 2021-01-07T19:39:07.000Z | Libraries/VtkVgModelView/vtkVgEventModel.cxx | PinkDiamond1/vivia | 70f7fbed4b33b14d34de35c69b2b14df3514d720 | [
"BSD-3-Clause"
] | 17 | 2015-06-30T13:41:47.000Z | 2021-11-22T17:38:48.000Z | // This file is part of ViViA, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/vivia/blob/master/LICENSE for details.
#include "vtkVgEventModel.h"
#include "vgEventType.h"
#include "vtkVgContourOperatorManager.h"
#include "vtkVgEvent.h"
#include "vtkVgEventInfo.h"
#include "vtkVgEventTypeRegistry.h"
#include "vtkVgTemporalFilters.h"
#include "vtkVgTrack.h"
#include "vtkVgTrackModel.h"
#include <vtkCommand.h>
#include <vtkIdList.h>
#include <vtkIdListCollection.h>
#include <vtkObjectFactory.h>
#include <vtkPoints.h>
#include <vtkTimeStamp.h>
#include <algorithm>
#include <assert.h>
#include <map>
vtkStandardNewMacro(vtkVgEventModel);
vtkCxxSetObjectMacro(vtkVgEventModel, TrackModel, vtkVgTrackModel);
vtkCxxSetObjectMacro(vtkVgEventModel, SharedRegionPoints, vtkPoints);
typedef std::map<vtkIdType, vtkVgEventInfo> EventMap;
typedef std::map<vtkIdType, vtkVgEventInfo>::iterator EventMapIterator;
typedef std::map<int, double> EventNormalcyMap;
//----------------------------------------------------------------------------
struct vtkVgEventModel::vtkInternal
{
EventMap EventIdMap;
EventMapIterator EventIter;
EventNormalcyMap NormalcyMinimum;
EventNormalcyMap NormalcyMaximum;
vtkTimeStamp UpdateTime;
vtkTimeStamp SpatialFilteringUpdateTime;
vtkTimeStamp TemporalFilteringUpdateTime;
std::vector<EventLink> EventLinks;
};
//-----------------------------------------------------------------------------
vtkVgEventModel::vtkVgEventModel()
{
this->TrackModel = 0;
this->UseSharedRegionPoints = true;
this->SharedRegionPoints = vtkPoints::New();
this->Internal = new vtkInternal;
this->ShowEventsBeforeStart = false;
this->ShowEventsAfterExpiration = false;
this->ShowEventsUntilSupportingTracksExpire = false;
this->UseTrackGroups = false;
this->EventExpirationOffset.SetFrameNumber(0u);
this->EventExpirationOffset.SetTime(0.0);
this->CurrentTimeStamp.SetToMinTime();
}
//-----------------------------------------------------------------------------
vtkVgEventModel::~vtkVgEventModel()
{
this->SetTrackModel(0);
this->SetSharedRegionPoints(0);
for (EventMapIterator itr = this->Internal->EventIdMap.begin(),
end = this->Internal->EventIdMap.end(); itr != end; ++itr)
{
itr->second.GetEvent()->UnRegister(this);
}
delete this->Internal;
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//-----------------------------------------------------------------------------
vtkVgEvent* vtkVgEventModel::GetEvent(vtkIdType eventId)
{
EventMapIterator eventIter = this->Internal->EventIdMap.find(eventId);
if (eventIter != this->Internal->EventIdMap.end())
{
return eventIter->second.GetEvent();
}
return 0;
}
//-----------------------------------------------------------------------------
vtkVgEventInfo vtkVgEventModel::GetEventInfo(vtkIdType eventId)
{
EventMapIterator eventIter = this->Internal->EventIdMap.find(eventId);
if (eventIter != this->Internal->EventIdMap.end())
{
return eventIter->second;
}
return vtkVgEventInfo();
}
//-----------------------------------------------------------------------------
vtkVgTrackDisplayData vtkVgEventModel::GetTrackDisplayData(vtkVgEvent* event,
int trackIndex)
{
vtkVgTimeStamp eventStart = event->GetStartFrame();
vtkVgTimeStamp eventExpiration = event->GetEndFrame();
eventExpiration.ShiftForward(this->EventExpirationOffset);
// Never display the event track if its start occurs before the reference time.
if (this->ReferenceTimeStamp.IsValid() &&
eventStart < this->ReferenceTimeStamp)
{
return vtkVgTrackDisplayData();
}
if (!this->ShowEventsBeforeStart &&
this->CurrentTimeStamp < eventStart)
{
return vtkVgTrackDisplayData();
}
if (!this->ShowEventsAfterExpiration &&
this->CurrentTimeStamp > eventExpiration)
{
return vtkVgTrackDisplayData();
}
// Display the whole event if showing before the start of the event.
if (this->CurrentTimeStamp < eventStart)
{
return event->GetTrackDisplayData(trackIndex, this->UseTrackGroups,
vtkVgTimeStamp(false),
vtkVgTimeStamp(true));
}
// Waiting for track expiration?
if (this->ShowEventsUntilSupportingTracksExpire)
{
vtkVgTimeStamp maxTime(false);
int end = this->UseTrackGroups ?
event->GetNumberOfTrackGroups() : event->GetNumberOfTracks();
for (int i = 0; i < end; ++i)
{
vtkVgTimeStamp endFrame = this->TrackModel->GetTrackEndDisplayFrame(
this->UseTrackGroups ? event->GetTrackGroupTrack(i) :
event->GetTrack(i));
if (endFrame > maxTime)
{
maxTime = endFrame;
}
}
if (this->CurrentTimeStamp > maxTime)
{
return vtkVgTrackDisplayData();
}
}
// Display from the first frame of the event track up to the current frame.
return event->GetTrackDisplayData(trackIndex, this->UseTrackGroups,
vtkVgTimeStamp(false),
this->CurrentTimeStamp);
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::GetEvents(vtkIdType trackId,
std::vector<vtkVgEvent*>& events)
{
EventMapIterator eventIter = this->Internal->EventIdMap.begin();
while (eventIter != this->Internal->EventIdMap.end())
{
vtkVgEvent* event = eventIter->second.GetEvent();
if (event->HasTrack(trackId))
{
events.push_back(event);
}
++eventIter;
}
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::GetEvents(vtkVgTrack* track,
std::vector<vtkVgEvent*>& events)
{
if (!track)
{
vtkErrorMacro("ERROR: NULL or invalid track\n");
return;
}
this->GetEvents(track->GetId(), events);
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::InitEventTraversal()
{
this->Internal->EventIter = this->Internal->EventIdMap.begin();
}
//-----------------------------------------------------------------------------
vtkVgEventInfo vtkVgEventModel::GetNextEvent()
{
if (this->Internal->EventIter != this->Internal->EventIdMap.end())
{
return this->Internal->EventIter++->second;
}
return vtkVgEventInfo();
}
//-----------------------------------------------------------------------------
vtkVgEventInfo vtkVgEventModel::GetNextDisplayedEvent()
{
while (this->Internal->EventIter != this->Internal->EventIdMap.end())
{
if (this->Internal->EventIter->second.GetDisplayEvent() &&
this->Internal->EventIter->second.GetPassesFilters())
{
return this->Internal->EventIter++->second;
}
++this->Internal->EventIter;
}
return vtkVgEventInfo();
}
//-----------------------------------------------------------------------------
vtkIdType vtkVgEventModel::GetNumberOfEvents()
{
return static_cast<vtkIdType>(this->Internal->EventIdMap.size());
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::SetEventExpirationOffset(const vtkVgTimeStamp& offset)
{
if (offset != this->EventExpirationOffset)
{
this->EventExpirationOffset = offset;
this->Modified();
}
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::Initialize()
{
this->Internal->EventIdMap.clear();
this->Internal->NormalcyMinimum.clear();
this->Internal->NormalcyMaximum.clear();
}
//-----------------------------------------------------------------------------
vtkVgEvent* vtkVgEventModel::AddEvent(vtkVgEventBase* vgEventBase)
{
vtkVgEventInfo eventInfo;
vtkVgEvent* vgEvent = vtkVgEvent::SafeDownCast(vgEventBase);
if (!vgEvent)
{
vgEvent = vtkVgEvent::New();
if (this->UseSharedRegionPoints)
{
vgEvent->SetRegionPoints(this->SharedRegionPoints);
}
vgEvent->DeepCopy(vgEventBase, true);
if (this->TrackModel)
{
// if we have a track model, try to resolve the track ptr
for (unsigned int i = 0; i < vgEvent->GetNumberOfTracks(); i++)
{
if (!vgEvent->SetTrackPtr(i,
this->TrackModel->GetTrack(vgEvent->GetTrackId(i))))
{
// not sure how to handle this yet... since now have events that
// might not have resolved tracks (display something of interest
// via region), we don't necessarily need to throw away events
// that we can't link up. However, we will throw them away if
// were able to find some of the tracks for the events, but not al.
if (i != 0)
{
vtkErrorMacro("Resolved some, but not all, track ptrs in event... thus NOT added!");
vgEvent->Delete();
return 0;
}
else
{
vtkErrorMacro("Failed to resolve track ptrs in event... but event added anyway!");
break;
}
}
}
}
eventInfo.SetEvent(vgEvent);
vgEvent->Register(this);
vgEvent->FastDelete();
}
else
{
eventInfo.SetEvent(vgEvent);
vgEvent->Register(this);
}
this->Modified();
eventInfo.SetDisplayEventOn();
this->Internal->EventIdMap[vgEvent->GetId()] = eventInfo;
// Update minimum and maximum normalcy for this event's classifiers
EventNormalcyMap::iterator itr;
for (bool valid = vgEvent->InitClassifierTraversal(); valid;
valid = vgEvent->NextClassifier())
{
int type = vgEvent->GetClassifierType();
double normalcy = vgEvent->GetClassifierNormalcy();
itr = this->Internal->NormalcyMinimum.find(type);
if (itr == this->Internal->NormalcyMinimum.end() ||
itr->second > normalcy)
{
this->Internal->NormalcyMinimum[type] = normalcy;
}
itr = this->Internal->NormalcyMaximum.find(type);
if (itr == this->Internal->NormalcyMaximum.end() ||
itr->second < normalcy)
{
this->Internal->NormalcyMaximum[type] = normalcy;
}
}
return vgEvent;
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::AddEventLink(const EventLink& link)
{
this->Internal->EventLinks.push_back(link);
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::GetEventLink(int index, EventLink& link)
{
link = this->Internal->EventLinks[index];
}
//-----------------------------------------------------------------------------
int vtkVgEventModel::GetNumberOfEventLinks()
{
return static_cast<int>(this->Internal->EventLinks.size());
}
//-----------------------------------------------------------------------------
vtkVgEvent* vtkVgEventModel::CreateAndAddEvent(int type, vtkIdList* trackIds)
{
if (!this->TrackModel)
{
return 0;
}
vtkVgEvent* event = vtkVgEvent::New();
if (this->UseSharedRegionPoints)
{
event->SetRegionPoints(this->SharedRegionPoints);
}
vtkIdType id = this->GetNextAvailableId();
event->SetId(id);
event->AddClassifier(type, 0.0, 1.0);
event->SetFlags(vtkVgEvent::EF_UserCreated |
vtkVgEvent::EF_Dirty |
vtkVgEvent::EF_Modifiable);
vtkVgTimeStamp minFrame(true);
vtkVgTimeStamp maxFrame(false);
for (vtkIdType i = 0, end = trackIds->GetNumberOfIds(); i < end; ++i)
{
vtkVgTrack* track = this->TrackModel->GetTrack(trackIds->GetId(i));
vtkVgTimeStamp startFrame = track->GetStartFrame();
vtkVgTimeStamp endFrame = track->GetEndFrame();
event->AddTrack(track, startFrame, endFrame);
minFrame = std::min(minFrame, startFrame);
maxFrame = std::max(maxFrame, endFrame);
}
// for now, have the event span the entire duration of all child tracks
event->SetStartFrame(minFrame);
event->SetEndFrame(maxFrame);
this->AddEvent(event);
event->FastDelete();
this->Modified();
return event;
}
//-----------------------------------------------------------------------------
vtkVgEvent* vtkVgEventModel::CloneEvent(vtkIdType eventId)
{
vtkVgEvent* srcEvent = this->GetEvent(eventId);
if (!srcEvent)
{
return 0;
}
vtkVgEvent* event = vtkVgEvent::New();
event->CloneEvent(srcEvent);
vtkIdType id = this->Internal->EventIdMap.empty()
? 0
: (--this->Internal->EventIdMap.end())->first + 1;
event->SetId(id);
this->AddEvent(event);
event->FastDelete();
this->Modified();
return event;
}
//-----------------------------------------------------------------------------
bool vtkVgEventModel::RemoveEvent(vtkIdType eventId)
{
EventMapIterator iter = this->Internal->EventIdMap.find(eventId);
if (iter != this->Internal->EventIdMap.end())
{
vtkVgEvent* event = iter->second.GetEvent();
this->InvokeEvent(vtkVgEventModel::EventRemoved, event);
this->Internal->EventIdMap.erase(iter);
event->UnRegister(this);
this->Modified();
return true;
}
return false; // not removed (not present)
}
//-----------------------------------------------------------------------------
double vtkVgEventModel::GetNormalcyMinForType(int type)
{
EventNormalcyMap::iterator itr = this->Internal->NormalcyMinimum.find(type);
if (itr == this->Internal->NormalcyMinimum.end())
{
return VTK_DOUBLE_MAX;
}
return itr->second;
}
//-----------------------------------------------------------------------------
double vtkVgEventModel::GetNormalcyMaxForType(int type)
{
EventNormalcyMap::iterator itr = this->Internal->NormalcyMaximum.find(type);
if (itr == this->Internal->NormalcyMaximum.end())
{
return VTK_DOUBLE_MIN;
}
return itr->second;
}
//-----------------------------------------------------------------------------
int vtkVgEventModel::Update(const vtkVgTimeStamp& timeStamp,
const vtkVgTimeStamp* referenceFrameTimeStamp/*=0*/)
{
bool updateSpatial = this->ContourOperatorManager &&
(this->GetMTime() >
this->Internal->SpatialFilteringUpdateTime ||
this->ContourOperatorManager->GetMTime() >
this->Internal->SpatialFilteringUpdateTime);
bool updateTemporal = this->TemporalFilters &&
(this->GetMTime() >
this->Internal->TemporalFilteringUpdateTime ||
this->TemporalFilters->GetMTime() >
this->Internal->TemporalFilteringUpdateTime);
if (this->CurrentTimeStamp == timeStamp &&
this->Internal->UpdateTime > this->GetMTime() &&
!(updateSpatial || updateTemporal))
{
return VTK_OK;
}
this->CurrentTimeStamp = timeStamp;
this->ReferenceTimeStamp = referenceFrameTimeStamp ? *referenceFrameTimeStamp
: vtkVgTimeStamp();
this->Internal->UpdateTime.Modified();
if (updateSpatial)
{
this->Internal->SpatialFilteringUpdateTime.Modified();
}
if (updateTemporal)
{
this->Internal->TemporalFilteringUpdateTime.Modified();
}
EventMapIterator eventIter;
for (eventIter = this->Internal->EventIdMap.begin();
eventIter != this->Internal->EventIdMap.end(); eventIter++)
{
vtkVgEventInfo& info = eventIter->second;
// hide this event if it is not displayed
if (!info.GetDisplayEvent())
{
continue;
}
if (updateTemporal)
{
this->UpdateTemporalFiltering(info);
}
if (updateSpatial)
{
this->UpdateSpatialFiltering(info);
}
}
// Let the representation (if listening) know it needs to update
//this->UpdateTime.ModifieDataRequestOn();
this->InvokeEvent(vtkCommand::UpdateDataEvent);
return VTK_OK;
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::SetEventDisplayState(vtkIdType eventId, bool displayEvent)
{
EventMapIterator eventIter = this->Internal->EventIdMap.find(eventId);
if (eventIter != this->Internal->EventIdMap.end() &&
eventIter->second.GetDisplayEvent() != displayEvent)
{
displayEvent ? eventIter->second.SetDisplayEventOn()
: eventIter->second.SetDisplayEventOff();
this->Modified();
}
}
//-----------------------------------------------------------------------------
unsigned long vtkVgEventModel::GetUpdateTime()
{
return this->Internal->UpdateTime.GetMTime();
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::SetAllEventsDisplayState(bool state)
{
for (EventMapIterator itr = this->Internal->EventIdMap.begin(),
end = this->Internal->EventIdMap.end(); itr != end; ++itr)
{
if (state)
{
itr->second.SetDisplayEventOn();
}
else
{
itr->second.SetDisplayEventOff();
}
}
this->Modified();
}
//-----------------------------------------------------------------------------
vtkIdType vtkVgEventModel::GetNextAvailableId()
{
if (this->Internal->EventIdMap.empty())
{
return 0;
}
return (--this->Internal->EventIdMap.end())->first + 1;
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::UpdateTemporalFiltering(vtkVgEventInfo& info)
{
vtkVgEvent* event = info.GetEvent();
bool pass =
this->TemporalFilters->EvaluateInterval(event->GetStartFrame(),
event->GetEndFrame());
pass ? info.SetPassesTemporalFiltersOn() : info.SetPassesTemporalFiltersOff();
}
//-----------------------------------------------------------------------------
void vtkVgEventModel::UpdateSpatialFiltering(vtkVgEventInfo& info)
{
vtkVgEvent* event = info.GetEvent();
// if no track (in which case we should really test the regions,
// but not right now) or track isn't started, don't mark the event as
// having failed filtering / selecting
if (event->GetNumberOfTracks() == 0 || !event->GetTrack(0) ||
!event->GetTrack(0)->IsStarted())
{
info.SetPassesSpatialFiltersOn();
return;
}
if (event->IsTripEvent())
{
if (this->ContourOperatorManager->EvaluatePoint(
event->GetTripEventPosition()))
{
info.SetPassesSpatialFiltersOn();
return;
}
}
else
{
vtkIdListCollection* idLists = event->GetFullEventIdCollection();
for (int i = 0; i < idLists->GetNumberOfItems(); ++i)
{
// does any of the event "pass" the filters and selectors
if (this->ContourOperatorManager->EvaluatePath(
event->GetPoints(), idLists->GetItem(i)))
{
info.SetPassesSpatialFiltersOn();
return;
}
}
}
info.SetPassesSpatialFiltersOff();
}
| 29.773791 | 96 | 0.577784 | PinkDiamond1 |
f427425e383e6661138ff8864f512a371d0122a7 | 4,454 | cpp | C++ | Kawakawa/KawaiiGraphic/RHI/DX12Viewport.cpp | JiaqiJin/KawaiiDesune | e5c3031898f96f1ec5370b41371b2c1cf22c3586 | [
"MIT"
] | null | null | null | Kawakawa/KawaiiGraphic/RHI/DX12Viewport.cpp | JiaqiJin/KawaiiDesune | e5c3031898f96f1ec5370b41371b2c1cf22c3586 | [
"MIT"
] | null | null | null | Kawakawa/KawaiiGraphic/RHI/DX12Viewport.cpp | JiaqiJin/KawaiiDesune | e5c3031898f96f1ec5370b41371b2c1cf22c3586 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "DX12Viewport.h"
#include "DX12GraphicRHI.h"
#include "DX12Device.h"
#include "Texture/TextureInfo.h"
namespace RHI
{
DX12Viewport::DX12Viewport(DX12GraphicRHI* DX12RHI, const DX12ViewportInfo& Info, int Width, int Height)
: m_DX12RHI(DX12RHI), m_ViewportInfo(Info), m_ViewportWidth(Width), m_ViewportHeight(Height)
{
CreateSwapChain();
}
DX12Viewport::~DX12Viewport()
{
}
void DX12Viewport::OnResize(int NewWidth, int NewHeight)
{
m_ViewportWidth = NewWidth;
m_ViewportHeight = NewHeight;
// Flush before changing any resources.
m_DX12RHI->GetDevice()->GetCommandContext()->FlushCommandQueue();
m_DX12RHI->GetDevice()->GetCommandContext()->ResetCommandList();
// Release the previous resources
for (UINT i = 0; i < m_SwapChainBufferCount; i++)
{
m_RenderTargetTextures[i].reset();
}
m_DepthStencilTexture.reset();
// Resize the swap chain.
ThrowIfFailed(m_SwapChain->ResizeBuffers(m_SwapChainBufferCount, m_ViewportWidth, m_ViewportHeight,
m_ViewportInfo.BackBufferFormat, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH));
m_CurrBackBuffer = 0;
// Create RenderTargetTextures
for (UINT i = 0; i < m_SwapChainBufferCount; i++)
{
Microsoft::WRL::ComPtr<ID3D12Resource> SwapChainBuffer = nullptr;
ThrowIfFailed(m_SwapChain->GetBuffer(i, IID_PPV_ARGS(&SwapChainBuffer)));
D3D12_RESOURCE_DESC BackBufferDesc = SwapChainBuffer->GetDesc();
TextureInfo textureInfo;
textureInfo.RTVFormat = BackBufferDesc.Format;
textureInfo.InitState = D3D12_RESOURCE_STATE_PRESENT;
m_RenderTargetTextures[i] = m_DX12RHI->CreateTexture(SwapChainBuffer, textureInfo, TexCreate_RTV);
}
// Create DepthStencilTexture
TextureInfo textureInfo;
textureInfo.Type = ETextureType::TEXTURE_2D;
textureInfo.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
textureInfo.Width = m_ViewportWidth;
textureInfo.Height = m_ViewportHeight;
textureInfo.Depth = 1;
textureInfo.MipCount = 1;
textureInfo.ArraySize = 1;
textureInfo.InitState = D3D12_RESOURCE_STATE_DEPTH_WRITE;
textureInfo.Format = DXGI_FORMAT_R24G8_TYPELESS; // Create with a typeless format, support DSV and SRV(for SSAO)
textureInfo.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
textureInfo.SRVFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
m_DepthStencilTexture = m_DX12RHI->CreateTexture(textureInfo, TexCreate_DSV | TexCreate_SRV);
// Execute the resize commands.
m_DX12RHI->GetDevice()->GetCommandContext()->ExecuteCommandLists();
// Wait until resize is complete.
m_DX12RHI->GetDevice()->GetCommandContext()->FlushCommandQueue();
}
void DX12Viewport::Present()
{
// swap the back and front buffers
ThrowIfFailed(m_SwapChain->Present(0, 0));
m_CurrBackBuffer = (m_CurrBackBuffer + 1) % m_SwapChainBufferCount;
}
void DX12Viewport::CreateSwapChain()
{
// Release the previous swapchain we will be recreating.
m_SwapChain.Reset();
DXGI_SWAP_CHAIN_DESC Desc;
Desc.BufferDesc.Width = m_ViewportWidth;
Desc.BufferDesc.Height = m_ViewportHeight;
Desc.BufferDesc.RefreshRate.Numerator = 60;
Desc.BufferDesc.RefreshRate.Denominator = 1;
Desc.BufferDesc.Format = m_ViewportInfo.BackBufferFormat;
Desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
Desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
Desc.SampleDesc.Count = m_ViewportInfo.bEnable4xMsaa ? 4 : 1;
Desc.SampleDesc.Quality = m_ViewportInfo.bEnable4xMsaa ? (m_ViewportInfo.QualityOf4xMsaa - 1) : 0;
Desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
Desc.BufferCount = m_SwapChainBufferCount;
Desc.OutputWindow = m_ViewportInfo.WindowHandle;
Desc.Windowed = true;
Desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
Desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
// Note: Swap chain uses queue to perform flush.
Microsoft::WRL::ComPtr<ID3D12CommandQueue> CommandQueue = m_DX12RHI->GetDevice()->GetCommandQueue();
ThrowIfFailed(m_DX12RHI->GetDxgiFactory()->CreateSwapChain(CommandQueue.Get(), &Desc, m_SwapChain.GetAddressOf()));
}
void DX12Viewport::GetD3DViewport(D3D12_VIEWPORT& OutD3DViewPort, D3D12_RECT& OutD3DRect)
{
OutD3DViewPort.TopLeftX = 0;
OutD3DViewPort.TopLeftY = 0;
OutD3DViewPort.Width = static_cast<float>(m_ViewportWidth);
OutD3DViewPort.Height = static_cast<float>(m_ViewportHeight);
OutD3DViewPort.MinDepth = 0.0f;
OutD3DViewPort.MaxDepth = 1.0f;
OutD3DRect = { 0, 0, m_ViewportWidth, m_ViewportHeight };
}
} | 35.632 | 117 | 0.776605 | JiaqiJin |
f4278b973fda15c5eba16fd9839c1cf2851857e4 | 324 | hpp | C++ | include/bisera/mainwindow.hpp | DanielAckerson/bisera | f574c257a4a20d663eae6c52d50444280bbfe67d | [
"MIT"
] | null | null | null | include/bisera/mainwindow.hpp | DanielAckerson/bisera | f574c257a4a20d663eae6c52d50444280bbfe67d | [
"MIT"
] | null | null | null | include/bisera/mainwindow.hpp | DanielAckerson/bisera | f574c257a4a20d663eae6c52d50444280bbfe67d | [
"MIT"
] | null | null | null | #ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include <glad/glad.h>
#include <GLFW/glfw3.h>
class MainWindow {
GLFWwindow *window;
GLFWmonitor *monitor;
GLuint width, height;
public:
MainWindow();
~MainWindow();
public:
inline GLFWwindow *context() { return window; }
};
#endif//MAINWINDOW_HPP
| 15.428571 | 51 | 0.694444 | DanielAckerson |
f42f71b0782e115902afe80664e901a9130de4e1 | 4,088 | cpp | C++ | src/dbus/dbus_watch.cpp | tpruzina/dvc-toggler-linux | ccd70fedfdc47172e876c04357b863bb758bd304 | [
"BSD-3-Clause"
] | null | null | null | src/dbus/dbus_watch.cpp | tpruzina/dvc-toggler-linux | ccd70fedfdc47172e876c04357b863bb758bd304 | [
"BSD-3-Clause"
] | 1 | 2019-05-20T16:47:28.000Z | 2019-05-20T16:47:28.000Z | src/dbus/dbus_watch.cpp | tpruzina/dvc-toggler-linux | ccd70fedfdc47172e876c04357b863bb758bd304 | [
"BSD-3-Clause"
] | null | null | null | #include "dbus_watch.hpp"
#include <cstdlib>
#include <cstring>
#include <dbus/dbus.h>
#include <iostream>
#include <unistd.h>
auto DBusInterface::sendSignal(char *message) noexcept -> void
{
auto args = DBusMessageIter{};
dbus_uint32_t serial = 0;
auto conn = dbus_bus_get(DBUS_BUS_STARTER, nullptr);
if (!conn)
return;
dbus_bus_request_name(
conn,
DBUS_CLIENT_NAME,
DBUS_NAME_FLAG_REPLACE_EXISTING,
nullptr);
auto msg = dbus_message_new_signal(
DBUS_SIGNAL_OBJECT, // object name of the signal
DBUS_IF_NAME, // interface name of the signal
DBUS_SIGNAL_SHOW // name of the signal
);
dbus_message_iter_init_append(msg, &args);
dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &message);
// send the message and flush the connection
dbus_connection_send(conn, msg, &serial);
dbus_connection_flush(conn);
dbus_message_unref(msg);
dbus_bus_release_name(conn, DBUS_CLIENT_NAME, nullptr);
dbus_connection_unref(conn);
return;
}
auto DBusInterface::spawnListener(void (*cb)(void*), void* object) noexcept -> void
{
this->callback_fn = cb;
this->callback_object = object;
listener = std::thread(&DBusInterface::receive, this);
return;
}
auto DBusInterface::receive() noexcept -> void
{
if (!callback_fn)
return;
auto conn = dbus_bus_get(DBUS_BUS_STARTER, nullptr);
if (!conn)
return;
dbus_bus_request_name(
conn,
DBUS_HOST_SERVER,
DBUS_NAME_FLAG_REPLACE_EXISTING,
NULL
);
dbus_bus_add_match(
conn,
"type='signal',interface='" DBUS_IF_NAME "'",
nullptr);
dbus_connection_flush(conn);
// loop listening for signals being emmitted
while (true)
{
if(shutdown)
break;
// non blocking read of the next available message
dbus_connection_read_write(conn, 0);
auto msg = dbus_connection_pop_message(conn);
// loop again if we haven't read a message
if (!msg)
{
std::this_thread::sleep_for(
std::chrono::milliseconds(sleep_ms));
continue;
}
// check if the message is a signal from the correct interface and with the correct name
if (dbus_message_is_signal(
msg,
DBUS_IF_NAME,
DBUS_SIGNAL_SHOW))
{
auto args = DBusMessageIter{};
// read the parameters
dbus_message_iter_init(msg, &args);
if (DBUS_TYPE_STRING ==
dbus_message_iter_get_arg_type(&args))
{
auto sigvalue = (char const *)(nullptr);
dbus_message_iter_get_basic(&args, &sigvalue);
// display mainWindow
if (!strcmp(sigvalue, "show()"))
callback_fn(callback_object);
}
}
// free the message
dbus_message_unref(msg);
}
// close the connection
dbus_bus_remove_match(
conn,
"type='signal',interface='" DBUS_IF_NAME "'",
nullptr);
dbus_bus_release_name(conn, DBUS_HOST_SERVER, nullptr);
dbus_connection_unref(conn);
return;
}
| 32.967742 | 104 | 0.489237 | tpruzina |
f42f8917e49952f4de8da45c32f5120c71609fa3 | 1,095 | hpp | C++ | test/ClientTester.hpp | AlexSL92/udp-packet-replicator | 90a3feb138e7ad2ae7e4b87f97305f658b7f6eeb | [
"MIT"
] | 2 | 2020-06-18T09:06:45.000Z | 2021-03-27T14:16:54.000Z | test/ClientTester.hpp | AlexSL92/udp-packet-replicator | 90a3feb138e7ad2ae7e4b87f97305f658b7f6eeb | [
"MIT"
] | null | null | null | test/ClientTester.hpp | AlexSL92/udp-packet-replicator | 90a3feb138e7ad2ae7e4b87f97305f658b7f6eeb | [
"MIT"
] | 1 | 2020-06-18T06:29:17.000Z | 2020-06-18T06:29:17.000Z | #pragma once
#include <asio.hpp>
#include <array>
#include <cstdint>
#include <vector>
/**
* @brief Tester of client sockets
*/
class ClientTester {
public:
/**
* @brief Construct a new Client Tester object
*
* @param port Port where listen for packets
*/
ClientTester(uint16_t port) :
io_context_{},
socket_{ io_context_, asio::ip::udp::endpoint(asio::ip::udp::v4(), port) } {}
/**
* @brief Destroy the Client Tester object
*
*/
~ClientTester() {}
/**
* @brief Read data from socket
*
* @return std::vector<uint8_t> Data received on the socket
*/
std::vector<uint8_t> ReceiveData() {
std::array<uint8_t, 8192> recv_buf{};
asio::ip::udp::endpoint remote_endpoint{};
auto recv{ socket_.receive_from(asio::buffer(recv_buf), remote_endpoint) };
return std::vector<uint8_t>{ recv_buf.begin(), recv_buf.begin() + recv };
}
private:
asio::io_context io_context_; //!< Asio context object
asio::ip::udp::socket socket_; //!< Asio socket
};
| 21.9 | 85 | 0.601826 | AlexSL92 |
f4300579eebdc53aec591485fafe4315b602a52a | 3,917 | hpp | C++ | src/libraries/waves/wavesProcessing/postProcessing/postProcessingWaves/spectralAnalysis/spectralMethods/spectralMethodsLeastSquaresBased.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/waves/wavesProcessing/postProcessing/postProcessingWaves/spectralAnalysis/spectralMethods/spectralMethodsLeastSquaresBased.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/waves/wavesProcessing/postProcessing/postProcessingWaves/spectralAnalysis/spectralMethods/spectralMethodsLeastSquaresBased.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright Niels Gjøl Jacobsen, Technical University of Denmark.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::spectralMethodsLeastSquaresBased
Description
Helper functions for spectral analysis using a least-squares based
approach.
SourceFiles
spectralMethodsLeastSquaresBased.cpp
Author
Niels Gjøl Jacobsen, Technical University of Denmark.
\*---------------------------------------------------------------------------*/
#ifndef spectralMethodsLeastSquaresBased_HPP
#define spectralMethodsLeastSquaresBased_HPP
#include "fvCFD.hpp"
#include "complexExp.hpp"
#include "scalarMatrices.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class waveTheory Declaration
\*---------------------------------------------------------------------------*/
class spectralMethodsLeastSquaresBased
{
private:
// Private Member Functions
void computePowerSpectrum
(
const scalarField&,
const scalarField&,
const label&,
const scalar&,
scalarField&
);
//- Disallow default bitwise copy construct
spectralMethodsLeastSquaresBased
(
const spectralMethodsLeastSquaresBased&
);
//- Disallow default bitwise assignment
void operator=(const spectralMethodsLeastSquaresBased&);
// Private member data
public:
//- Runtime type information
TypeName("spectralMethodsLeastSquaresBased");
// Constructors
//- Construct from components
spectralMethodsLeastSquaresBased
(
const Time&,
const dictionary&
);
// Destructor
virtual ~spectralMethodsLeastSquaresBased();
// Member Functions
//- Solves a least squares problem, with the columns given in the
// List<scalarField> and the right hand side in the scalarField.
// The solution is returned in the right hand side field
void solve
(
const List<scalarField>&,
scalarField&
);
scalarField frequencies
(
const label&
);
scalarField powerSpectra
(
const scalarField&,
const scalarField&,
const label&,
const scalar&
);
List<vectorField> powerSpectra
(
const scalarField&,
const List<vectorField>&,
const label&,
const scalar&
);
List<scalarField> powerSpectra
(
const scalarField&,
const List<scalarField>&,
const label& N,
const scalar&
);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 26.466216 | 79 | 0.513148 | MrAwesomeRocks |
f43233e9143cdf268ce84e2809cb31cb5c9415d1 | 1,286 | cpp | C++ | Source/core/layout/LayoutPagedFlowThread.cpp | prepare/Blink_only_permissive_lic_files | 8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4 | [
"BSD-3-Clause"
] | null | null | null | Source/core/layout/LayoutPagedFlowThread.cpp | prepare/Blink_only_permissive_lic_files | 8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4 | [
"BSD-3-Clause"
] | null | null | null | Source/core/layout/LayoutPagedFlowThread.cpp | prepare/Blink_only_permissive_lic_files | 8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "core/layout/LayoutPagedFlowThread.h"
namespace blink {
LayoutPagedFlowThread* LayoutPagedFlowThread::createAnonymous(Document& document, const ComputedStyle& parentStyle)
{
LayoutPagedFlowThread* LayoutObject = new LayoutPagedFlowThread();
LayoutObject->setDocumentForAnonymous(&document);
LayoutObject->setStyle(ComputedStyle::createAnonymousStyleWithDisplay(parentStyle, BLOCK));
return LayoutObject;
}
bool LayoutPagedFlowThread::needsNewWidth() const
{
return progressionIsInline() != pagedBlockFlow()->style()->hasInlinePaginationAxis();
}
void LayoutPagedFlowThread::updateLogicalWidth()
{
// As long as we inherit from LayoutMultiColumnFlowThread, we need to bypass its implementation
// here. We're not split into columns, so the flow thread width will just be whatever is
// available in the containing block.
LayoutFlowThread::updateLogicalWidth();
}
void LayoutPagedFlowThread::layout()
{
setProgressionIsInline(pagedBlockFlow()->style()->hasInlinePaginationAxis());
LayoutMultiColumnFlowThread::layout();
}
} // namespace blink
| 33.842105 | 115 | 0.774495 | prepare |
f433ba650422179f51533d41069c2b246d6e60a9 | 2,891 | cc | C++ | code/render/frame/frameplugin.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | null | null | null | code/render/frame/frameplugin.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | null | null | null | code/render/frame/frameplugin.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | null | null | null | //------------------------------------------------------------------------------
// frameplugin.cc
// (C) 2016-2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "render/stdneb.h"
#include "frameplugin.h"
namespace Frame
{
//------------------------------------------------------------------------------
/**
*/
FramePlugin::FramePlugin()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
FramePlugin::~FramePlugin()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
FramePlugin::CompiledImpl::Run(const IndexT frameIndex, const IndexT bufferIndex)
{
this->func(frameIndex, bufferIndex);
}
//------------------------------------------------------------------------------
/**
*/
void
FramePlugin::CompiledImpl::Discard()
{
this->func = nullptr;
}
//------------------------------------------------------------------------------
/**
*/
FrameOp::Compiled*
FramePlugin::AllocCompiled(Memory::ArenaAllocator<BIG_CHUNK>& allocator)
{
CompiledImpl* ret = allocator.Alloc<CompiledImpl>();
#if NEBULA_GRAPHICS_DEBUG
ret->name = this->name;
#endif
ret->func = this->func;
return ret;
}
//------------------------------------------------------------------------------
/**
*/
void
FramePlugin::Build(
Memory::ArenaAllocator<BIG_CHUNK>& allocator,
Util::Array<FrameOp::Compiled*>& compiledOps,
Util::Array<CoreGraphics::EventId>& events,
Util::Array<CoreGraphics::BarrierId>& barriers,
Util::Dictionary<CoreGraphics::BufferId, Util::Array<BufferDependency>>& rwBuffers,
Util::Dictionary<CoreGraphics::TextureId, Util::Array<TextureDependency>>& textures)
{
CompiledImpl* myCompiled = (CompiledImpl*)this->AllocCompiled(allocator);
this->compiled = myCompiled;
this->SetupSynchronization(allocator, events, barriers, rwBuffers, textures);
compiledOps.Append(myCompiled);
}
Util::Dictionary<Util::StringAtom, std::function<void(IndexT, IndexT)>> nameToFunction;
//------------------------------------------------------------------------------
/**
*/
const std::function<void(IndexT, IndexT)>&
GetCallback(const Util::StringAtom& str)
{
if (nameToFunction.Contains(str))
return nameToFunction[str];
else
{
n_printf("No function '%s' found\n", str.Value());
return nameToFunction["null"];
}
}
//------------------------------------------------------------------------------
/**
*/
void
AddCallback(const Util::StringAtom name, std::function<void(IndexT, IndexT)> func)
{
nameToFunction.Add(name, func);
}
//------------------------------------------------------------------------------
/**
*/
void
InitPluginTable()
{
nameToFunction.Add("null", nullptr);
}
} // namespace Frame2
| 24.709402 | 88 | 0.476306 | sirAgg |
f4378ba73efb592ab9fc2e6d69fecf7c201c49b5 | 2,449 | cpp | C++ | leetcode/problems/easy/26-remove-duplicates-from-sorted-array.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/problems/easy/26-remove-duplicates-from-sorted-array.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/problems/easy/26-remove-duplicates-from-sorted-array.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int i = !nums.empty();
for (int n : nums) if (n > nums[i - 1]) nums[i++] = n;
return i;
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int sz=nums.size();
if(!sz) return 0;
int i=0;
for(int j=1;j<nums.size();j++){
if(nums[j]!=nums[i]){
// We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array.
// So, we ought to use a two-pointer approach here.
// One, that would keep track of the current element in the original array and another one for just the unique elements.
i++;
nums[i]=nums[j];
}
// Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
}
return i+1;
}
};
static const auto io_sync_off = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}(); | 34.985714 | 151 | 0.665986 | wingkwong |
f438c6540d1b2df16928dedfb42152e7866f5de5 | 1,724 | hpp | C++ | babyrobot/src/object-assembly-agent-master/object_assembly_ros/include/object_assembly_ros/assembly_task_guess_mode.hpp | babyrobot-eu/core-modules | 7e8c006c40153fb649208c9a78fc71aa70243f69 | [
"MIT"
] | 1 | 2019-02-07T15:32:06.000Z | 2019-02-07T15:32:06.000Z | babyrobot/src/object-assembly-agent-master/object_assembly_ros/include/object_assembly_ros/assembly_task_guess_mode.hpp | babyrobot-eu/core-modules | 7e8c006c40153fb649208c9a78fc71aa70243f69 | [
"MIT"
] | 9 | 2020-01-28T22:09:41.000Z | 2022-03-11T23:39:17.000Z | babyrobot/src/object-assembly-agent-master/object_assembly_ros/include/object_assembly_ros/assembly_task_guess_mode.hpp | babyrobot-eu/core-modules | 7e8c006c40153fb649208c9a78fc71aa70243f69 | [
"MIT"
] | null | null | null | #include <assembly_subtask.hpp>
#include <cstdlib>
class AssemblyTask
{
public:
AssemblyTask(
int id,
int num_parts,
std::vector<std::vector<int>> connnection_pairs,
int num_connections,
std::vector<AssemblySubtask> subtasks,
int max_particles,
int all_particles,
int connection_list_offset,
std::string connection_vector_topic);
//returns current subtask
double evaluate_task(std::vector<tf::Transform> current_object_poses, std::vector<object_assembly_msgs::ConnectionInfo> &connection_list);
void set_connections(std::vector<object_assembly_msgs::ConnectionInfo> &connection_list);
tf::Quaternion calculate_prerotation();
void publish_connection_vector();
int num_connections_;
//struct AssemblySubgraph
//{
// std::vector<tf::Quaternion> rotations;
// std::vector<int> nodes;
//};
private:
ros::NodeHandle node_handle_;
ros::Publisher connection_vector_publisher_;
//int current_subtask_ = 0;
const int task_id_;
const int num_parts_;
const int connection_list_offset_;
int subgraph_max_index_ = -1;
std::vector<AssemblySubtask> subtasks_;
int max_particles_;
int all_particles_;
std::vector<std::vector<int>> connection_pairs_;
std::vector<bool> connection_status_vector_;
//std::vector<AssemblySubgraph> subgraph_list_;
std::vector<int> part_subgraph_index_; //which subgraph each part belongs to (-1 means none)
std::vector<double> scores_;
std::list<int> zero_score_queue_;
std::vector<int> zero_score_spotlight_times_;
std::vector<tf::Quaternion> rotations_;
//std::vector<int> rotation_index;
};
| 28.733333 | 142 | 0.703596 | babyrobot-eu |
f43adb441badf2b1ccfd5d8f037cc662692288eb | 1,441 | cpp | C++ | TP3_Prog_SpaceSim/warning_leaving_game_area.cpp | Arganancer/S3_TP3_Prog_SpaceSim | 43364f6613ad690f81c94f8a027ee3708fa58d3d | [
"MIT"
] | null | null | null | TP3_Prog_SpaceSim/warning_leaving_game_area.cpp | Arganancer/S3_TP3_Prog_SpaceSim | 43364f6613ad690f81c94f8a027ee3708fa58d3d | [
"MIT"
] | null | null | null | TP3_Prog_SpaceSim/warning_leaving_game_area.cpp | Arganancer/S3_TP3_Prog_SpaceSim | 43364f6613ad690f81c94f8a027ee3708fa58d3d | [
"MIT"
] | null | null | null | #include "warning_leaving_game_area.h"
#include "g_vars.hpp"
warning_leaving_game_area::warning_leaving_game_area()
{
warning_message_ = text(
"WARNING: LEAVING NAVIGABLE SPACE",
sf::Vector2f(g_vars::view_width / 2,
g_vars::view_height / 2 - 200),
text::warning_title, text::center);
distance_until_termination_ = text(
"PLACEHOLDER: distance until termination",
sf::Vector2f(g_vars::view_width / 2,
g_vars::view_height / 2 - 160),
text::warning, text::center);
time_until_termination_ = text(
"PLACEHOLDER: time until termination",
sf::Vector2f(g_vars::view_width / 2,
g_vars::view_height / 2 - 130),
text::warning, text::center);
alpha_channel_increasing_ = true;
overlay_color_ = sf::Color(214, 4, 4, 0);
overlay_.setFillColor(overlay_color_);
}
warning_leaving_game_area::~warning_leaving_game_area()
{
}
void warning_leaving_game_area::update(float delta_t)
{
if(alpha_channel_increasing_)
{
++overlay_color_.a;
if(overlay_color_.a >= 60)
{
alpha_channel_increasing_ = false;
}
}
else
{
--overlay_color_.a;
if (overlay_color_.a <= 15)
{
alpha_channel_increasing_ = true;
}
}
overlay_.setFillColor(overlay_color_);
overlay::update(delta_t);
}
void warning_leaving_game_area::draw(sf::RenderWindow& main_win)
{
overlay::draw(main_win);
warning_message_.draw(main_win);
distance_until_termination_.draw(main_win);
time_until_termination_.draw(main_win);
}
| 23.241935 | 64 | 0.734906 | Arganancer |
f43dac6a98496e8ef946ae6d3f000cb52c668d8e | 1,993 | cpp | C++ | tests/exec/josephus.cpp | xuedong/mini-cpp | 3f4c505e3c422709e2da3fec1ecea7165f76292b | [
"MIT"
] | null | null | null | tests/exec/josephus.cpp | xuedong/mini-cpp | 3f4c505e3c422709e2da3fec1ecea7165f76292b | [
"MIT"
] | null | null | null | tests/exec/josephus.cpp | xuedong/mini-cpp | 3f4c505e3c422709e2da3fec1ecea7165f76292b | [
"MIT"
] | null | null | null | #include <iostream>
/*** listes circulaires doublement chaînées ***/
class ListeC {
public:
int valeur;
ListeC *suivant;
ListeC *precedent;
ListeC(int v);
void insererApres(int v);
void supprimer();
void afficher();
};
/* constructeur = liste réduite à un élément */
ListeC::ListeC(int v) {
valeur = v;
suivant = precedent = this;
}
/* insertion après un élément */
void ListeC::insererApres(int v) {
ListeC *e = new ListeC(0);
e->valeur = v;
e->suivant = suivant;
suivant = e;
e->suivant->precedent = e;
e->precedent = this;
}
/* suppression d'un élément */
void ListeC::supprimer() {
precedent->suivant = suivant;
suivant->precedent = precedent;
}
/* affichage */
void ListeC::afficher() {
ListeC *c = this;
std::cout << c->valeur << " ";
c = c->suivant;
for (; c != this;) {
std::cout << c->valeur << " ";
c = c->suivant;
}
std::cout << "\n";
}
/*** problème de Josephus ***/
/* construction de la liste circulaire 1,2,...,n;
l'élément retourné est celui contenant 1 */
ListeC *cercle(int n) {
ListeC *l = new ListeC(1);
int i;
for (i = n; i >= 2; i--) {
l->insererApres(i);
}
return l;
}
/* jeu de Josephus */
int josephus(int n, int p) {
/* c est le joueur courant, 1 au départ */
ListeC *c = cercle(n);
/* tant qu'il reste plus d'un joueur */
for (; c != c->suivant;) {
/* on élimine un joueur */
int i;
for (i = 1; i < p; i++)
c = c->suivant;
c->supprimer();
// std::cout << c->valeur << " est éliminé";
c = c->suivant;
}
// std::cout << "le gagnant est " << c->valeur;
return c->valeur;
}
/*** Tests ***/
int main() {
ListeC l = ListeC(1);
l.afficher();
l.insererApres(3);
l.afficher();
l.insererApres(2);
l.afficher();
l.suivant->supprimer();
l.afficher();
ListeC *c = cercle(7);
c->afficher();
if (josephus(7, 5) == 6 &&
josephus(5, 5) == 2 &&
josephus(5, 17) == 4 && josephus(13, 2) == 11)
std::cout << "ok\n";
}
| 19.539216 | 52 | 0.564977 | xuedong |
f4424c59eca2beb900b96c092a0aaae4c3d28634 | 13,021 | cc | C++ | zircon/system/ulib/cobalt-client/test/histogram_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | zircon/system/ulib/cobalt-client/test/histogram_test.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | zircon/system/ulib/cobalt-client/test/histogram_test.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2018 The Fuchsia 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 <cobalt-client/cpp/histogram.h>
#include <lib/fit/function.h>
#include <lib/sync/completion.h>
#include <lib/zx/time.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <cstdint>
#include <mutex>
#include <string_view>
#include <thread>
#include <cobalt-client/cpp/collector.h>
#include <cobalt-client/cpp/histogram_internal.h>
#include <cobalt-client/cpp/in_memory_logger.h>
#include <cobalt-client/cpp/metric_options.h>
#include <zxtest/zxtest.h>
namespace cobalt_client {
namespace internal {
namespace {
constexpr uint32_t kBucketCount = 20;
using TestBaseHistogram = BaseHistogram<kBucketCount>;
TEST(BaseHistogramTest, BucketCountStartsAtZero) {
TestBaseHistogram histogram;
ASSERT_EQ(kBucketCount, histogram.size());
for (uint32_t i = 0; i < kBucketCount; ++i) {
EXPECT_EQ(0, histogram.GetCount(i));
}
}
TEST(BaseHistogramTest, IncrementCountByDefaultIncrementsBucketCountByOne) {
constexpr uint32_t kTargetBucket = 2;
TestBaseHistogram histogram;
histogram.IncrementCount(kTargetBucket);
for (uint32_t i = 0; i < kBucketCount; ++i) {
if (i == kTargetBucket) {
continue;
}
EXPECT_EQ(0, histogram.GetCount(i));
}
EXPECT_EQ(1, histogram.GetCount(kTargetBucket));
}
TEST(BaseHistogramTest, IncrementCountWithValueIncrementsBucketCountByValue) {
constexpr uint32_t kTargetBucket = 2;
constexpr uint64_t kValue = 123456;
TestBaseHistogram histogram;
histogram.IncrementCount(kTargetBucket, kValue);
for (uint32_t i = 0; i < kBucketCount; ++i) {
if (i == kTargetBucket) {
continue;
}
EXPECT_EQ(0, histogram.GetCount(i));
}
EXPECT_EQ(kValue, histogram.GetCount(kTargetBucket));
}
TEST(BaseHistogramTest, IncrementCountIsIsolated) {
constexpr std::array<uint32_t, 5> kTargetBuckets = {2, 4, 6, 8, 10};
constexpr uint64_t kValue = 123456;
TestBaseHistogram histogram;
for (auto bucket : kTargetBuckets) {
histogram.IncrementCount(bucket, kValue + bucket);
}
for (uint32_t i = 0; i < kBucketCount; ++i) {
if (std::find(kTargetBuckets.begin(), kTargetBuckets.end(), i) != kTargetBuckets.end()) {
EXPECT_EQ(kValue + i, histogram.GetCount(i));
continue;
}
EXPECT_EQ(0, histogram.GetCount(i));
}
}
TEST(BaseHistogramTest, IncrementCountFromMultipleTheadsIsConsistent) {
constexpr uint64_t kThreadCount = 20;
constexpr uint64_t kTimes = 200;
TestBaseHistogram histogram;
std::array<std::thread, kThreadCount> incrementing_threads;
sync_completion_t start_signal;
auto increment_fn = [&histogram, &start_signal]() {
sync_completion_wait(&start_signal, zx::duration::infinite().get());
for (uint64_t i = 0; i < kTimes; ++i) {
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
histogram.IncrementCount(bucket_index);
}
}
};
for (uint64_t i = 0; i < kThreadCount; i++) {
incrementing_threads[i] = std::thread(increment_fn);
}
sync_completion_signal(&start_signal);
for (auto& thread : incrementing_threads) {
thread.join();
}
constexpr uint64_t kExpectedCount = kTimes * kThreadCount;
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
EXPECT_EQ(kExpectedCount, histogram.GetCount(bucket_index));
}
}
using TestRemoteHistogram = RemoteHistogram<kBucketCount>;
// Default id for the histogram.
constexpr uint64_t kMetricId = 1;
// Default component name.
constexpr std::string_view kComponentName = "RemoteHisotgramComponentName";
// Default event codes.
constexpr std::array<uint32_t, MetricOptions::kMaxEventCodes> kEventCodes = {1, 2, 3, 4, 5};
HistogramOptions MakeHistogramOptions() {
HistogramOptions options = HistogramOptions::CustomizedExponential(kBucketCount, 2, 1, 0);
options.metric_id = kMetricId;
options.component = kComponentName;
options.event_codes = kEventCodes;
return options;
}
TestRemoteHistogram MakeRemoteHistogram() { return TestRemoteHistogram(MakeHistogramOptions()); }
TEST(RemoteHistogramTest, FlushSetsBucketsToZeroAndReturnsTrueIfLogSucceeds) {
TestRemoteHistogram histogram = MakeRemoteHistogram();
InMemoryLogger logger;
logger.fail_logging(false);
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
histogram.IncrementCount(bucket_index, bucket_index + 1);
}
ASSERT_TRUE(histogram.Flush(&logger));
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
EXPECT_EQ(0, histogram.GetCount(bucket_index));
}
const auto& logged_histograms = logger.histograms();
auto logged_histogram_itr = logged_histograms.find(histogram.metric_options());
ASSERT_NE(logged_histograms.end(), logged_histogram_itr);
const auto& logged_histogram = logged_histogram_itr->second;
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
const uint64_t kExpectedCount = bucket_index + 1;
ASSERT_NE(logged_histogram.end(), logged_histogram.find(bucket_index));
EXPECT_EQ(kExpectedCount, logged_histogram.at(bucket_index));
}
}
TEST(RemoteHistogramTest, FlushSetsBucketsToZeroAndReturnsFalseIfLogFails) {
TestRemoteHistogram histogram = MakeRemoteHistogram();
InMemoryLogger logger;
logger.fail_logging(true);
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
histogram.IncrementCount(bucket_index, bucket_index + 1);
}
ASSERT_FALSE(histogram.Flush(&logger));
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
EXPECT_EQ(0, histogram.GetCount(bucket_index));
}
const auto& logged_histograms = logger.histograms();
auto logged_histogram_itr = logged_histograms.find(histogram.metric_options());
ASSERT_EQ(logged_histograms.end(), logged_histogram_itr);
}
TEST(RemoteHistogramTest, UndoFlushSetsCounterToPreviousValue) {
TestRemoteHistogram histogram = MakeRemoteHistogram();
InMemoryLogger logger;
logger.fail_logging(true);
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
histogram.IncrementCount(bucket_index, bucket_index + 1);
}
ASSERT_FALSE(histogram.Flush(&logger));
histogram.UndoFlush();
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
EXPECT_EQ(bucket_index + 1, histogram.GetCount(bucket_index));
}
}
using TestHistogram = Histogram<kBucketCount>;
TEST(HistogramTest, ConstructFromOptionsIsOk) {
ASSERT_NO_DEATH([] { [[maybe_unused]] TestHistogram histogram(MakeHistogramOptions()); });
}
TEST(HistogramTest, ConstructFromOptionsWithCollectorIsOk) {
ASSERT_NO_DEATH([] {
std::unique_ptr<InMemoryLogger> logger = std::make_unique<InMemoryLogger>();
Collector collector(std::move(logger));
[[maybe_unused]] TestHistogram histogram(MakeHistogramOptions(), &collector);
});
}
TEST(HistogramTest, InitilizeAlreadyInitializedHistogramIsAssertionError) {
std::unique_ptr<InMemoryLogger> logger = std::make_unique<InMemoryLogger>();
Collector collector(std::move(logger));
HistogramOptions histogram_options = MakeHistogramOptions();
[[maybe_unused]] TestHistogram histogram(histogram_options, &collector);
ASSERT_DEATH([&]() { histogram.Initialize(histogram_options, &collector); });
}
void InMemoryLoggerContainsHistogramWithBucketCount(const TestHistogram& histogram,
const InMemoryLogger& logger,
int64_t logged_value, uint64_t logged_count) {
const auto& logged_histograms = logger.histograms();
auto logged_histogram_itr = logged_histograms.find(histogram.GetOptions());
ASSERT_NE(logged_histograms.end(), logged_histogram_itr);
const auto& logged_histogram = logged_histogram_itr->second;
uint32_t bucket_index = histogram.GetOptions().map_fn(static_cast<double>(logged_value),
histogram.size(), histogram.GetOptions());
auto bucket_itr = logged_histogram.find(bucket_index);
ASSERT_NE(logged_histogram.end(), bucket_itr);
uint64_t actual_count = bucket_itr->second;
EXPECT_EQ(logged_count, actual_count);
}
fit::function<void(uint64_t, uint64_t)> MakeLoggedHistogramContainsChecker(
const TestHistogram& histogram, const InMemoryLogger& logger) {
return [&histogram, &logger](uint64_t value, uint64_t count) {
InMemoryLoggerContainsHistogramWithBucketCount(histogram, logger, value, count);
};
}
TEST(HistogramTest, AddIncreasesCorrectBucketCount) {
constexpr uint64_t kValue = 25;
std::unique_ptr<InMemoryLogger> logger = std::make_unique<InMemoryLogger>();
logger->fail_logging(false);
auto* logger_ptr = logger.get();
Collector collector(std::move(logger));
TestHistogram histogram(MakeHistogramOptions(), &collector);
histogram.Add(kValue);
ASSERT_EQ(1, histogram.GetCount(kValue));
ASSERT_TRUE(collector.Flush());
ASSERT_EQ(0, histogram.GetCount(kValue));
auto logged_histogram_contains = MakeLoggedHistogramContainsChecker(histogram, *logger_ptr);
ASSERT_NO_FAILURES(logged_histogram_contains(kValue, 1));
}
TEST(HistogramTest, AddWithCountIncreasesCorrectBucketCount) {
constexpr uint64_t kValue = 25;
constexpr uint64_t kCount = 25678;
std::unique_ptr<InMemoryLogger> logger = std::make_unique<InMemoryLogger>();
logger->fail_logging(false);
auto* logger_ptr = logger.get();
Collector collector(std::move(logger));
TestHistogram histogram(MakeHistogramOptions(), &collector);
histogram.Add(kValue, kCount);
ASSERT_EQ(kCount, histogram.GetCount(kValue));
ASSERT_TRUE(collector.Flush());
ASSERT_EQ(0, histogram.GetCount(kValue));
auto logged_histogram_contains = MakeLoggedHistogramContainsChecker(histogram, *logger_ptr);
ASSERT_NO_FAILURES(logged_histogram_contains(kValue, kCount));
}
TEST(HistogramTest, AddIncreasesCountByOne) {
constexpr uint64_t kValue = 25;
TestHistogram histogram(MakeHistogramOptions());
histogram.Add(kValue);
EXPECT_EQ(1, histogram.GetCount(kValue));
}
TEST(HistogramTest, AddValueIncreasesCountByValue) {
constexpr uint64_t kValue = 25;
constexpr uint64_t kTimes = 100;
TestHistogram histogram(MakeHistogramOptions());
histogram.Add(kValue, kTimes);
EXPECT_EQ(kTimes, histogram.GetCount(kValue));
}
TEST(HistogramTest, AddOnMultipleThreadsWithSynchronizedFlushingIsConsistent) {
constexpr uint64_t kTimes = 1;
constexpr uint64_t kThreadCount = 20;
std::unique_ptr<InMemoryLogger> logger = std::make_unique<InMemoryLogger>();
auto* logger_ptr = logger.get();
std::mutex logger_mutex;
Collector collector(std::move(logger));
TestHistogram histogram(MakeHistogramOptions(), &collector);
sync_completion_t start_signal;
std::array<std::thread, kThreadCount> spamming_threads = {};
auto get_value_for_bucket = [&histogram](uint32_t bucket_index) {
const double bucket_value = histogram.GetOptions().reverse_map_fn(
bucket_index, histogram.size(), histogram.GetOptions());
return static_cast<int64_t>(
std::max<double>(std::numeric_limits<int64_t>::min(), bucket_value));
};
auto increment_fn = [&histogram, &start_signal, &get_value_for_bucket]() {
sync_completion_wait(&start_signal, zx::duration::infinite().get());
for (uint64_t i = 0; i < kTimes; ++i) {
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
const int64_t kValue = get_value_for_bucket(bucket_index);
histogram.Add(kValue, bucket_index + 1);
}
}
};
auto flushing_fn = [&collector, &logger_ptr, &logger_mutex, &start_signal]() {
sync_completion_wait(&start_signal, zx::duration::infinite().get());
for (uint64_t i = 0; i < kTimes; ++i) {
bool result = collector.Flush();
{
std::lock_guard lock(logger_mutex);
logger_ptr->fail_logging(!result);
}
}
};
for (uint64_t thread = 0; thread < kThreadCount; ++thread) {
if (thread % 2 == 0) {
spamming_threads[thread] = std::thread(increment_fn);
} else {
spamming_threads[thread] = std::thread(flushing_fn);
}
}
sync_completion_signal(&start_signal);
for (auto& thread : spamming_threads) {
thread.join();
}
logger_ptr->fail_logging(false);
ASSERT_TRUE(collector.Flush());
constexpr uint64_t kBaseExpectedCount = (kThreadCount / 2) * kTimes;
auto logged_histogram_contains = MakeLoggedHistogramContainsChecker(histogram, *logger_ptr);
for (uint32_t bucket_index = 0; bucket_index < histogram.size(); ++bucket_index) {
const uint64_t kExpectedCount = kBaseExpectedCount * (bucket_index + 1);
const int64_t kValue = get_value_for_bucket(bucket_index);
ASSERT_NO_FAILURES(logged_histogram_contains(kValue, kExpectedCount));
}
}
} // namespace
} // namespace internal
} // namespace cobalt_client
| 33.997389 | 98 | 0.737501 | allansrc |
f443843d4f7f7e67650e9d5c9413d5fec5e2ad56 | 11,726 | cc | C++ | src/scheduler.cc | sunnyxhuang/2D-Placement | 53310fa7336430a1b82b3ed3fa98409ab5d4b7d5 | [
"Apache-2.0"
] | 4 | 2017-09-01T14:43:01.000Z | 2017-09-02T04:58:55.000Z | src/scheduler.cc | little-by/2D-Placement | 53310fa7336430a1b82b3ed3fa98409ab5d4b7d5 | [
"Apache-2.0"
] | null | null | null | src/scheduler.cc | little-by/2D-Placement | 53310fa7336430a1b82b3ed3fa98409ab5d4b7d5 | [
"Apache-2.0"
] | 3 | 2017-09-21T08:24:51.000Z | 2018-10-30T04:46:15.000Z | #include <algorithm>
#include <iomanip>
#include <cfloat>
#include <sys/time.h>
#include <string.h>
#include "coflow.h"
#include "events.h"
#include "global.h"
#include "scheduler.h"
#include "util.h"
#define MWM_RANGE 100000000 //2147483647 = 2,147,483,647
using namespace std;
///////////////////////////////////////////////////////
////////////// Code for base class Scheduler
///////////////////////////////////////////////////////
Scheduler::Scheduler() {
m_simPtr = NULL;
m_currentTime = 0;
m_myTimeLine = new SchedulerTimeLine();
m_coflowPtrVector = vector<Coflow *>();
m_nextElecRate = map<int, long>();
m_nextOptcRate = map<int, long>();
}
Scheduler::~Scheduler() {
delete m_myTimeLine;
}
void
Scheduler::UpdateAlarm() {
// update alarm for scheduler on simulator
if (!m_myTimeLine->isEmpty()) {
Event *nextEvent = m_myTimeLine->PeekNext();
double nextTime = nextEvent->GetEventTime();
Event *schedulerAlarm = new Event(ALARM_SCHEDULER, nextTime);
m_simPtr->UpdateSchedulerAlarm(schedulerAlarm);
}
}
void
Scheduler::NotifySimEnd() {
return;
cout << "[Scheduler::NotifySimEnd()] is called." << endl;
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end(); cfIt++) {
vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows();
for (vector<Flow *>::iterator fpIt = flowVecPtr->begin();
fpIt != flowVecPtr->end(); fpIt++) {
if ((*fpIt)->GetBitsLeft() <= 0) {
// such flow has finished
continue;
}
cout << "[Scheduler::NotifySimEnd()] flow [" << (*fpIt)->GetFlowId()
<< "] "
<< "(" << (*fpIt)->GetSrc() << "=>" << (*fpIt)->GetDest() << ") "
<< (*fpIt)->GetSizeInBit() << " bytes "
<< (*fpIt)->GetBitsLeft() << " bytes left "
<< (*fpIt)->GetElecRate() << " bps" << endl;
}
}
}
bool
Scheduler::Transmit(double startTime,
double endTime,
bool basic,
bool local,
bool salvage) {
CircuitAuditIfNeeded(startTime, endTime);
bool hasCoflowFinish = false;
bool hasFlowFinish = false;
bool hasCoflowTmpFinish = false;
vector<Coflow *> finished_coflows;
vector<Flow *> finished_flows;
m_validate_last_tx_src_bits.clear();
m_validate_last_tx_dst_bits.clear();
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end();) {
if ((*cfIt)->IsFlowsAddedComplete()) {
// coflow not completed yet
// but the flows added so far have finished
cfIt++;
continue;
}
vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows();
for (vector<Flow *>::iterator fpIt = flowVecPtr->begin();
fpIt != flowVecPtr->end(); fpIt++) {
if ((*fpIt)->GetBitsLeft() <= 0) {
// such flow has finished
continue;
}
// tx rate verification debug
long validate_tx_this_flow_bits = (*fpIt)->GetBitsLeft();
// ********* begin tx ****************
if (basic) {
(*fpIt)->Transmit(startTime, endTime);
}
if (local) {
(*fpIt)->TxLocal();
}
if (salvage) {
(*fpIt)->TxSalvage();
}
// ********* end tx ********************
// tx rate verification debug
validate_tx_this_flow_bits -= (*fpIt)->GetBitsLeft();
MapWithInc(m_validate_last_tx_src_bits,
(*fpIt)->GetSrc(),
validate_tx_this_flow_bits);
MapWithInc(m_validate_last_tx_dst_bits,
(*fpIt)->GetDest(),
validate_tx_this_flow_bits);
if ((*fpIt)->GetBitsLeft() == 0) {
hasFlowFinish = true;
(*cfIt)->NumFlowFinishInc();
(*fpIt)->SetEndTime(endTime);
finished_flows.push_back(*fpIt);
}
// update coflow account on bytes sent.
(*cfIt)->AddTxBit(validate_tx_this_flow_bits);
}
// debug for coflow progress
if (DEBUG_LEVEL >= 3 && hasFlowFinish) {
cout << fixed << setw(FLOAT_TIME_WIDTH) << endTime << "s ";
cout << (*cfIt)->toString() << endl;
}
if ((*cfIt)->IsComplete()) {
//cout << string(FLOAT_TIME_WIDTH+2, ' ')
cout << fixed << setw(FLOAT_TIME_WIDTH) << endTime << "s "
<< "[Scheduler::Transmit] coflow finish! # "
<< (*cfIt)->GetJobId() << endl;
Coflow * finished_coflow = *cfIt;
finished_coflows.push_back(finished_coflow);
finished_coflow->SetEndTime(endTime);
hasCoflowFinish = true;
// advance coflow iterator.
cfIt = m_coflowPtrVector.erase(cfIt);
} else {
if ((*cfIt)->IsFlowsAddedComplete()) {
hasCoflowTmpFinish = true;
}
// jump to next coflow
cfIt++;
}
}
ScheduleToNotifyTrafficFinish(endTime, finished_coflows, finished_flows);
if (hasCoflowFinish || hasCoflowTmpFinish) {
CoflowFinishCallBack(endTime);
} else if (hasFlowFinish) {
FlowFinishCallBack(endTime);
}
if (hasCoflowFinish || hasCoflowTmpFinish || hasFlowFinish) {
Scheduler::UpdateFlowFinishEvent(endTime);
}
if (hasCoflowFinish || hasCoflowTmpFinish || hasFlowFinish) {
return true;
}
return false;
}
void
Scheduler::ScheduleToNotifyTrafficFinish(double end_time,
vector<Coflow *> &coflows_done,
vector<Flow *> &flows_done) {
if (coflows_done.empty() && flows_done.empty()) {
return;
}
//notify traffic generator of coflow / flow finish
vector<Coflow *> *finishedCf = new vector<Coflow *>(coflows_done);
vector<Flow *> *finishedF = new vector<Flow *>(flows_done);
MsgEventTrafficFinish *msgEventPtr =
new MsgEventTrafficFinish(end_time, finishedCf, finishedF);
m_simPtr->AddEvent(msgEventPtr);
if (!coflows_done.empty()) {
WriteCircuitAuditIfNeeded(end_time, coflows_done);
}
}
//returns negative if all flows has finished
//return DBL_MAX if all flows are waiting indefinitely
double
Scheduler::CalcTime2FirstFlowEnd() {
double time2FirstFinish = DBL_MAX;
bool hasUnfinishedFlow = false;
bool finishTimeValid = false;
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end(); cfIt++) {
if ((*cfIt)->IsFlowsAddedComplete()) {
//flows added in such coflow have all completed
continue;
}
vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows();
for (vector<Flow *>::iterator fpIt = flowVecPtr->begin();
fpIt != flowVecPtr->end(); fpIt++) {
if ((*fpIt)->GetBitsLeft() <= 0) {
//such flow has completed
continue;
}
hasUnfinishedFlow = true;
// calc the min finishing time
double flowCompleteTime = DBL_MAX;
if ((*fpIt)->isThruOptic() && (*fpIt)->GetOptcRate() > 0) {
flowCompleteTime = SecureFinishTime((*fpIt)->GetBitsLeft(),
(*fpIt)->GetOptcRate());
} else if (!(*fpIt)->isThruOptic() && (*fpIt)->GetElecRate() > 0) {
flowCompleteTime = SecureFinishTime((*fpIt)->GetBitsLeft(),
(*fpIt)->GetElecRate());
}
if (time2FirstFinish > flowCompleteTime) {
finishTimeValid = true;
time2FirstFinish = flowCompleteTime;
}
}
}
if (hasUnfinishedFlow) {
if (finishTimeValid) {
return time2FirstFinish;
} else {
//all flows are waiting indefinitely
return DBL_MAX;
}
} else {
// all flows are finished
return -DBL_MAX;
}
}
void
Scheduler::UpdateFlowFinishEvent(double baseTime) {
double time2FirstFinish = CalcTime2FirstFlowEnd();
if (time2FirstFinish == DBL_MAX) {
// all flows are waiting indefinitely
m_myTimeLine->RemoveSingularEvent(FLOW_FINISH);
} else if (time2FirstFinish == -DBL_MAX) {
// all flows are done
} else {
// valid finishing time
m_myTimeLine->RemoveSingularEvent(FLOW_FINISH);
double firstFinishTime = baseTime + time2FirstFinish;
Event *flowFinishEventPtr = new Event(FLOW_FINISH, firstFinishTime);
m_myTimeLine->AddEvent(flowFinishEventPtr);
}
}
void
Scheduler::UpdateRescheduleEvent(double reScheduleTime) {
m_myTimeLine->RemoveSingularEvent(RESCHEDULE);
Event *rescheduleEventPtr = new Event(RESCHEDULE, reScheduleTime);
m_myTimeLine->AddEvent(rescheduleEventPtr);
}
void
Scheduler::NotifyAddFlows(double alarmTime) {
//FlowArrive(alarmTime);
EventFlowArrive *msgEp = new EventFlowArrive(alarmTime);
m_myTimeLine->AddEvent(msgEp);
UpdateAlarm();
}
void
Scheduler::NotifyAddCoflows(double alarmTime, vector<Coflow *> *cfVecPtr) {
//CoflowArrive(alarmTime,cfVecPtr);
EventCoflowArrive *msgEp = new EventCoflowArrive(alarmTime, cfVecPtr);
m_myTimeLine->AddEvent(msgEp);
UpdateAlarm();
}
double
Scheduler::SecureFinishTime(long bits, long rate) {
if (rate == 0) {
return DBL_MAX;
}
double timeLen = (double) bits / (double) rate;
// more complicated impl below *********
long bitsleft = 1;
int delta = 0;
while (bitsleft > 0) {
timeLen = (double) (delta + bits) / (double) rate;
bitsleft = bits - rate * timeLen;
delta++;
}
// more complicated impl above *****
//if (timeLen < 0.0000000001) return 0.0000000001;
return timeLen;
}
void
Scheduler::Print(void) {
return;
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end(); cfIt++) {
if (cfIt == m_coflowPtrVector.begin()) {
cout << fixed << setw(FLOAT_TIME_WIDTH)
<< m_currentTime << "s ";
} else {
cout << string(FLOAT_TIME_WIDTH + 2, ' ');
}
cout << "[Scheduler::Print] "
<< "Coflow ID " << (*cfIt)->GetCoflowId() << endl;
(*cfIt)->Print();
}
}
// copy flow rate from m_nextElecRate & m_nextOptcRate
// and reflect the rate on flow record.
void
Scheduler::SetFlowRate() {
for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin();
cfIt != m_coflowPtrVector.end(); cfIt++) {
vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows();
for (vector<Flow *>::iterator fpIt = flowVecPtr->begin();
fpIt != flowVecPtr->end(); fpIt++) {
//set flow rate
int flowId = (*fpIt)->GetFlowId();
long elecBps = MapWithDef(m_nextElecRate, flowId, (long) 0);
long optcBps = MapWithDef(m_nextOptcRate, flowId, (long) 0);
(*fpIt)->SetRate(elecBps, optcBps);
}
}
}
void
Scheduler::CalAlphaAndSortCoflowsInPlace(vector<Coflow *> &coflows) {
for (vector<Coflow *>::iterator it = coflows.begin();
it != coflows.end(); it++) {
(*it)->CalcAlpha();
}
std::stable_sort(coflows.begin(), coflows.end(), coflowCompAlpha);
}
bool
Scheduler::ValidateLastTxMeetConstraints(long port_bound_bits) {
for (map<int, long>::const_iterator
src_kv_pair = m_validate_last_tx_src_bits.begin();
src_kv_pair != m_validate_last_tx_src_bits.end();
src_kv_pair++) {
if (src_kv_pair->second > port_bound_bits) {
cout << "Error in validating TX constraints!!! " << endl
<< " src " << src_kv_pair->first << " flows over bound "
<< port_bound_bits << endl;
return false;
}
}
for (map<int, long>::const_iterator
dst_kv_pair = m_validate_last_tx_dst_bits.begin();
dst_kv_pair != m_validate_last_tx_dst_bits.end();
dst_kv_pair++) {
if (dst_kv_pair->second > port_bound_bits) {
cout << "Error in validating TX constraints!!! " << endl
<< " dst " << dst_kv_pair->first << " flows over bound "
<< port_bound_bits << endl;
return false;
}
}
// cout << "TX budget is valid." << endl;
return true;
}
| 28.953086 | 76 | 0.609074 | sunnyxhuang |
f444a252e66e85d298218ff08191db87f3891e87 | 238 | hpp | C++ | include/RavEngine/AnimatorSystem.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 48 | 2020-11-18T23:14:25.000Z | 2022-03-11T09:13:42.000Z | include/RavEngine/AnimatorSystem.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 1 | 2020-11-17T20:53:10.000Z | 2020-12-01T20:27:36.000Z | include/RavEngine/AnimatorSystem.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 3 | 2020-12-22T02:40:39.000Z | 2021-10-08T02:54:22.000Z | #pragma once
#include "System.hpp"
#include "AnimatorComponent.hpp"
namespace RavEngine{
class AnimatorSystem : public AutoCTTI{
public:
inline void Tick(float fpsScale, Ref<AnimatorComponent> c) const {
c->Tick(fpsScale);
}
};
}
| 18.307692 | 70 | 0.739496 | Ravbug |
f446e49c22efe8b62648400235466cd0079e1715 | 353 | cpp | C++ | Practice/2019.2.9/CF15E.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2019.2.9/CF15E.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2019.2.9/CF15E.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int Mod=1000000009;
int main()
{
int n;
scanf("%d",&n);
int sum=0,mul=4,pw=2;
while (n>2) {
n-=2;
pw=2ll*pw%Mod;
mul=1ll*mul*(pw-3+Mod)%Mod;
sum=(sum+mul)%Mod;
}
sum=(2ll*sum*sum%Mod+8ll*sum%Mod+10)%Mod;
printf("%d\n",sum);
return 0;
} | 15.347826 | 42 | 0.631728 | SYCstudio |
f44776b3a2b74cf641e9ff802c03579e5fd140aa | 12,871 | hpp | C++ | src/mge/core/exception.hpp | mge-engine/mge | e7a6253f99dd640a655d9a80b94118d35c7d8139 | [
"MIT"
] | null | null | null | src/mge/core/exception.hpp | mge-engine/mge | e7a6253f99dd640a655d9a80b94118d35c7d8139 | [
"MIT"
] | 91 | 2019-03-09T11:31:29.000Z | 2022-02-27T13:06:06.000Z | src/mge/core/exception.hpp | mge-engine/mge | e7a6253f99dd640a655d9a80b94118d35c7d8139 | [
"MIT"
] | null | null | null | // mge - Modern Game Engine
// Copyright (c) 2021 by Alexander Schroeder
// All rights reserved.
#pragma once
#include "mge/config.hpp"
#include "mge/core/dllexport.hpp"
#include "mge/core/stacktrace.hpp"
#include "mge/core/type_name.hpp"
#include <any>
#include <exception>
#include <optional>
#include <sstream>
#include <string_view>
#include <type_traits>
#include <typeindex>
#include <typeinfo>
namespace mge {
/**
* @brief An exception.
*/
class MGECORE_EXPORT exception : virtual public std::exception
{
public:
/**
* Helper class for detailed exception information.
*/
struct exception_details
{
public:
exception_details(const mge::exception* ex) noexcept
: m_ex(ex)
{}
inline const mge::exception* ex() const noexcept { return m_ex; }
private:
const mge::exception* m_ex;
};
private:
struct tag_base
{};
public:
/**
* @brief Exception value tag type.
*
* @tparam Tag type used to access the value
* @tparam Value stored value type
*
* The tag type is used to attach values to the
* exception.
*
* To use it, create a type that will hold the information as a
* member @c value, and derive that type from the tag type as follows.
* @code
* // A 'foo' value will hold a string attached to an exception.
* struct foo : public tag<foo, std::string>
* {
* std::string value;
* };
* @endcode
*/
template <typename Tag, typename Value> struct tag : public tag_base
{
using tag_type = Tag; //!< Tag type.
using value_type = Value; //!< Value type of value stored under tag.
};
/**
* @brief Source file name attached to exception.
*/
struct source_file : public tag<source_file, std::string_view>
{
/**
* @brief Capture source file name.
* @param value_ source file name
*/
source_file(const std::string_view& value_) noexcept
: m_value(value_)
{}
std::string_view value() const noexcept { return m_value; }
std::string_view m_value;
};
/**
* @brief Function name attached to exception.
*/
struct function : public tag<function, std::string_view>
{
/**
* @brief Capture current function name.
* @param value_ current function name
*/
function(const std::string_view& value_) noexcept
: m_value(value_)
{}
std::string_view value() const noexcept { return m_value; }
std::string_view m_value;
};
/**
* @brief Source file line number attached to exception.
*/
struct source_line : public tag<source_line, uint32_t>
{
/**
* @brief Capture source line number.
* @param value_ source line number
*/
source_line(uint32_t value_) noexcept
: m_value(value_)
{}
uint32_t value() const noexcept { return m_value; }
uint32_t m_value;
};
/**
* @brief Stack backtrace attached to exception.
*/
struct stack : public tag<stack, mge::stacktrace>
{
/**
* @brief Capture stack backtrace.
*
* @param s stack backtrace
*/
stack(mge::stacktrace&& s)
: m_value(std::move(s))
{}
const mge::stacktrace& value() const noexcept { return m_value; }
mge::stacktrace m_value;
};
/**
* @brief Message attached to exception.
*/
struct message : public tag<message, std::string>
{
message() {}
std::string_view value() const noexcept { return m_value; }
std::string m_value;
};
/**
* @brief Exception type name.
*/
struct type_name : public tag<type_name, std::string>
{
/**
* @brief Capture exception type name (subclass of mge::exception).
*
* @param name type name
*/
type_name(std::string_view name)
: m_value(name)
{}
const std::string& value() const noexcept { return m_value; }
std::string m_value;
};
/**
* @brief Function in which exception is thrown.
*/
struct called_function : public tag<called_function, std::string_view>
{
/**
* @brief Capture called function that raised the error.
*
* @param name called function
*/
called_function(const std::string_view& name)
: m_value(name)
{}
std::string_view value() const noexcept { return m_value; }
std::string_view m_value;
};
struct cause;
/**
* @brief Construct empty exception.
*/
exception();
/**
* @brief Copy constructor.
* @param ex copied exception
*/
exception(const exception& ex);
/**
* @brief Move constructor.
* @param ex moved exception
*/
exception(exception&& ex);
/**
* Destructor.
*/
virtual ~exception();
/**
* Assignment.
* @return @c *this
*/
exception& operator=(const exception&);
/**
* Move assignment.
* @param e moved exception
* @return @c *this
*/
exception& operator=(exception&& e);
/**
* Overrides @c std::exception @c what function.
* @return exception message
*/
const char* what() const override;
/**
* Get current exception of this thread.
* @return pointer to current exception or @c nullptr if there is none
*/
static mge::exception* current_exception();
/**
* @brief Set information associated with tag type.
*
* @tparam Info info tag type
* @param info information stored under the tag
* @return @c *this
*/
template <typename Info> inline exception& set_info(const Info& info)
{
m_infos[std::type_index(typeid(typename Info::tag_type))] =
info.value();
return *this;
}
/**
* @brief Set information associated with exception message.
*
* @tparam exception::message
* @param info info object containing message
* @return @c *this
*/
template <>
exception& set_info<exception::message>(const exception::message& info)
{
m_raw_message = info.value();
return *this;
}
/**
* @brief Retrieve information stored under a tag type.
*
* @tparam Info tag type
* @return the stored value
*/
template <typename Info> inline auto get() const
{
auto it =
m_infos.find(std::type_index(typeid(typename Info::tag_type)));
std::optional<Info::value_type> result;
if (it != m_infos.end()) {
result = std::any_cast<Info::value_type>(it->second);
}
return result;
}
/**
* @brief Get an exception details instance referring to this
* exception.
*
* @return exception details for this exception
*/
exception_details details() const noexcept
{
return exception_details(this);
}
/**
* @brief Set exception information.
* This is same as calling @c set_info.
*
* @tparam T type of appended value, is a @c tag type
* @param value value to set
* @return @c *this
*/
template <class T>
typename std::enable_if<std::is_base_of<tag_base, T>::value,
exception&>::type
operator<<(const T& value)
{
set_info(value);
return *this;
}
/**
* @brief Append value to message.
*
* @tparam T type of appended value
* @param value value to append
* @return @c *this
*/
template <class T>
typename std::enable_if<!std::is_base_of<tag_base, T>::value,
exception&>::type
operator<<(const T& value)
{
if (!m_raw_message_stream) {
m_raw_message_stream = std::make_unique<std::stringstream>();
if (!m_raw_message.empty()) {
(*m_raw_message_stream) << m_raw_message;
m_raw_message.clear();
}
}
(*m_raw_message_stream) << value;
return *this;
}
private:
using exception_info_map = std::map<std::type_index, std::any>;
exception_info_map m_infos;
private:
void copy_message_or_materialize(const exception& e);
void materialize_message() const;
mutable std::unique_ptr<std::stringstream> m_raw_message_stream;
mutable std::string m_raw_message;
};
/**
* @brief Exception cause.
*/
struct exception::cause : public tag<cause, mge::exception>
{
/**
* @brief Capture causing exception.
*
* @param ex causing exception
*/
cause(const mge::exception& ex)
: m_value(ex)
{}
/**
* @brief Capture causing exception.
*
* @param ex causing exception
*/
cause(mge::exception&& ex)
: m_value(std::move(ex))
{}
const mge::exception& value() const noexcept { return m_value; }
mge::exception m_value;
};
/**
* Throw exception instance.
* @param ex exception type
*/
#define MGE_THROW(ex) \
throw(ex().set_info(mge::exception::source_file(__FILE__)) \
.set_info(mge::exception::source_line(__LINE__)) \
.set_info(mge::exception::function(MGE_FUNCTION_SIGNATURE)) \
.set_info(mge::exception::stack(mge::stacktrace())) \
.set_info(mge::exception::type_name(mge::type_name<ex>())))
/**
* Throw exception and adds a cause.
* @param ex exception type
* @param causing_exception exception causing this exception
*/
#define MGE_THROW_WITH_CAUSE(ex, causing_exception) \
throw ex() \
.set_info(mge::exception::source_file(__FILE__)) \
.set_info(mge::exception::source_line(__LINE__)) \
.set_info(mge::exception::function(MGE_FUNCTION_SIGNATURE)) \
.set_info(mge::exception::stack(mge::stacktrace())) \
.set_info(mge::exception::type_name(mge::type_name<ex>())) \
.set_info(mge::exception::cause(causing_exception))
/**
* @def MGE_CALLED_FUNCTION
* @brief Helper to add called function to exception information.
* @param X name of called function
* This helper is usually used to attach additional information
* to the exception, e.g. in case of system or foreign API errors.
* @code
* MGE_THROW(mge::exception) << MGE_CALLED_FUNCTION(fopen);
* @endcode
*/
#define MGE_CALLED_FUNCTION(X) ::mge::exception::called_function(#X)
/**
* @brief Print exception message.
*
* @param os output stream
* @param ex exception
* @return @c os
*/
MGECORE_EXPORT std::ostream& operator<<(std::ostream& os,
const exception& ex);
/**
* @brief Print exception details.
*
* @param os output stream
* @param details wrapped exception
* @return @c os
*/
MGECORE_EXPORT std::ostream&
operator<<(std::ostream& os, const exception::exception_details& details);
/**
* @brief Re-throws the current exception.
*
* This function does not return.
*/
[[noreturn]] inline void rethrow() { throw; }
} // namespace mge | 29.054176 | 80 | 0.515345 | mge-engine |
f449581900d35f80d252e4c6b7048e79b825a99b | 13,114 | cpp | C++ | samples/basic.cpp | fabriquer/lug | 884a58531c359882585084e48625aa688208a7f6 | [
"MIT"
] | 53 | 2017-07-20T10:01:44.000Z | 2022-02-13T04:57:22.000Z | samples/basic.cpp | fabriquer/lug | 884a58531c359882585084e48625aa688208a7f6 | [
"MIT"
] | 4 | 2018-08-31T14:06:50.000Z | 2020-06-17T17:34:20.000Z | samples/basic.cpp | fabriquer/lug | 884a58531c359882585084e48625aa688208a7f6 | [
"MIT"
] | 6 | 2017-07-16T22:54:51.000Z | 2019-12-04T13:15:12.000Z | // lug - Embedded DSL for PE grammar parser combinators in C++
// Copyright (c) 2017 Jesse W. Towner
// See LICENSE.md file for license details
// Derived from BASIC, Dartmouth College Computation Center, October 1st 1964
// http://www.bitsavers.org/pdf/dartmouth/BASIC_Oct64.pdf
#include <lug/lug.hpp>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <iomanip>
#include <map>
#ifdef _MSC_VER
#include <io.h>
#define fileno _fileno
#define isatty _isatty
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#else
#include <unistd.h>
#endif
class basic_interpreter
{
public:
basic_interpreter()
{
using namespace lug::language;
rule Expr;
implicit_space_rule SP = *"[ \t]"_rx;
rule NL = lexeme["\n"_sx | "\r\n" | "\r"];
rule Func = lexeme[capture(id_)["[A-Za-z]"_rx > *"[0-9A-Za-z]"_rx]] <[this]{ return lug::utf8::toupper(*id_); };
rule LineNo = lexeme[capture(sv_)[+"[0-9]"_rx]] <[this]{ return std::stoi(std::string{*sv_}); };
rule Real = lexeme[capture(sv_)[+"[0-9]"_rx > ~("."_sx > +"[0-9]"_rx)
> ~("[Ee]"_rx > ~"[+-]"_rx > +"[0-9]"_rx)]] <[this]{ return std::stod(std::string{*sv_}); };
rule String = lexeme["\"" > capture(sv_)[*"[^\"]"_rx] > "\""] <[this]{ return *sv_; };
rule Var = lexeme[capture(id_)["[A-Za-z]"_rx > ~"[0-9]"_rx]] <[this]{ return lug::utf8::toupper(*id_); };
rule RelOp = "=" <[]() -> RelOpFn { return [](double x, double y) { return x == y; }; }
| ">=" <[]() -> RelOpFn { return std::isgreaterequal; }
| ">" <[]() -> RelOpFn { return std::isgreater; }
| "<=" <[]() -> RelOpFn { return std::islessequal; }
| "<>" <[]() -> RelOpFn { return [](double x, double y) { return x != y; }; }
| "<" <[]() -> RelOpFn { return std::isless; };
rule Ref = id_%Var > "(" > r1_%Expr > ","
> r2_%Expr > ")" <[this]{ return &at(tables_[*id_], *r1_, *r2_); }
| id_%Var > "(" > r1_%Expr > ")" <[this]{ return &at(lists_[*id_], *r1_); }
| id_%Var <[this]{ return &vars_[*id_]; };
rule Value = !("[A-Z][A-Z][A-Z]"_irx > "(")
> ( ref_%Ref <[this]{ return **ref_; }
| Real | "(" > Expr > ")" )
| "SIN"_isx > "(" > r1_%Expr > ")" <[this]{ return std::sin(*r1_); }
| "COS"_isx > "(" > r1_%Expr > ")" <[this]{ return std::cos(*r1_); }
| "TAN"_isx > "(" > r1_%Expr > ")" <[this]{ return std::tan(*r1_); }
| "ATN"_isx > "(" > r1_%Expr > ")" <[this]{ return std::atan(*r1_); }
| "EXP"_isx > "(" > r1_%Expr > ")" <[this]{ return std::exp(*r1_); }
| "ABS"_isx > "(" > r1_%Expr > ")" <[this]{ return std::abs(*r1_); }
| "LOG"_isx > "(" > r1_%Expr > ")" <[this]{ return std::log(*r1_); }
| "SQR"_isx > "(" > r1_%Expr > ")" <[this]{ return std::sqrt(*r1_); }
| "INT"_isx > "(" > r1_%Expr > ")" <[this]{ return std::trunc(*r1_); }
| "RND"_isx > "(" > r1_%Expr > ")" <[this]{ return std::rand() / static_cast<double>(RAND_MAX); };
rule Factor = r1_%Value > ~(u8"[↑^]"_rx > r2_%Value <[this]{ *r1_ = std::pow(*r1_, *r2_); }
) <[this]{ return *r1_; };
rule Term = r1_%Factor > *(
"*"_sx > r2_%Factor <[this]{ *r1_ *= *r2_; }
| "/"_sx > r2_%Factor <[this]{ *r1_ /= *r2_; }
) <[this]{ return *r1_; };
Expr = ( ~ "+"_sx > r1_%Term
| "-"_sx > r1_%Term <[this]{ *r1_ = -*r1_; }
) > *( "+"_sx > r2_%Term <[this]{ *r1_ += *r2_; }
| "-"_sx > r2_%Term <[this]{ *r1_ -= *r2_; }
) <[this]{ return *r1_; };
rule DimEl = id_%Var > "(" > r1_%Expr > ","
> r2_%Expr > ")" <[this]{ dimension(tables_[*id_], *r1_, *r2_); }
| id_%Var > "(" > r1_%Expr > ")" <[this]{ dimension(lists_[*id_], *r1_); };
rule ReadEl = ref_%Ref <[this]{ read(*ref_); };
rule DataEl = r1_%Real <[this]{ data_.push_back(*r1_); };
rule InptEl = ref_%Ref <[this]{ std::cin >> **ref_; };
rule PrntEl = sv_%String <[this]{ std::cout << *sv_; }
| r1_%Expr <[this]{ std::cout << *r1_; };
rule Stmnt = "IF"_isx > r1_%Expr
> rop_%RelOp > r2_%Expr <[this]{ if (!(*rop_)(*r1_, *r2_)) { environment_.escape(); } }
> "THEN"_isx > Stmnt
| "FOR"_isx > id_%Var > "=" > r1_%Expr
> "TO"_isx > r2_%Expr
> ( "STEP"_isx > r3_%Expr
| eps < [this]{ *r3_ = 1.0; } ) <[this]{ for_to_step(*id_, *r1_, *r2_, *r3_); }
| "NEXT"_isx > id_%Var <[this]{ next(*id_); }
| "GOTO"_isx > no_%LineNo <[this]{ goto_line(*no_); }
| "LET"_isx > ref_%Ref > "=" > r1_%Expr <[this]{ **ref_ = *r1_; }
| "DIM"_isx > DimEl > *("," > DimEl)
| "RESTORE"_isx <[this]{ read_itr_ = data_.cbegin(); }
| "READ"_isx > ReadEl > *("," > ReadEl)
| "INPUT"_isx > InptEl > *("," > InptEl)
| "PRINT"_isx > ~PrntEl > *("," > PrntEl) <[this]{ std::cout << std::endl; }
| "GOSUB"_isx > no_%LineNo <[this]{ gosub(*no_); }
| "RETURN"_isx <[this]{ retsub(); }
| "STOP"_isx <[this]{ haltline_ = line_; line_ = lines_.end(); }
| "END"_isx <[this]{ if (line_ == lines_.end()) std::exit(EXIT_SUCCESS); line_ = lines_.end(); }
| ("EXIT"_isx | "QUIT"_isx) <[this]{ std::exit(EXIT_SUCCESS); }
| "REM"_isx > *(!NL > any);
rule Cmnd = "CLEAR"_isx <[this]{ lines_.clear(); }
| "CONT"_isx <[this]{ cont(); }
| "LIST"_isx <[this]{ list(std::cout); }
| "LOAD"_isx > sv_%String <[this]{ load(*sv_); }
| "RUN"_isx <[this]{ line_ = lines_.begin(); read_itr_ = data_.cbegin(); }
| "SAVE"_isx > sv_%String <[this]{ save(*sv_); };
rule Line = Stmnt > NL
| Cmnd > NL
| no_%LineNo > capture(sv_)[*(!NL > any) > NL] <[this]{ update_line(*no_, *sv_); }
| NL
| (*(!NL > any) > NL) <[this]{ print_error("ILLEGAL FORMULA"); }
| !any <[this]{ std::exit(EXIT_SUCCESS); };
grammar_ = start(Line);
}
void repl()
{
lug::parser parser{grammar_, environment_};
parser.push_source([this](std::string& out) {
if (line_ != lines_.end()) {
lastline_ = line_++;
out = lastline_->second;
} else {
if (stdin_tty_)
std::cout << "> " << std::flush;
if (!std::getline(std::cin, out))
return false;
out.push_back('\n');
}
return true;
});
while (parser.parse()) ;
}
void load(std::string_view name)
{
std::ifstream file{filename_with_ext(name), std::ifstream::in};
if (file) {
while (!file.bad() && !file.eof()) {
int lineno;
std::string line;
if (file >> lineno && std::getline(file >> std::ws, line)) {
update_line(lineno, line + "\n");
} else {
file.clear();
file.ignore(std::numeric_limits<std::streamsize>::max(), file.widen('\n'));
}
}
} else {
print_error("FILE DOES NOT EXIST");
}
}
private:
struct List { std::vector<double> values = std::vector<double>(11, 0.0); };
struct Table { std::vector<double> values = std::vector<double>(121, 0.0); std::size_t width = 11, height = 11; };
using RelOpFn = bool(*)(double, double);
std::string filename_with_ext(std::string_view name)
{
std::string filename{name};
if (filename.size() < 4 || strncasecmp(filename.data() + filename.size() - 4, ".BAS", 4) != 0)
filename.append(".BAS");
return filename;
}
void print_error(char const* message)
{
std::cerr << message << "\n";
if (lastline_ != lines_.end())
std::cerr << "LINE " << lastline_->first << ": " << lastline_->second << std::flush;
line_ = lastline_ = lines_.end();
stack_.clear(), for_stack_.clear();
}
void cont()
{
line_ = haltline_;
haltline_ = lines_.end();
if (line_ == haltline_)
print_error("CAN'T CONTINUE");
}
void list(std::ostream& out)
{
for (auto const& [n, l] : lines_)
out << n << "\t" << l;
out << std::flush;
}
void save(std::string_view name)
{
std::ofstream file{filename_with_ext(name), std::ofstream::out};
if (file)
list(file);
else
print_error("UNABLE TO SAVE TO FILE");
}
void update_line(int n, std::string_view s)
{
haltline_ = lines_.end();
if (s.empty() || s.front() < ' ')
lines_.erase(n);
else
lines_[n] = s;
}
bool goto_line(int n)
{
if (lastline_ = line_, line_ = lines_.find(n); line_ == lines_.end()) {
print_error("ILLEGAL LINE NUMBER");
return false;
}
return true;
}
void gosub(int n)
{
lastline_ = line_;
if (goto_line(n))
stack_.push_back(lastline_);
}
void retsub()
{
if (!stack_.empty())
line_ = stack_.back(), stack_.pop_back();
else
print_error("ILLEGAL RETURN");
}
void for_to_step(std::string const& id, double from, double to, double step)
{
if (lastline_ != lines_.end()) {
double& v = vars_[id];
v += step;
if (for_stack_.empty() || id != for_stack_.back().first) {
for_stack_.emplace_back(id, lastline_);
v = from;
}
if ((step >= 0 && v <= to) || (step < 0 && v >= to))
return;
for_stack_.pop_back();
for (auto k = id.size(); line_ != lines_.end(); ++line_) {
auto& t = line_->second;
if (auto n = t.size(); n > 4 && !strncasecmp(t.data(), "NEXT", 4)) {
if (auto i = t.find_first_not_of(" \t", 4); i != std::string::npos &&
i + k <= n && !strncasecmp(t.data() + i, id.data(), k)) {
lastline_ = line_++;
return;
}
}
}
}
print_error("FOR WITHOUT NEXT");
}
void next(std::string const& id)
{
if (lastline_ != lines_.end() && !for_stack_.empty() && for_stack_.back().first == id) {
lastline_ = line_;
line_ = for_stack_.back().second;
} else {
print_error("NOT MATCH WITH FOR");
}
}
void read(double* ref)
{
if (read_itr_ != data_.cend())
*ref = *(read_itr_++);
else
print_error("NO DATA");
}
double& at(List& lst, double i)
{
auto const index = static_cast<std::size_t>(i);
if (index < lst.values.size())
return lst.values[index];
print_error("ARRAY INDEX OUT OF RANGE");
return (invalid_value_ = std::numeric_limits<double>::quiet_NaN());
}
double& at(Table& tab, double i, double j)
{
auto const row = static_cast<std::size_t>(i), col = static_cast<std::size_t>(j);
if (row < tab.height || col < tab.width)
return tab.values[tab.width * row + col];
print_error("ARRAY INDEX OUT OF RANGE");
return (invalid_value_ = std::numeric_limits<double>::quiet_NaN());
}
void dimension(List& lst, double n)
{
if (n < 0.0)
print_error("ARRAY SIZE OUT OF RANGE");
else
lst.values = std::vector<double>(static_cast<std::size_t>(n) + 1, 0.0);
}
void dimension(Table& tab, double m, double n)
{
if (m < 0.0 || n < 0.0) {
print_error("ARRAY SIZE OUT OF RANGE");
} else {
tab.width = static_cast<std::size_t>(m) + 1;
tab.height = static_cast<std::size_t>(n) + 1;
tab.values = std::vector<double>(tab.width * tab.height, 0.0);
}
}
lug::grammar grammar_;
lug::environment environment_;
lug::variable<std::string> id_{environment_};
lug::variable<std::string_view> sv_{environment_};
lug::variable<double> r1_{environment_}, r2_{environment_}, r3_{environment_};
lug::variable<int> no_{environment_};
lug::variable<double*> ref_{environment_};
lug::variable<RelOpFn> rop_{environment_};
std::deque<double> data_;
std::deque<double>::const_iterator read_itr_;
std::unordered_map<std::string, double> vars_;
std::unordered_map<std::string, List> lists_;
std::unordered_map<std::string, Table> tables_;
std::map<int, std::string> lines_;
std::map<int, std::string>::iterator line_{lines_.end()}, lastline_{lines_.end()}, haltline_{lines_.end()};
std::vector<std::map<int, std::string>::iterator> stack_;
std::vector<std::pair<std::string, std::map<int, std::string>::iterator>> for_stack_;
double invalid_value_{std::numeric_limits<double>::quiet_NaN()};
bool const stdin_tty_{isatty(fileno(stdin)) != 0};
};
int main(int argc, char** argv)
{
try {
basic_interpreter interpreter;
while (--argc > 1)
interpreter.load(*++argv);
interpreter.repl();
} catch (std::exception& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
return -1;
}
return 0;
}
| 35.928767 | 133 | 0.516852 | fabriquer |
f44a472e519db1042bf0e7fb53b1234fbd4f778d | 908 | cpp | C++ | src/vjudge/Aizu/1379/24793677_TLE_1098ms_2856kB.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/vjudge/Aizu/1379/24793677_TLE_1098ms_2856kB.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/vjudge/Aizu/1379/24793677_TLE_1098ms_2856kB.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
struct Point {
int x, y;
bool vis;
} a[17];
struct Line {
int x, y;
} ;
int n, ans;
vector<Line > q;
void dfs(int pt) {
if(pt >= n) {
int tmp = 0;
for(auto i = q.begin(); i != q.end(); ++i)
for(auto j = i + 1; j != q.end(); ++j)
if(i->x * j->y == i->y * j->x) ++tmp;
ans = max(ans, tmp);
return ;
}
a[pt].vis = 1;
for(int i = 1; i <= n; ++i) {
if(i == pt) continue;
if(!a[i].vis) {
a[i].vis = 1;
q.push_back((Line){a[i].x - a[pt].x, a[i].y - a[pt].y});
dfs(pt + 1);
q.pop_back();
a[i].vis = 0;
}
}
a[pt].vis = 0;
return ;
}
int main() {
cin >> n;
for(int i = 1; i <= n; ++i)
cin >> a[i].x >> a[i].y;
dfs(1);
cout << ans;
return 0;
} | 18.916667 | 68 | 0.385463 | lnkkerst |
f44ab1aea43bc79fc0c47f9c39d8ad1bb618c21d | 619 | cpp | C++ | examples/CBuilder/Compound/ModelEvolution/Common/dSystemTypeInfo.cpp | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 121 | 2020-09-22T10:46:20.000Z | 2021-11-17T12:33:35.000Z | examples/CBuilder/Compound/ModelEvolution/Common/dSystemTypeInfo.cpp | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 8 | 2020-09-23T12:32:23.000Z | 2021-07-28T07:01:26.000Z | examples/CBuilder/Compound/ModelEvolution/Common/dSystemTypeInfo.cpp | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 42 | 2020-09-22T14:37:20.000Z | 2021-10-04T10:24:12.000Z | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "dSystemTypeInfo.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "BoldHandles"
#pragma link "BoldSubscription"
#pragma resource "*.dfm"
TdmSystemTypeInfo *dmSystemTypeInfo;
//---------------------------------------------------------------------------
__fastcall TdmSystemTypeInfo::TdmSystemTypeInfo(TComponent* Owner)
: TDataModule(Owner)
{
}
//---------------------------------------------------------------------------
| 32.578947 | 77 | 0.390953 | LenakeTech |
f44ad3e847afa0014af02a60083c04175689a6e2 | 1,783 | cpp | C++ | src/pipeline/profile.cpp | seagull1993/librealsense | 18cf36775c16efd1f727b656c7e88a928a53a427 | [
"Apache-2.0"
] | 6,457 | 2016-01-21T03:56:07.000Z | 2022-03-31T11:57:15.000Z | src/pipeline/profile.cpp | seagull1993/librealsense | 18cf36775c16efd1f727b656c7e88a928a53a427 | [
"Apache-2.0"
] | 8,393 | 2016-01-21T09:47:28.000Z | 2022-03-31T22:21:42.000Z | src/pipeline/profile.cpp | seagull1993/librealsense | 18cf36775c16efd1f727b656c7e88a928a53a427 | [
"Apache-2.0"
] | 4,874 | 2016-01-21T09:20:08.000Z | 2022-03-31T15:18:00.000Z | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "profile.h"
#include "media/record/record_device.h"
#include "media/ros/ros_writer.h"
namespace librealsense
{
namespace pipeline
{
profile::profile(std::shared_ptr<device_interface> dev,
util::config config,
const std::string& to_file) :
_dev(dev), _to_file(to_file)
{
if (!to_file.empty())
{
if (!dev)
throw librealsense::invalid_value_exception("Failed to create a profile, device is null");
_dev = std::make_shared<record_device>(dev, std::make_shared<ros_writer>(to_file, dev->compress_while_record()));
}
_multistream = config.resolve(_dev.get());
}
std::shared_ptr<device_interface> profile::get_device()
{
//profile can be retrieved from a pipeline_config and pipeline::start()
//either way, it is created by the pipeline
//TODO: handle case where device has disconnected and reconnected
//TODO: remember to recreate the device as record device in case of to_file.empty() == false
if (!_dev)
{
throw std::runtime_error("Device is unavailable");
}
return _dev;
}
stream_profiles profile::get_active_streams() const
{
auto profiles_per_sensor = _multistream.get_profiles_per_sensor();
stream_profiles profiles;
for (auto&& kvp : profiles_per_sensor)
for (auto&& p : kvp.second)
profiles.push_back(p);
return profiles;
}
}
}
| 33.641509 | 129 | 0.583847 | seagull1993 |
f45212aa6b029307dd24242672315effb4ceb9cc | 2,917 | cc | C++ | ortools/math_opt/samples/integer_programming.cc | bollhals/or-tools | 87cc5a1cb12d901089de0aab55f7ec50bce2cdfd | [
"Apache-2.0"
] | null | null | null | ortools/math_opt/samples/integer_programming.cc | bollhals/or-tools | 87cc5a1cb12d901089de0aab55f7ec50bce2cdfd | [
"Apache-2.0"
] | null | null | null | ortools/math_opt/samples/integer_programming.cc | bollhals/or-tools | 87cc5a1cb12d901089de0aab55f7ec50bce2cdfd | [
"Apache-2.0"
] | null | null | null | // Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Simple integer programming example
#include <iostream>
#include <limits>
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "ortools/base/logging.h"
#include "ortools/math_opt/cpp/math_opt.h"
namespace {
using ::operations_research::math_opt::Model;
using ::operations_research::math_opt::SolveResult;
using ::operations_research::math_opt::SolverType;
using ::operations_research::math_opt::TerminationReason;
using ::operations_research::math_opt::Variable;
using ::operations_research::math_opt::VariableMap;
constexpr double kInf = std::numeric_limits<double>::infinity();
// Model and solve the problem:
// max x + 10 * y
// s.t. x + 7 * y <= 17.5
// x <= 3.5
// x in {0.0, 1.0, 2.0, ...,
// y in {0.0, 1.0, 2.0, ...,
//
void SolveSimpleMIP() {
Model model("Integer programming example");
// Variables
const Variable x = model.AddIntegerVariable(0.0, kInf, "x");
const Variable y = model.AddIntegerVariable(0.0, kInf, "y");
// Constraints
model.AddLinearConstraint(x + 7 * y <= 17.5, "c1");
model.AddLinearConstraint(x <= 3.5, "c2");
// Objective
model.Maximize(x + 10 * y);
std::cout << "Num variables: " << model.num_variables() << std::endl;
std::cout << "Num constraints: " << model.num_linear_constraints()
<< std::endl;
const SolveResult result = Solve(model, SolverType::kGscip).value();
// Check for warnings.
for (const auto& warning : result.warnings) {
LOG(ERROR) << "Solver warning: " << warning << std::endl;
}
// Check that the problem has an optimal solution.
QCHECK_EQ(result.termination.reason, TerminationReason::kOptimal)
<< "Failed to find an optimal solution: " << result.termination;
std::cout << "Problem solved in " << result.solve_time() << std::endl;
std::cout << "Objective value: " << result.objective_value() << std::endl;
const double x_val = result.variable_values().at(x);
const double y_val = result.variable_values().at(y);
std::cout << "Variable values: [x=" << x_val << ", y=" << y_val << "]"
<< std::endl;
}
} // namespace
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
absl::ParseCommandLine(argc, argv);
SolveSimpleMIP();
return 0;
}
| 33.147727 | 76 | 0.675694 | bollhals |
f45239977eb81a0662fa9614d652ad55f0557382 | 5,504 | cpp | C++ | dali-toolkit/internal/image-loader/atlas-packer.cpp | pwisbey/dali-toolkit | aeb2a95e6cb48788c99d0338dd9788c402ebde07 | [
"Apache-2.0"
] | null | null | null | dali-toolkit/internal/image-loader/atlas-packer.cpp | pwisbey/dali-toolkit | aeb2a95e6cb48788c99d0338dd9788c402ebde07 | [
"Apache-2.0"
] | null | null | null | dali-toolkit/internal/image-loader/atlas-packer.cpp | pwisbey/dali-toolkit | aeb2a95e6cb48788c99d0338dd9788c402ebde07 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Samsung Electronics 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.
*
*/
// CLASS HEADER
#include "atlas-packer.h"
// EXTERNAL HEADER
#include <stdlib.h> // For abs()
namespace Dali
{
namespace Toolkit
{
namespace Internal
{
namespace
{
bool ApproximatelyEqual( uint32_t a, uint32_t b )
{
return abs( a-b ) <= 1;
}
}
AtlasPacker::Node::Node( Node* parent, SizeType x, SizeType y, SizeType width, SizeType height )
: rectArea( x, y, width, height ),
parent(parent),
occupied( false )
{
child[0] = NULL;
child[1] = NULL;
}
AtlasPacker:: AtlasPacker( SizeType atlasWidth, SizeType atlasHeight )
: mAvailableArea( atlasWidth * atlasHeight )
{
mRoot = new Node( NULL, 0u, 0u, atlasWidth, atlasHeight );
}
AtlasPacker::~AtlasPacker()
{
DeleteNode( mRoot );
}
bool AtlasPacker::Pack( SizeType blockWidth, SizeType blockHeight,
SizeType& packPositionX, SizeType& packPositionY)
{
Node* firstFit = InsertNode( mRoot, blockWidth, blockHeight );
if( firstFit != NULL )
{
firstFit->occupied = true;
packPositionX = firstFit->rectArea.x;
packPositionY = firstFit->rectArea.y;
mAvailableArea -= blockWidth*blockHeight;
return true;
}
return false;
}
void AtlasPacker::DeleteBlock( SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight )
{
Node* node = SearchNode( mRoot, packPositionX, packPositionY, blockWidth, blockHeight );
if( node != NULL )
{
mAvailableArea += blockWidth*blockHeight;
MergeToNonOccupied( node );
}
}
unsigned int AtlasPacker::GetAvailableArea() const
{
return mAvailableArea;
}
AtlasPacker::Node* AtlasPacker::InsertNode( Node* root, SizeType blockWidth, SizeType blockHeight )
{
if( root == NULL )
{
return NULL;
}
if( root->occupied )
{
// if not the leaf, then try insert into the first child.
Node* newNode = InsertNode(root->child[0], blockWidth, blockHeight);
if( newNode == NULL )// no room, try insert into the second child.
{
newNode = InsertNode(root->child[1], blockWidth, blockHeight);
}
return newNode;
}
// too small, return
if( root->rectArea.width < blockWidth || root->rectArea.height < blockHeight )
{
return NULL;
}
// right size, accept
if( root->rectArea.width == blockWidth && root->rectArea.height == blockHeight )
{
return root;
}
//too much room, need to split
SplitNode( root, blockWidth, blockHeight );
// insert into the first child created.
return InsertNode( root->child[0], blockWidth, blockHeight);
}
void AtlasPacker::SplitNode( Node* node, SizeType blockWidth, SizeType blockHeight )
{
node->occupied = true;
// decide which way to split
SizeType remainingWidth = node->rectArea.width - blockWidth;
SizeType remainingHeight = node->rectArea.height - blockHeight;
if( remainingWidth > remainingHeight ) // split vertically
{
node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, blockWidth, node->rectArea.height );
node->child[1] = new Node( node, node->rectArea.x+blockWidth, node->rectArea.y, node->rectArea.width-blockWidth, node->rectArea.height );
}
else // split horizontally
{
node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, node->rectArea.width, blockHeight );
node->child[1] = new Node( node, node->rectArea.x, node->rectArea.y+blockHeight, node->rectArea.width, node->rectArea.height-blockHeight );
}
}
AtlasPacker::Node* AtlasPacker::SearchNode( Node* node, SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight )
{
if( node != NULL )
{
if( node->child[0] != NULL) //not a leaf
{
Node* newNode = SearchNode(node->child[0], packPositionX, packPositionY, blockWidth, blockHeight);
if( newNode == NULL )// try search from the second child.
{
newNode = SearchNode(node->child[1], packPositionX, packPositionY, blockWidth, blockHeight);
}
return newNode;
}
else if( ApproximatelyEqual(node->rectArea.x, packPositionX) && ApproximatelyEqual(node->rectArea.y, packPositionY )
&& ApproximatelyEqual(node->rectArea.width, blockWidth) && ApproximatelyEqual( node->rectArea.height, blockHeight) )
{
return node;
}
}
return NULL;
}
void AtlasPacker::MergeToNonOccupied( Node* node )
{
node->occupied = false;
Node* parent = node->parent;
// both child are not occupied, merge the space to parent
if( parent != NULL && parent->child[0]->occupied == false && parent->child[1]->occupied == false)
{
delete parent->child[0];
parent->child[0] = NULL;
delete parent->child[1];
parent->child[1] = NULL;
MergeToNonOccupied( parent );
}
}
void AtlasPacker::DeleteNode( Node *node )
{
if( node != NULL )
{
DeleteNode( node->child[0] );
DeleteNode( node->child[1] );
delete node;
}
}
} // namespace Internal
} // namespace Toolkit
} // namespace Dali
| 27.1133 | 148 | 0.683866 | pwisbey |
f453551d908198e43ed5d3dfd77ea364391b5080 | 8,134 | cpp | C++ | AnalyzerExamples/AtmelSWIAnalyzer/AtmelSWIAnalyzer.cpp | blargony/RFFEAnalyzer | 24684cee1494f5ac4bd7d9c9f020f42248a06f89 | [
"MIT"
] | 15 | 2015-06-23T23:28:24.000Z | 2022-03-12T03:23:31.000Z | AnalyzerExamples/AtmelSWIAnalyzer/AtmelSWIAnalyzer.cpp | blargony/RFFEAnalyzer | 24684cee1494f5ac4bd7d9c9f020f42248a06f89 | [
"MIT"
] | 3 | 2015-06-23T23:41:48.000Z | 2022-03-16T22:20:50.000Z | AnalyzerExamples/AtmelSWIAnalyzer/AtmelSWIAnalyzer.cpp | blargony/RFFEAnalyzer | 24684cee1494f5ac4bd7d9c9f020f42248a06f89 | [
"MIT"
] | 3 | 2015-06-23T23:28:30.000Z | 2020-07-30T15:46:04.000Z | #include <AnalyzerChannelData.h>
#include <vector>
#include <algorithm>
#include "AtmelSWIAnalyzer.h"
#include "AtmelSWIAnalyzerSettings.h"
AtmelSWIAnalyzer::AtmelSWIAnalyzer()
: mSimulationInitilized(false)
{
SetAnalyzerSettings(&mSettings);
}
AtmelSWIAnalyzer::~AtmelSWIAnalyzer()
{
KillThread();
}
void AtmelSWIAnalyzer::Setup()
{
// get the channel data pointer
mSDA = GetAnalyzerChannelData(mSettings.mSDAChannel);
}
void AtmelSWIAnalyzer::AddFrame(U64 SampleBegin, U64 SampleEnd, AtmelSWIFrameType FrameType, U64 Data1, U64 Data2)
{
Frame frm;
frm.mFlags = 0;
frm.mStartingSampleInclusive = SampleBegin;
frm.mEndingSampleInclusive = SampleEnd - 1;
frm.mData1 = Data1;
frm.mData2 = Data2;
frm.mType = FrameType;
mResults->AddFrame(frm);
mResults->CommitResults();
}
void AtmelSWIAnalyzer::ResyncToWake(SWI_WaveParser& tokenizer)
{
U64 SampleBegin, SampleEnd;
U8 byte;
bool is_wake;
// just read the raw bytes until GetByteWithExceptions finds a wake token and throws an exception
for (;;)
{
byte = tokenizer.GetByte(SampleBegin, SampleEnd, is_wake);
if (is_wake)
{
AddFrame(SampleBegin, SampleEnd, FrameToken, SWI_Wake);
throw WakeException();
}
AddFrame(SampleBegin, SampleEnd, FrameByte, byte);
}
}
void AtmelSWIAnalyzer::WorkerThread()
{
Setup();
SWI_WaveParser tokenizer(mSDA, GetSampleRate());
Frame frm;
U64 SampleBegin, SampleEnd;
SWI_Token token;
if (mSettings.mDecodeLevel == DL_Tokens)
{
// just read all the tokens
for (;;)
{
token = tokenizer.GetToken(SampleBegin, SampleEnd);
AddFrame(SampleBegin, SampleEnd, FrameToken, token);
}
} else if (mSettings.mDecodeLevel == DL_Bytes) {
// sync to the first wake token
tokenizer.GetWake(SampleBegin, SampleEnd);
AddFrame(SampleBegin, SampleEnd, FrameToken, SWI_Wake);
// now read bytes or wake tokens
bool IsWake;
for (;;)
{
U8 DataByte = tokenizer.GetByte(SampleBegin, SampleEnd, IsWake);
if (IsWake)
AddFrame(SampleBegin, SampleEnd, FrameToken, SWI_Wake);
else
AddFrame(SampleBegin, SampleEnd, FrameByte, DataByte);
}
} else if (mSettings.mDecodeLevel == DL_Packets) {
// sync to the first wake token
tokenizer.GetWake(SampleBegin, SampleEnd);
AddFrame(SampleBegin, SampleEnd, FrameToken, SWI_Wake);
// now read bytes and pack them into Flag frames and I/O blocks
std::vector<std::pair<U64, U64> > ByteSamples;
SWI_Block block;
SWI_Opcode PrevOpcode = SWIO_Undefined;
bool is_wake = false;
U8 byte;
for (;;)
{
try {
// get the flag
U8 Flag = tokenizer.GetByte(SampleBegin, SampleEnd, is_wake);
if (is_wake)
{
AddFrame(SampleBegin, SampleEnd, FrameToken, SWI_Wake);
throw WakeException();
} else if (Flag == SWIF_Command || Flag == SWIF_Transmit || Flag == SWIF_Idle || Flag == SWIF_Sleep) {
AddFrame(SampleBegin, SampleEnd, FrameFlag, Flag, 1);
} else {
// add the error flag
AddFrame(SampleBegin, SampleEnd, FrameFlag, Flag, 0);
ResyncToWake(tokenizer);
}
// read the I/O block after the command or transmit flags
if (Flag == SWIF_Command || Flag == SWIF_Transmit)
{
ByteSamples.clear();
block.Clear();
// set the block opcode
block.IsCommand = (Flag == SWIF_Command);
if (!block.IsCommand)
block.Opcode = PrevOpcode;
// read the block byte count
U8 Count = tokenizer.GetByte(SampleBegin, SampleEnd, is_wake);
if (is_wake)
{
AddFrame(SampleBegin, SampleEnd, FrameToken, SWI_Wake);
throw WakeException();
}
block.Data.push_back(Count);
ByteSamples.push_back(std::make_pair(SampleBegin, SampleEnd));
// we can't have a block without a data packet of at least
// one byte meaning the block has to be at least 4 bytes long
if (Count < 4)
ResyncToWake(tokenizer);
// read the bytes of the IO block
int c;
for (c = 0; c < Count - 1; c++)
{
byte = tokenizer.GetByte(SampleBegin, SampleEnd, is_wake);
if (is_wake && !ByteSamples.empty())
{
// make raw byte frames from the data read so far
std::vector<std::pair<U64, U64> >::const_iterator bs_i(ByteSamples.begin());
std::vector<U8>::const_iterator di(block.Data.begin());
while (bs_i != ByteSamples.end())
{
AddFrame(bs_i->first, bs_i->second, FrameByte, *di);
++di;
++bs_i;
}
// add the wake token
AddFrame(SampleBegin, SampleEnd, FrameToken, SWI_Wake);
throw WakeException();
}
block.Data.push_back(byte);
ByteSamples.push_back(std::make_pair(SampleBegin, SampleEnd));
}
// set the opcode in the block object
if (block.IsCommand)
block.Opcode = static_cast<SWI_Opcode>(block.Data[1]);
// Add the Count frame
AddFrame(ByteSamples.front().first, ByteSamples.front().second, FrameCount, Count);
// add the block to the container
size_t block_ndx = mResults->AddBlock(block);
// parse the packet data
ParsePacket(block, block_ndx, ByteSamples);
// Add the checksum frame
AddFrame((ByteSamples.end() - 2)->first, ByteSamples.back().second,
FrameChecksum,
block.GetChecksum(),
block.CalcCRC());
// remember the command for the next iteration
if (block.IsCommand)
PrevOpcode = block.Opcode;
else
PrevOpcode = SWIO_Undefined;
}
} catch (WakeException&) {
// Just ignore the wake token. The exception thrown on an unexpected
// wake token will only re-sync the parser to the next flag.
}
}
}
}
void AtmelSWIAnalyzer::ParsePacket(const SWI_Block& block, size_t block_ndx, const std::vector<std::pair<U64, U64> >& ByteSamples)
{
const U8 Count = block.GetCount();
// is this a status/response block?
if (Count == 4)
{
// make a status block frame
AddFrame(ByteSamples[1].first, ByteSamples[1].second, FramePacketSegment, 0, 0x100000000ull | (U64)block_ndx);
} else {
int offset = 1; // I/O block offset - we are skipping the Count byte
int param_cnt = 0;
SWI_PacketParam* param;
for (param_cnt = 0; PacketParams[param_cnt].Name != NULL; ++param_cnt)
{
param = PacketParams + param_cnt;
if (param->IsCommand == block.IsCommand && param->ForOpcode == block.Opcode
&& (Count == param->ValidIfCount || param->ValidIfCount == 0))
{
// pack the offset and block index into mData2
U64 data2 = offset;
data2 <<= 32;
data2 |= block_ndx;
AddFrame(ByteSamples[offset].first, ByteSamples[offset + param->Length - 1].second, FramePacketSegment,
param_cnt, data2);
offset += param->Length;
}
param++;
}
}
}
bool AtmelSWIAnalyzer::NeedsRerun()
{
return false;
}
U32 AtmelSWIAnalyzer::GenerateSimulationData(U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels)
{
if (!mSimulationInitilized)
{
mSimulationDataGenerator.Initialize(GetSimulationSampleRate(), &mSettings);
mSimulationInitilized = true;
}
return mSimulationDataGenerator.GenerateSimulationData(minimum_sample_index, device_sample_rate, simulation_channels);
}
U32 AtmelSWIAnalyzer::GetMinimumSampleRateHz()
{
return 4000000; // 4 MHz
}
void AtmelSWIAnalyzer::SetupResults()
{
// reset the results
mResults.reset(new AtmelSWIAnalyzerResults(this, &mSettings));
SetAnalyzerResults(mResults.get());
// set which channels will carry bubbles
mResults->AddChannelBubblesWillAppearOn(mSettings.mSDAChannel);
}
const char* AtmelSWIAnalyzer::GetAnalyzerName() const
{
return ::GetAnalyzerName();
}
const char* GetAnalyzerName()
{
return "Atmel SWI";
}
Analyzer* CreateAnalyzer()
{
return new AtmelSWIAnalyzer();
}
void DestroyAnalyzer(Analyzer* analyzer)
{
delete analyzer;
}
| 26.154341 | 146 | 0.658102 | blargony |
f45448509a0b8e87a7012398a743007c74b9413d | 9,952 | cpp | C++ | src/main.cpp | yafeiwang89/liver2gui | 77c8b0e54a106682fe392e64108402e886440206 | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | yafeiwang89/liver2gui | 77c8b0e54a106682fe392e64108402e886440206 | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | yafeiwang89/liver2gui | 77c8b0e54a106682fe392e64108402e886440206 | [
"BSD-3-Clause"
] | 1 | 2020-06-09T20:16:58.000Z | 2020-06-09T20:16:58.000Z | /*
#############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the ver- #
# sion number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version 1.2.0) [1]. #
# #
# [1] A Ghaffarizadeh, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for #
# Multicellular Systems, PLoS Comput. Biol. 2017 (in revision). #
# preprint DOI: 10.1101/088773 #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite #
# BioFVM as below: #
# #
# We implemented and solved the model using PhysiCell (Version 1.2.0) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for #
# Multicellular Systems, PLoS Comput. Biol. 2017 (in revision). #
# preprint DOI: 10.1101/088773 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient #
# parallelized diffusive transport solver for 3-D biological simulations,#
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
#############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2017, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are #
# met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED #
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A #
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER #
# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, #
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR #
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF #
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING #
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS #
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #
# #
#############################################################################
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <omp.h>
#include <fstream>
#include "./core/PhysiCell.h"
#include "./modules/PhysiCell_standard_modules.h"
// put custom code modules here!
#include "./custom_modules/liver.h"
using namespace BioFVM;
using namespace PhysiCell;
int main( int argc, char* argv[] )
{
// load and parse settings file(s)
bool XML_status = false;
if( argc > 1 )
{ XML_status = load_PhysiCell_config_file( argv[1] ); }
else
{ XML_status = load_PhysiCell_config_file( "./config/PhysiCell_settings.xml" ); }
if( !XML_status )
{ exit(-1); }
// OpenMP setup
omp_set_num_threads(PhysiCell_settings.omp_num_threads);
// PNRG setup
SeedRandom();
// time setup
std::string time_units = "min";
setup_liver();
// some more setup
Cell* pC = create_cell( HCT116 );
pC->assign_position( 0,0,0 );
/* Users typically stop modifying here. END USERMODS */
// set MultiCellDS save options
set_save_biofvm_mesh_as_matlab( true );
set_save_biofvm_data_as_matlab( true );
set_save_biofvm_cell_data( true );
set_save_biofvm_cell_data_as_custom_matlab( true );
// save a simulation snapshot
char filename[1024];
sprintf( filename , "%s/initial" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
// save a quick SVG cross section through z = 0, after setting its
// length bar to 200 microns
PhysiCell_SVG_options.length_bar = 1000;
// for simplicity, set a pathology coloring function
std::vector<std::string> (*cell_coloring_function)(Cell*) = liver_strain_coloring_function; // false_cell_coloring_Ki67;
sprintf( filename , "%s/initial.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
// set the performance timers
BioFVM::RUNTIME_TIC();
BioFVM::TIC();
std::ofstream report_file;
if( PhysiCell_settings.enable_legacy_saves == true )
{
sprintf( filename , "%s/simulation_report.txt" , PhysiCell_settings.folder.c_str() );
report_file.open(filename); // create the data log file
report_file<<"simulated time\tnum cells\tnum division\tnum death\twall time"<<std::endl;
}
// main loop
try
{
while( PhysiCell_globals.current_time < PhysiCell_settings.max_time + 0.1*diffusion_dt )
{
// save data if it's time.
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_full_save_time ) < 0.01 * diffusion_dt )
{
display_simulation_status( std::cout );
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output( PhysiCell_globals.current_time , PhysiCell_globals.full_output_index, microenvironment, report_file);
}
if( PhysiCell_settings.enable_full_saves == true )
{
sprintf( filename , "%s/output%08u" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
}
PhysiCell_globals.full_output_index++;
PhysiCell_globals.next_full_save_time += PhysiCell_settings.full_save_interval;
}
// save SVG plot if it's time
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_SVG_save_time ) < 0.01 * diffusion_dt )
{
if( PhysiCell_settings.enable_SVG_saves == true )
{
sprintf( filename , "%s/snapshot%08u.svg" , PhysiCell_settings.folder.c_str() , PhysiCell_globals.SVG_output_index );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
PhysiCell_globals.SVG_output_index++;
PhysiCell_globals.next_SVG_save_time += PhysiCell_settings.SVG_save_interval;
}
}
// run the liver model
advance_liver_model( diffusion_dt );
// update the microenvironment
microenvironment.simulate_diffusion_decay( diffusion_dt );
// run PhysiCell
((Cell_Container *)microenvironment.agent_container)->update_all_cells( PhysiCell_globals.current_time );
PhysiCell_globals.current_time += diffusion_dt;
}
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output(PhysiCell_globals.current_time, PhysiCell_globals.full_output_index, microenvironment, report_file);
report_file.close();
}
}
catch( const std::exception& e )
{ // reference to the base of a polymorphic object
std::cout << e.what(); // information from length_error printed
}
// save a final simulation snapshot
sprintf( filename , "%s/final" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
sprintf( filename , "%s/final.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
// timer
std::cout << std::endl << "Total simulation runtime: " << std::endl;
BioFVM::display_stopwatch_value( std::cout , BioFVM::runtime_stopwatch_value() );
return 0;
}
| 43.649123 | 123 | 0.58963 | yafeiwang89 |
f45a441e40b04c7a67ee2f8beec28f9650f6f103 | 1,936 | cpp | C++ | inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_transpose.cpp | asenina/openvino | 3790b3506091d132e2bbe491755001b0decc84db | [
"Apache-2.0"
] | null | null | null | inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_transpose.cpp | asenina/openvino | 3790b3506091d132e2bbe491755001b0decc84db | [
"Apache-2.0"
] | null | null | null | inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_transpose.cpp | asenina/openvino | 3790b3506091d132e2bbe491755001b0decc84db | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "vpu/ngraph/transformations/dynamic_to_static_shape_transpose.hpp"
#include "vpu/ngraph/operations/dynamic_shape_resolver.hpp"
#include <vpu/utils/error.hpp>
#include "ngraph/graph_util.hpp"
#include "ngraph/opsets/opset3.hpp"
#include <memory>
namespace vpu {
void dynamicToStaticShapeTranspose(std::shared_ptr<ngraph::Node> target) {
const auto dsr = target->get_argument(0);
VPU_THROW_UNLESS(ngraph::as_type_ptr<ngraph::vpu::op::DynamicShapeResolver>(dsr),
"DynamicToStaticShape transformation for {} of type {} expects {} as input with index {}",
target->get_friendly_name(), target->get_type_info(), ngraph::vpu::op::DynamicShapeResolver::type_info, 0);
const auto transposition = target->get_argument(1);
VPU_THROW_UNLESS(ngraph::as_type_ptr<ngraph::opset3::Constant>(transposition),
"DynamicToStaticShape transformation for {] of type {} expects {} as input with index {}",
target->get_friendly_name(), target->get_type_info(), ngraph::opset3::Constant::type_info, 1);
const auto transpose = std::dynamic_pointer_cast<ngraph::opset3::Transpose>(target);
const auto copied = transpose->copy_with_new_args(target->get_arguments());
const auto shape = dsr->input(1).get_source_output();
const auto axis = std::make_shared<ngraph::opset3::Constant>(
ngraph::element::i64,
ngraph::Shape{std::initializer_list<std::size_t>{1}},
std::vector<std::int64_t>{0});
const auto scatterElementsUpdate = std::make_shared<ngraph::opset3::ScatterElementsUpdate>(shape, transposition, shape, axis);
auto outDSR = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(copied, scatterElementsUpdate);
outDSR->set_friendly_name(transpose->get_friendly_name());
ngraph::replace_node(std::move(target), std::move(outDSR));
}
} // namespace vpu
| 44 | 130 | 0.731405 | asenina |
f45e34ce8c3fbfc160a139ad89bc7ab1f7dd68c5 | 1,044 | cpp | C++ | Source/Runtime/Engine/Private/SceneManager.cpp | blAs1N/BS_Engine | e63be4eaea30c117adfc6fcb7fa2d2e8a57d04b2 | [
"MIT"
] | 8 | 2019-12-05T14:05:21.000Z | 2020-12-16T07:49:22.000Z | Source/Runtime/Engine/Private/SceneManager.cpp | blAs1N/BS_Engine | e63be4eaea30c117adfc6fcb7fa2d2e8a57d04b2 | [
"MIT"
] | 66 | 2019-11-14T10:43:06.000Z | 2021-04-11T04:35:53.000Z | Source/Runtime/Engine/src/SceneManager.cpp | blAs1N/BS-Engine | 2e16a5b136c3065e185c7376f60cff3ab8f393c2 | [
"MIT"
] | 2 | 2019-11-14T13:26:10.000Z | 2020-08-06T04:32:26.000Z | #include "SceneManager.h"
#include "ThreadManager.h"
bool SceneManager::Update(float deltaTime) noexcept
{
if (isSwapScene)
{
isFrontScene = !isFrontScene;
isSwapScene = false;
}
onUpdates[isFrontScene](deltaTime);
return !isEnd;
}
std::future<bool> SceneManager::Load(Name name) noexcept
{
Delegate<bool(void)> load{ [this, name] { return LoadImpl(name); } };
return Accessor<ThreadManager>::GetManager()->AddTask(std::move(load));
}
void SceneManager::RegisterUpdate(const Delegate<void(float)>& callback)
{
std::shared_lock lock{ mutex };
onUpdates[isFrontScene != isLoadScene] += callback;
}
void SceneManager::RegisterUpdate(Delegate<void(float)>&& callback)
{
std::shared_lock lock{ mutex };
onUpdates[isFrontScene != isLoadScene] += std::move(callback);
}
bool SceneManager::LoadImpl(Name name) noexcept
{
mutex.lock();
isLoadScene = true;
mutex.unlock();
const bool isSuccess = scenes[!isFrontScene].Load(name);
mutex.lock();
isLoadScene = false;
isSwapScene = true;
mutex.unlock();
return isSuccess;
}
| 21.306122 | 72 | 0.726054 | blAs1N |
f4629c897f06bdee647dec24d30f7218ba4b14fe | 1,219 | hpp | C++ | valiant/sprite_renderer.hpp | claby2/valiant | d932574fe1f424c444a09ac99ae53fa2c7c4a9ac | [
"MIT"
] | null | null | null | valiant/sprite_renderer.hpp | claby2/valiant | d932574fe1f424c444a09ac99ae53fa2c7c4a9ac | [
"MIT"
] | null | null | null | valiant/sprite_renderer.hpp | claby2/valiant | d932574fe1f424c444a09ac99ae53fa2c7c4a9ac | [
"MIT"
] | null | null | null | #ifndef VALIANT_SPRITE_RENDERER_HPP
#define VALIANT_SPRITE_RENDERER_HPP
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <string>
#include "error.hpp"
namespace valiant {
struct Sprite {
std::string path;
int width{0};
int height{0};
SDL_Surface* surface;
SDL_Texture* texture;
Sprite() : path(""), surface(nullptr), texture(nullptr) {}
Sprite& operator=(const std::string& new_path) {
path = new_path;
surface = IMG_Load(path.c_str());
if (!surface) {
// Error encountered when loading image
throw ValiantError(IMG_GetError());
}
width = surface->w;
height = surface->h;
// Reset texture
texture = nullptr;
return *this;
}
void create_texture(SDL_Renderer* renderer) {
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
}
};
struct SpriteRendererComponent {
Sprite sprite;
bool flip_x{false};
bool flip_y{false};
SpriteRendererComponent() : sprite() {}
};
class SpriteRenderer {
public:
SpriteRendererComponent sprite_renderer;
};
}; // namespace valiant
#endif
| 21.385965 | 66 | 0.64397 | claby2 |
f463b59d45aba293705ee4538fa9c5333e4d5d16 | 836 | hpp | C++ | include/customizer/serialization.hpp | neilbu/osrm-backend | 2a8e1f77459fef33ca34c9fe01ec62e88e255452 | [
"BSD-2-Clause"
] | null | null | null | include/customizer/serialization.hpp | neilbu/osrm-backend | 2a8e1f77459fef33ca34c9fe01ec62e88e255452 | [
"BSD-2-Clause"
] | null | null | null | include/customizer/serialization.hpp | neilbu/osrm-backend | 2a8e1f77459fef33ca34c9fe01ec62e88e255452 | [
"BSD-2-Clause"
] | 1 | 2021-11-24T14:24:44.000Z | 2021-11-24T14:24:44.000Z | #ifndef OSRM_CUSTOMIZER_SERIALIZATION_HPP
#define OSRM_CUSTOMIZER_SERIALIZATION_HPP
#include "partition/cell_storage.hpp"
#include "storage/io.hpp"
#include "storage/serialization.hpp"
#include "storage/shared_memory_ownership.hpp"
namespace osrm
{
namespace customizer
{
namespace serialization
{
template <storage::Ownership Ownership>
inline void read(storage::io::FileReader &reader, detail::CellMetricImpl<Ownership> &metric)
{
storage::serialization::read(reader, metric.weights);
storage::serialization::read(reader, metric.durations);
}
template <storage::Ownership Ownership>
inline void write(storage::io::FileWriter &writer, const detail::CellMetricImpl<Ownership> &metric)
{
storage::serialization::write(writer, metric.weights);
storage::serialization::write(writer, metric.durations);
}
}
}
}
#endif
| 23.885714 | 99 | 0.783493 | neilbu |
f4658709122414d4df7b5c21c1560364298d8a57 | 2,654 | cpp | C++ | 11-stream_file/14-regex.cpp | stevenokm/cpp_tutorial | 0cbc0917bcee8c503a3b9318e945a6ec662ac402 | [
"MIT"
] | 1 | 2021-09-23T00:35:43.000Z | 2021-09-23T00:35:43.000Z | 11-stream_file/14-regex.cpp | stevenokm/cpp_tutorial | 0cbc0917bcee8c503a3b9318e945a6ec662ac402 | [
"MIT"
] | null | null | null | 11-stream_file/14-regex.cpp | stevenokm/cpp_tutorial | 0cbc0917bcee8c503a3b9318e945a6ec662ac402 | [
"MIT"
] | 2 | 2021-08-30T05:34:42.000Z | 2021-09-21T14:11:22.000Z | #include <iostream>
#include <sstream>
#include <string>
#include <regex>
int main()
{
std::string log = R"(
[2021-10-13T14:47:22.050Z] info code-server 3.11.1 acb5de66b71a3f8f1cc065df4633ecd3f9788d46
[2021-10-13T14:47:22.051Z] info Using user-data-dir ~/.local/share/code-server
[2021-10-13T14:47:22.059Z] info Using config file ~/.config/code-server/config.yaml
[2021-10-13T14:47:22.059Z] info HTTP server listening on http://0.0.0.0:8080
[2021-10-13T14:47:22.059Z] info - Authentication is enabled
[2021-10-13T14:47:22.059Z] info - Using password from ~/.config/code-server/config.yaml
[2021-10-13T14:47:22.059Z] info - Not serving HTTPS
[2021-10-13T14:47:22.185Z] error vscode is not running Error: vscode is not running
at VscodeProvider.send (/usr/lib/code-server/out/node/vscode.js:121:19)
at VscodeProvider.sendWebsocket (/usr/lib/code-server/out/node/vscode.js:117:14)
at async /usr/lib/code-server/out/node/routes/vscode.js:205:5
[2021-10-13T14:47:22.435Z] error vscode is not running Error: vscode is not running
at VscodeProvider.send (/usr/lib/code-server/out/node/vscode.js:121:19)
at VscodeProvider.sendWebsocket (/usr/lib/code-server/out/node/vscode.js:117:14)
at async /usr/lib/code-server/out/node/routes/vscode.js:205:5
INFO Detected extension installed from another source ms-python.python
INFO Detected extension installed from another source ms-toolsai.jupyter
[IPC Library: Pty Host] INFO Persistent process "1": Replaying 30070 chars and 1 size events
[node.js fs] readdir with filetypes failed with error: [Error: ENOENT: no such file or directory, scandir '/home/coder/project/upload/210051214'] {
errno: -2,
code: 'ENOENT',
syscall: 'scandir',
path: '/home/coder/project/upload/210051214'
}
[node.js fs] readdir with filetypes failed with error: [Error: ENOENT: no such file or directory, scandir '/home/coder/project/upload/210051214'] {
errno: -2,
code: 'ENOENT',
syscall: 'scandir',
path: '/home/coder/project/upload/210051214'
}
)";
std::stringstream ss;
ss << log;
std::string prefix = R"(^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\])";
std::string level = R"((info|error))";
std::string pattern = prefix + R"(\s+)" + level;
std::regex r(pattern, std::regex_constants::ECMAScript);
std::smatch sm;
while(!ss.eof())
{
std::string line;
std::getline(ss, line);
if(std::regex_search(line, sm, r))
{
std::string msg = sm.suffix();
//std::string keyword;
//std::regex r_key(pattern);
std::cout << msg << '\n';
}
}
return 0;
} | 40.830769 | 148 | 0.677845 | stevenokm |
f4692cadb178355504574ca04a011f5e9b145776 | 12,365 | cpp | C++ | Sources/Internal/UI/UISpinner.cpp | BlitzModder/dava.engine | 0c7a16e627fc0d12309250d6e5e207333b35361e | [
"BSD-3-Clause"
] | 4 | 2019-11-15T11:30:00.000Z | 2021-12-27T21:16:31.000Z | Sources/Internal/UI/UISpinner.cpp | TTopox/dava.engine | 0c7a16e627fc0d12309250d6e5e207333b35361e | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/UI/UISpinner.cpp | TTopox/dava.engine | 0c7a16e627fc0d12309250d6e5e207333b35361e | [
"BSD-3-Clause"
] | 4 | 2017-04-07T04:32:41.000Z | 2021-12-27T21:55:49.000Z | #include "UISpinner.h"
#include "UI/UIEvent.h"
#include "Animation/Animation.h"
#include "Reflection/ReflectionRegistrator.h"
#include "UI/Update/UIUpdateComponent.h"
#include "UI/Render/UIClipContentComponent.h"
namespace DAVA
{
//use these names for children buttons to define UISpinner in .yaml
static const FastName UISPINNER_BUTTON_NEXT_NAME("buttonNext");
static const FastName UISPINNER_BUTTON_PREVIOUS_NAME("buttonPrevious");
static const FastName UISPINNER_CONTENT_NAME("content");
static const float32 UISPINNER_ANIRMATION_TIME = 0.1f;
static const int32 UISPINNER_MOVE_ANIMATION_TRACK = 10;
static const float32 UISPINNER_X_UNDEFINED = 10000;
static const float32 UISPINNER_SLIDE_GESTURE_SPEED = 20.f;
static const float32 UISPINNER_SLIDE_GESTURE_TIME = 0.1f;
DAVA_VIRTUAL_REFLECTION_IMPL(UISpinner)
{
ReflectionRegistrator<UISpinner>::Begin()
.ConstructorByPointer()
.DestructorByPointer([](UISpinner* o) { o->Release(); })
.End();
}
void SpinnerAdapter::AddObserver(SelectionObserver* anObserver)
{
observers.insert(anObserver);
}
void SpinnerAdapter::RemoveObserver(SelectionObserver* anObserver)
{
observers.erase(anObserver);
}
void SpinnerAdapter::NotifyObservers(bool isSelectedFirst, bool isSelectedLast, bool isSelectedChanged)
{
Set<SelectionObserver*>::const_iterator end = observers.end();
for (Set<SelectionObserver*>::iterator it = observers.begin(); it != end; ++it)
{
(*it)->OnSelectedChanged(isSelectedFirst, isSelectedLast, isSelectedChanged);
}
}
bool SpinnerAdapter::Next()
{
bool completedOk = SelectNext();
if (completedOk)
NotifyObservers(false /*as we selected next it can't be first*/, IsSelectedLast(), true);
return completedOk;
}
bool SpinnerAdapter::Previous()
{
bool completedOk = SelectPrevious();
if (completedOk)
NotifyObservers(IsSelectedFirst(), false /*as we selected previous it can't be last*/, true);
return completedOk;
}
void SpinnerAdapter::DisplaySelectedData(UISpinner* spinner)
{
FillScrollableContent(spinner->GetContent(), EIO_CURRENT);
}
UISpinner::UISpinner(const Rect& rect)
: UIControl(rect)
, adapter(nullptr)
, buttonNext(new UIControl())
, buttonPrevious(new UIControl())
, content(new UIControl())
, nextContent(new UIControl())
, contentViewport(new UIControl())
, dragAnchorX(UISPINNER_X_UNDEFINED)
, previousTouchX(UISPINNER_X_UNDEFINED)
, currentTouchX(UISPINNER_X_UNDEFINED)
, totalGestureTime(0)
, totalGestureDx(0)
{
buttonNext->SetName(UISPINNER_BUTTON_NEXT_NAME);
buttonPrevious->SetName(UISPINNER_BUTTON_PREVIOUS_NAME);
content->SetName(UISPINNER_CONTENT_NAME);
AddControl(buttonNext.Get());
AddControl(buttonPrevious.Get());
AddControl(content.Get());
contentViewport->AddControl(nextContent.Get());
contentViewport->SetInputEnabled(false);
contentViewport->GetOrCreateComponent<UIClipContentComponent>();
GetOrCreateComponent<UIUpdateComponent>();
}
UISpinner::~UISpinner()
{
SetAdapter(nullptr);
}
void UISpinner::Update(DAVA::float32 timeElapsed)
{
if (currentTouchX < UISPINNER_X_UNDEFINED)
{
Move move;
move.dx = currentTouchX - previousTouchX;
move.time = timeElapsed;
moves.push_back(move);
totalGestureDx += move.dx;
totalGestureTime += move.time;
if (totalGestureTime > UISPINNER_SLIDE_GESTURE_TIME)
{
List<Move>::iterator it = moves.begin();
totalGestureTime -= it->time;
totalGestureDx -= it->dx;
moves.erase(it);
}
previousTouchX = currentTouchX;
}
}
void UISpinner::Input(UIEvent* currentInput)
{
if (NULL == adapter)
{
return;
}
if (content->IsAnimating(UISPINNER_MOVE_ANIMATION_TRACK))
{
return;
}
Vector2 touchPos = currentInput->point;
if (currentInput->phase == UIEvent::Phase::BEGAN)
{
if (content->IsPointInside(touchPos))
{
content->relativePosition = Vector2();
content->SetPivot(Vector2());
contentViewport->AddControl(content.Get());
AddControl(contentViewport.Get());
dragAnchorX = touchPos.x - content->relativePosition.x;
currentTouchX = touchPos.x;
previousTouchX = currentTouchX;
}
else
{
dragAnchorX = UISPINNER_X_UNDEFINED;
}
}
else if (currentInput->phase == UIEvent::Phase::DRAG)
{
if (dragAnchorX < UISPINNER_X_UNDEFINED)
{
currentTouchX = touchPos.x;
float32 contentNewX = touchPos.x - dragAnchorX;
float32 contentNewLeftEdge = contentNewX - content->GetPivotPoint().x;
if (!(contentNewLeftEdge < 0 && adapter->IsSelectedLast()) && !(contentNewLeftEdge > 0 && adapter->IsSelectedFirst()))
{
if (contentNewX != 0)
{
if (content->relativePosition.x * contentNewX <= 0) //next content just appears or visible side changes
{
//adjust nextContent->pivotPoint to make more convenient setting of nextContent->relativePosition below
Vector2 newPivotPoint = nextContent->GetPivotPoint();
newPivotPoint.x = contentNewX > 0 ? content->size.dx : -content->size.dx;
nextContent->SetPivotPoint(newPivotPoint);
adapter->FillScrollableContent(nextContent.Get(), contentNewX > 0 ? SpinnerAdapter::EIO_PREVIOUS : SpinnerAdapter::EIO_NEXT);
}
}
content->relativePosition.x = contentNewX;
nextContent->relativePosition.x = contentNewX; //for this to work we adjust pivotPoint above
if (Abs(content->relativePosition.x) > content->size.dx / 2)
{
OnSelectWithSlide(content->relativePosition.x > 0);
dragAnchorX = touchPos.x - content->relativePosition.x;
}
}
}
}
else if (currentInput->phase == UIEvent::Phase::ENDED || currentInput->phase == UIEvent::Phase::CANCELLED)
{
if (dragAnchorX < UISPINNER_X_UNDEFINED)
{
if (totalGestureTime > 0)
{
float32 averageSpeed = totalGestureDx / totalGestureTime;
bool selectPrevious = averageSpeed > 0;
if (selectPrevious == content->relativePosition.x > 0) //switch only if selected item is already shifted in slide direction
{
bool isSelectedLast = selectPrevious ? adapter->IsSelectedFirst() : adapter->IsSelectedLast();
if (Abs(averageSpeed) > UISPINNER_SLIDE_GESTURE_SPEED && !isSelectedLast)
{
OnSelectWithSlide(selectPrevious);
}
}
}
Animation* animation = content->PositionAnimation(Vector2(0, content->relativePosition.y), UISPINNER_ANIRMATION_TIME, Interpolation::EASY_IN, UISPINNER_MOVE_ANIMATION_TRACK);
animation->AddEvent(Animation::EVENT_ANIMATION_END, Message(this, &UISpinner::OnScrollAnimationEnd));
nextContent->PositionAnimation(Vector2(0, content->relativePosition.y), UISPINNER_ANIRMATION_TIME, Interpolation::EASY_IN, UISPINNER_MOVE_ANIMATION_TRACK);
currentTouchX = UISPINNER_X_UNDEFINED;
previousTouchX = UISPINNER_X_UNDEFINED;
dragAnchorX = UISPINNER_X_UNDEFINED;
moves.clear();
totalGestureTime = 0;
totalGestureDx = 0;
}
}
currentInput->SetInputHandledType(UIEvent::INPUT_HANDLED_HARD); // Drag is handled - see please DF-2508.
}
void UISpinner::OnSelectWithSlide(bool isPrevious)
{
RefPtr<UIControl> temp = content;
content = nextContent;
nextContent = temp;
//save display position but change pivot points
Vector2 newPivotPoint = nextContent->GetPivotPoint();
newPivotPoint.x -= content->GetPivotPoint().x;
nextContent->SetPivotPoint(newPivotPoint);
nextContent->relativePosition.x -= content->GetPivotPoint().x;
content->relativePosition.x -= content->GetPivotPoint().x;
newPivotPoint = content->GetPivotPoint();
newPivotPoint.x = 0;
content->SetPivotPoint(newPivotPoint);
if (isPrevious)
adapter->Previous();
else
adapter->Next();
}
void UISpinner::OnScrollAnimationEnd(BaseObject* caller, void* param, void* callerData)
{
DVASSERT(NULL != contentViewport->GetParent());
content->SetPivotPoint(contentViewport->GetPivotPoint());
content->relativePosition = contentViewport->relativePosition;
RemoveControl(contentViewport.Get());
AddControl(content.Get());
}
void UISpinner::CopyDataFrom(UIControl* srcControl)
{
UIControl::CopyDataFrom(srcControl);
SetupInternalControls();
UISpinner* src = DynamicTypeCheck<UISpinner*>(srcControl);
SetAdapter(src->GetAdater());
}
UISpinner* UISpinner::Clone()
{
UISpinner* control = new UISpinner(GetRect());
control->CopyDataFrom(this);
return control;
}
void UISpinner::AddControl(UIControl* control)
{
UIControl::AddControl(control);
if (control->GetName() == UISPINNER_BUTTON_NEXT_NAME && control != buttonNext.Get())
{
buttonNext = control;
}
else if (control->GetName() == UISPINNER_BUTTON_PREVIOUS_NAME && control != buttonPrevious.Get())
{
buttonPrevious = control;
}
}
void UISpinner::RemoveControl(UIControl* control)
{
if (control == buttonNext.Get())
{
buttonNext = nullptr;
}
else if (control == buttonPrevious.Get())
{
buttonPrevious = nullptr;
}
UIControl::RemoveControl(control);
}
void UISpinner::LoadFromYamlNodeCompleted()
{
SetupInternalControls();
SetAdapter(nullptr);
}
void UISpinner::SetAdapter(SpinnerAdapter* anAdapter)
{
buttonNext->RemoveEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnNextPressed));
buttonPrevious->RemoveEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnPreviousPressed));
if (adapter)
{
adapter->RemoveObserver(this);
SafeRelease(adapter);
}
adapter = SafeRetain(anAdapter);
if (adapter)
{
adapter->DisplaySelectedData(this);
adapter->AddObserver(this);
buttonNext->AddEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnNextPressed));
buttonPrevious->AddEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnPreviousPressed));
}
buttonNext->SetDisabled(!adapter || adapter->IsSelectedLast());
buttonPrevious->SetDisabled(!adapter || adapter->IsSelectedFirst());
}
void UISpinner::OnNextPressed(DAVA::BaseObject* caller, void* param, void* callerData)
{
if (content->IsAnimating(UISPINNER_MOVE_ANIMATION_TRACK))
{
return;
}
//buttonNext is disabled if we have no adapter or selected adapter element is last, so we don't need checks here
adapter->Next();
}
void UISpinner::OnPreviousPressed(DAVA::BaseObject* caller, void* param, void* callerData)
{
if (content->IsAnimating(UISPINNER_MOVE_ANIMATION_TRACK))
{
return;
}
//buttonPrevious is disabled if we have no adapter or selected adapter element is first, so we don't need checks here
adapter->Previous();
}
void UISpinner::OnSelectedChanged(bool isSelectedFirst, bool isSelectedLast, bool isSelectedChanged)
{
buttonNext->SetDisabled(isSelectedLast);
buttonPrevious->SetDisabled(isSelectedFirst);
if (isSelectedChanged)
{
adapter->DisplaySelectedData(this);
PerformEvent(UIControl::EVENT_VALUE_CHANGED, nullptr);
}
}
void UISpinner::SetupInternalControls()
{
content = FindByName(UISPINNER_CONTENT_NAME, false);
content->SetInputEnabled(false);
contentViewport->SetRect(content->GetRect());
contentViewport->SetPivotPoint(content->GetPivotPoint());
nextContent->CopyDataFrom(content.Get());
nextContent->relativePosition = Vector2();
Vector2 newPivotPoint = nextContent->GetPivotPoint();
newPivotPoint.x = content->size.dx;
nextContent->SetPivotPoint(newPivotPoint);
}
}
| 33.328841 | 186 | 0.671573 | BlitzModder |
f469355b193e56c177df94300d0ce34221270fb3 | 607 | hpp | C++ | cpmf/parallel/switch.hpp | xxthermidorxx/cpmf | 134283d66665a4b5cf2452ded4614ca8b219cfd7 | [
"MIT"
] | 2 | 2015-01-21T01:23:36.000Z | 2016-07-26T16:22:09.000Z | cpmf/parallel/switch.hpp | xxthermidorxx/cpmf | 134283d66665a4b5cf2452ded4614ca8b219cfd7 | [
"MIT"
] | 2 | 2018-11-21T02:46:49.000Z | 2018-12-02T10:53:32.000Z | cpmf/parallel/switch.hpp | xxthermidorxx/cpmf | 134283d66665a4b5cf2452ded4614ca8b219cfd7 | [
"MIT"
] | 1 | 2016-12-11T12:57:49.000Z | 2016-12-11T12:57:49.000Z | #ifndef CPMF_PARALLEL_SWITCH_HPP_
#define CPMF_PARALLEL_SWITCH_HPP_
#include "../common/common.hpp"
#include "../utils/utils.hpp"
#if defined TP_BASED
#include "tp_based/tp_based.hpp"
using namespace cpmf::parallel::tp_based;
#elif defined FPSGD
#include "fpsgd/fpsgd.hpp"
using namespace cpmf::parallel::fpsgd;
#endif
namespace cpmf {
namespace parallel {
void train(const std::shared_ptr<cpmf::common::Matrix> R,
std::shared_ptr<cpmf::common::Model> model,
const cpmf::BaseParams &base_params);
} // namespace parallel
} // namespace cpmf
#endif // CPMF_PARALLEL_SWITCH_HPP_
| 21.678571 | 57 | 0.741351 | xxthermidorxx |
f46ae5658725a597b2bfbe8eecf8d64038a7d3fc | 7,942 | cpp | C++ | src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/culling_of_stratholme/boss_salramm.cpp | mfooo/wow | 3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d | [
"OpenSSL"
] | 1 | 2017-11-16T19:04:07.000Z | 2017-11-16T19:04:07.000Z | src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/culling_of_stratholme/boss_salramm.cpp | mfooo/wow | 3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d | [
"OpenSSL"
] | null | null | null | src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/culling_of_stratholme/boss_salramm.cpp | mfooo/wow | 3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d | [
"OpenSSL"
] | null | null | null | /* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: instance_culling_of_stratholme
SD%Complete: ?%
SDComment: by MaxXx2021
SDCategory: Culling of Stratholme
EndScriptData */
#include "precompiled.h"
#include "def_culling_of_stratholme.h"
enum
{
SAY_SALRAMM_AGGRO = -1594130,
SAY_SALRAMM_DEATH = -1594131,
SAY_SALRAMM_SLAY01 = -1594132,
SAY_SALRAMM_SLAY02 = -1594133,
SAY_SALRAMM_SLAY03 = -1594134,
SAY_SALRAMM_STEAL01 = -1594135,
SAY_SALRAMM_STEAL02 = -1594136,
SAY_SALRAMM_STEAL03 = -1594137,
SAY_SUMMON01 = -1594138,
SAY_SUMMON02 = -1594139,
SAY_BOOM01 = -1594140,
SAY_BOOM02 = -1594141,
SPELL_SB_N = 57725,
SPELL_SB_H = 58827,
SPELL_FLESH = 58845,
SPELL_STEAL = 52708,
SPELL_GNOUL_BLOW = 58825,
SPELL_SUMMON_GNOUL = 52451,
NPC_GNOUL = 27733
};
struct MANGOS_DLL_DECL boss_salrammAI : public ScriptedAI
{
boss_salrammAI(Creature *pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
m_bIsHeroic = pCreature->GetMap()->IsRaidOrHeroicDungeon();
m_creature->SetActiveObjectState(true);
Reset();
}
ScriptedInstance* m_pInstance;
bool m_bIsHeroic;
uint32 ShadowBoltTimer;
uint32 FleshTimer;
uint32 StealTimer;
uint32 SummonTimer;
void Reset()
{
ShadowBoltTimer = 5000;
FleshTimer = (urand(7000, 9000));
StealTimer = (urand(9000, 17000));
SummonTimer = (urand(12000, 17000));
if(m_pInstance)
m_pInstance->SetData64(NPC_SALRAMM, m_creature->GetGUID());
}
void Aggro(Unit* who)
{
DoScriptText(SAY_SALRAMM_AGGRO, m_creature);
}
void JustDied(Unit *killer)
{
DoScriptText(SAY_SALRAMM_DEATH, m_creature);
if(m_pInstance)
m_pInstance->SetData(TYPE_ENCOUNTER, DONE);
}
void KilledUnit(Unit* pVictim)
{
switch(rand()%3)
{
case 0: DoScriptText(SAY_SALRAMM_SLAY01, m_creature); break;
case 1: DoScriptText(SAY_SALRAMM_SLAY02, m_creature); break;
case 2: DoScriptText(SAY_SALRAMM_SLAY03, m_creature); break;
}
}
void SpellHitTarget(Unit *target, const SpellEntry *spell)
{
if(spell->Id == SPELL_GNOUL_BLOW)
if(target->GetTypeId() != TYPEID_PLAYER && target->GetEntry() == NPC_GNOUL)
target->SetDisplayId(11686);
}
void UpdateAI(const uint32 diff)
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
if (ShadowBoltTimer < diff)
{
DoCast(m_creature->getVictim(), m_bIsHeroic ? SPELL_SB_H : SPELL_SB_N);
ShadowBoltTimer = (urand(5000, 6000));
}else ShadowBoltTimer -= diff;
if (FleshTimer < diff)
{
if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM,0))
DoCast(target,SPELL_FLESH);
FleshTimer = 7300;
}else FleshTimer -= diff;
if (StealTimer < diff)
{
if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM,0))
DoCast(target,SPELL_STEAL);
switch(rand()%3)
{
case 0: DoScriptText(SAY_SALRAMM_STEAL01, m_creature); break;
case 1: DoScriptText(SAY_SALRAMM_STEAL02, m_creature); break;
case 2: DoScriptText(SAY_SALRAMM_STEAL03, m_creature); break;
}
StealTimer = (urand(8000, 11000));
}else StealTimer -= diff;
if (SummonTimer < diff)
{
switch(rand()%2)
{
case 0: DoScriptText(SAY_SUMMON01, m_creature); break;
case 1: DoScriptText(SAY_SUMMON02, m_creature); break;
}
m_creature->InterruptNonMeleeSpells(false);
DoCast(m_creature,SPELL_SUMMON_GNOUL);
SummonTimer = (urand(12000, 17000));
}else SummonTimer -= diff;
DoMeleeAttackIfReady();
}
};
/*###
## npc_salramm_gnoul
###*/
struct MANGOS_DLL_DECL npc_salramm_gnoulAI : public ScriptedAI
{
npc_salramm_gnoulAI(Creature *pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
m_bIsHeroic = pCreature->GetMap()->IsRaidOrHeroicDungeon();
m_creature->SetActiveObjectState(true);
Reset();
}
ScriptedInstance* m_pInstance;
bool m_bIsHeroic;
uint32 m_uiBlowTimer;
void Reset()
{
m_uiBlowTimer = (urand(3000, 15000));
}
void MoveInLineOfSight(Unit* pWho)
{
if (!pWho)
return;
if (!m_creature->hasUnitState(UNIT_STAT_STUNNED) && pWho->isTargetableForAttack() &&
m_creature->IsHostileTo(pWho) && pWho->isInAccessablePlaceFor(m_creature))
{
if (!m_creature->CanFly() && m_creature->GetDistanceZ(pWho) > CREATURE_Z_ATTACK_RANGE)
return;
float attackRadius = m_creature->GetAttackDistance(pWho);
if (m_creature->IsWithinDistInMap(pWho, attackRadius) && m_creature->IsWithinLOSInMap(pWho))
{
if (!m_creature->getVictim())
{
AttackStart(pWho);
pWho->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
}
else if (m_creature->GetMap()->IsDungeon())
{
pWho->SetInCombatWith(m_creature);
m_creature->AddThreat(pWho, 0.0f);
}
}
}
}
void UpdateAI(const uint32 uiDiff)
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
if(m_uiBlowTimer < uiDiff)
{
if(Creature* pSalramm = m_pInstance->instance->GetCreature(m_pInstance->GetData64(NPC_SALRAMM)))
{
if(pSalramm->isDead()) return;
switch(rand()%2)
{
case 0: DoScriptText(SAY_BOOM01, pSalramm); break;
case 1: DoScriptText(SAY_BOOM02, pSalramm); break;
}
pSalramm->InterruptNonMeleeSpells(false);
pSalramm->CastSpell(m_creature, SPELL_GNOUL_BLOW, false);
}
}
else m_uiBlowTimer -= uiDiff;
DoMeleeAttackIfReady();
return;
}
};
CreatureAI* GetAI_boss_salramm(Creature* pCreature)
{
return new boss_salrammAI(pCreature);
}
CreatureAI* GetAI_npc_salramm_gnoul(Creature* pCreature)
{
return new npc_salramm_gnoulAI(pCreature);
}
void AddSC_boss_salramm()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_salramm";
newscript->GetAI = &GetAI_boss_salramm;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "npc_salramm_gnoul";
newscript->GetAI = &GetAI_npc_salramm_gnoul;
newscript->RegisterSelf();
}
| 29.634328 | 108 | 0.607152 | mfooo |
c2e1bcc8922079f4325d6d89070c07ce37a42390 | 9,750 | cpp | C++ | vendor/github.com/apple/foundationdb/fdbserver/DatabaseConfiguration.cpp | jukylin/meq | 5a90566b820adc42ef1e390c3f3942eccd77d84a | [
"Apache-2.0"
] | 1 | 2019-10-16T04:00:57.000Z | 2019-10-16T04:00:57.000Z | vendor/github.com/apple/foundationdb/fdbserver/DatabaseConfiguration.cpp | jukylin/meq | 5a90566b820adc42ef1e390c3f3942eccd77d84a | [
"Apache-2.0"
] | null | null | null | vendor/github.com/apple/foundationdb/fdbserver/DatabaseConfiguration.cpp | jukylin/meq | 5a90566b820adc42ef1e390c3f3942eccd77d84a | [
"Apache-2.0"
] | null | null | null | /*
* DatabaseConfiguration.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* 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 "DatabaseConfiguration.h"
#include "fdbclient/SystemData.h"
DatabaseConfiguration::DatabaseConfiguration()
{
resetInternal();
}
void DatabaseConfiguration::resetInternal() {
// does NOT reset rawConfiguration
initialized = false;
masterProxyCount = resolverCount = desiredTLogCount = tLogWriteAntiQuorum = tLogReplicationFactor = durableStorageQuorum = storageTeamSize = -1;
tLogDataStoreType = storageServerStoreType = KeyValueStoreType::END;
autoMasterProxyCount = CLIENT_KNOBS->DEFAULT_AUTO_PROXIES;
autoResolverCount = CLIENT_KNOBS->DEFAULT_AUTO_RESOLVERS;
autoDesiredTLogCount = CLIENT_KNOBS->DEFAULT_AUTO_LOGS;
storagePolicy = IRepPolicyRef();
tLogPolicy = IRepPolicyRef();
}
void parse( int* i, ValueRef const& v ) {
// FIXME: Sanity checking
*i = atoi(v.toString().c_str());
}
void parseReplicationPolicy(IRepPolicyRef* policy, ValueRef const& v) {
BinaryReader reader(v, IncludeVersion());
serializeReplicationPolicy(reader, *policy);
}
void DatabaseConfiguration::setDefaultReplicationPolicy() {
storagePolicy = IRepPolicyRef(new PolicyAcross(storageTeamSize, "zoneid", IRepPolicyRef(new PolicyOne())));
tLogPolicy = IRepPolicyRef(new PolicyAcross(tLogReplicationFactor, "zoneid", IRepPolicyRef(new PolicyOne())));
}
bool DatabaseConfiguration::isValid() const {
return initialized &&
tLogWriteAntiQuorum >= 0 &&
tLogReplicationFactor >= 1 &&
durableStorageQuorum >= 1 &&
storageTeamSize >= 1 &&
getDesiredProxies() >= 1 &&
getDesiredLogs() >= 1 &&
getDesiredResolvers() >= 1 &&
durableStorageQuorum <= storageTeamSize &&
tLogDataStoreType != KeyValueStoreType::END &&
storageServerStoreType != KeyValueStoreType::END &&
autoMasterProxyCount >= 1 &&
autoResolverCount >= 1 &&
autoDesiredTLogCount >= 1 &&
storagePolicy &&
tLogPolicy
;
}
std::map<std::string, std::string> DatabaseConfiguration::toMap() const {
std::map<std::string, std::string> result;
if( initialized ) {
std::string tlogInfo = tLogPolicy->info();
std::string storageInfo = storagePolicy->info();
if( durableStorageQuorum == storageTeamSize &&
tLogWriteAntiQuorum == 0 ) {
if( tLogReplicationFactor == 1 && durableStorageQuorum == 1 )
result["redundancy_mode"] = "single";
else if( tLogReplicationFactor == 2 && durableStorageQuorum == 2 )
result["redundancy_mode"] = "double";
else if( tLogReplicationFactor == 4 && durableStorageQuorum == 6 && tlogInfo == "dcid^2 x zoneid^2 x 1" && storageInfo == "dcid^3 x zoneid^2 x 1" )
result["redundancy_mode"] = "three_datacenter";
else if( tLogReplicationFactor == 3 && durableStorageQuorum == 3 )
result["redundancy_mode"] = "triple";
else if( tLogReplicationFactor == 4 && durableStorageQuorum == 3 && tlogInfo == "data_hall^2 x zoneid^2 x 1" && storageInfo == "data_hall^3 x 1" )
result["redundancy_mode"] = "three_data_hall";
else
result["redundancy_mode"] = "custom";
} else
result["redundancy_mode"] = "custom";
if( tLogDataStoreType == KeyValueStoreType::SSD_BTREE_V1 && storageServerStoreType == KeyValueStoreType::SSD_BTREE_V1)
result["storage_engine"] = "ssd-1";
else if (tLogDataStoreType == KeyValueStoreType::SSD_BTREE_V2 && storageServerStoreType == KeyValueStoreType::SSD_BTREE_V2)
result["storage_engine"] = "ssd-2";
else if( tLogDataStoreType == KeyValueStoreType::MEMORY && storageServerStoreType == KeyValueStoreType::MEMORY )
result["storage_engine"] = "memory";
else
result["storage_engine"] = "custom";
if( desiredTLogCount != -1 )
result["logs"] = format("%d", desiredTLogCount);
if( masterProxyCount != -1 )
result["proxies"] = format("%d", masterProxyCount);
if( resolverCount != -1 )
result["resolvers"] = format("%d", resolverCount);
}
return result;
}
std::string DatabaseConfiguration::toString() const {
std::string result;
std::map<std::string, std::string> config = toMap();
for(auto itr : config) {
result += itr.first + "=" + itr.second;
result += ";";
}
return result.substr(0, result.length()-1);
}
bool DatabaseConfiguration::setInternal(KeyRef key, ValueRef value) {
KeyRef ck = key.removePrefix( configKeysPrefix );
int type;
if (ck == LiteralStringRef("initialized")) initialized = true;
else if (ck == LiteralStringRef("proxies")) parse(&masterProxyCount, value);
else if (ck == LiteralStringRef("resolvers")) parse(&resolverCount, value);
else if (ck == LiteralStringRef("logs")) parse(&desiredTLogCount, value);
else if (ck == LiteralStringRef("log_replicas")) parse(&tLogReplicationFactor, value);
else if (ck == LiteralStringRef("log_anti_quorum")) parse(&tLogWriteAntiQuorum, value);
else if (ck == LiteralStringRef("storage_quorum")) parse(&durableStorageQuorum, value);
else if (ck == LiteralStringRef("storage_replicas")) parse(&storageTeamSize, value);
else if (ck == LiteralStringRef("log_engine")) { parse((&type), value); tLogDataStoreType = (KeyValueStoreType::StoreType)type; }
else if (ck == LiteralStringRef("storage_engine")) { parse((&type), value); storageServerStoreType = (KeyValueStoreType::StoreType)type; }
else if (ck == LiteralStringRef("auto_proxies")) parse(&autoMasterProxyCount, value);
else if (ck == LiteralStringRef("auto_resolvers")) parse(&autoResolverCount, value);
else if (ck == LiteralStringRef("auto_logs")) parse(&autoDesiredTLogCount, value);
else if (ck == LiteralStringRef("storage_replication_policy")) parseReplicationPolicy(&storagePolicy, value);
else if (ck == LiteralStringRef("log_replication_policy")) parseReplicationPolicy(&tLogPolicy, value);
else return false;
return true; // All of the above options currently require recovery to take effect
}
inline static KeyValueRef * lower_bound( VectorRef<KeyValueRef> & config, KeyRef const& key ) {
return std::lower_bound( config.begin(), config.end(), KeyValueRef(key, ValueRef()), KeyValueRef::OrderByKey() );
}
inline static KeyValueRef const* lower_bound( VectorRef<KeyValueRef> const& config, KeyRef const& key ) {
return lower_bound( const_cast<VectorRef<KeyValueRef> &>(config), key );
}
void DatabaseConfiguration::applyMutation( MutationRef m ) {
if( m.type == MutationRef::SetValue && m.param1.startsWith(configKeysPrefix) ) {
set(m.param1, m.param2);
} else if( m.type == MutationRef::ClearRange ) {
KeyRangeRef range(m.param1, m.param2);
if( range.intersects( configKeys ) ) {
clear(range & configKeys);
}
}
}
bool DatabaseConfiguration::set(KeyRef key, ValueRef value) {
makeConfigurationMutable();
mutableConfiguration.get()[ key.toString() ] = value.toString();
return setInternal(key,value);
}
bool DatabaseConfiguration::clear( KeyRangeRef keys ) {
makeConfigurationMutable();
auto& mc = mutableConfiguration.get();
mc.erase( mc.lower_bound( keys.begin.toString() ), mc.lower_bound( keys.end.toString() ) );
// FIXME: More efficient
bool wasValid = isValid();
resetInternal();
for(auto c = mc.begin(); c != mc.end(); ++c)
setInternal(c->first, c->second);
return wasValid && !isValid();
}
Optional<ValueRef> DatabaseConfiguration::get( KeyRef key ) const {
if (mutableConfiguration.present()) {
auto i = mutableConfiguration.get().find(key.toString());
if (i == mutableConfiguration.get().end()) return Optional<ValueRef>();
return ValueRef(i->second);
} else {
auto i = lower_bound(rawConfiguration, key);
if (i == rawConfiguration.end() || i->key != key) return Optional<ValueRef>();
return i->value;
}
}
bool DatabaseConfiguration::isExcludedServer( NetworkAddress a ) const {
return get( encodeExcludedServersKey( AddressExclusion(a.ip, a.port) ) ).present() ||
get( encodeExcludedServersKey( AddressExclusion(a.ip) ) ).present();
}
std::set<AddressExclusion> DatabaseConfiguration::getExcludedServers() const {
const_cast<DatabaseConfiguration*>(this)->makeConfigurationImmutable();
std::set<AddressExclusion> addrs;
for( auto i = lower_bound(rawConfiguration, excludedServersKeys.begin); i != rawConfiguration.end() && i->key < excludedServersKeys.end; ++i ) {
AddressExclusion a = decodeExcludedServersKey( i->key );
if (a.isValid()) addrs.insert(a);
}
return addrs;
}
void DatabaseConfiguration::makeConfigurationMutable() {
if (mutableConfiguration.present()) return;
mutableConfiguration = std::map<std::string,std::string>();
auto& mc = mutableConfiguration.get();
for(auto r = rawConfiguration.begin(); r != rawConfiguration.end(); ++r)
mc[ r->key.toString() ] = r->value.toString();
rawConfiguration = Standalone<VectorRef<KeyValueRef>>();
}
void DatabaseConfiguration::makeConfigurationImmutable() {
if (!mutableConfiguration.present()) return;
auto & mc = mutableConfiguration.get();
rawConfiguration = Standalone<VectorRef<KeyValueRef>>();
rawConfiguration.resize( rawConfiguration.arena(), mc.size() );
int i = 0;
for(auto r = mc.begin(); r != mc.end(); ++r)
rawConfiguration[i++] = KeyValueRef( rawConfiguration.arena(), KeyValueRef( r->first, r->second ) );
mutableConfiguration = Optional<std::map<std::string,std::string>>();
}
| 40.966387 | 150 | 0.728 | jukylin |
c2e241bbc6ad3e6f568c14b33203990cb52cec8b | 2,711 | hpp | C++ | include/qcpc/input/input_utils.hpp | QuarticCat/qc-parser-comb | fd7bbd09233c3f42b23236b242f344ea4d26080e | [
"MIT"
] | 1 | 2021-07-26T03:16:02.000Z | 2021-07-26T03:16:02.000Z | include/qcpc/input/input_utils.hpp | QuarticCat/qc-parser-comb | fd7bbd09233c3f42b23236b242f344ea4d26080e | [
"MIT"
] | null | null | null | include/qcpc/input/input_utils.hpp | QuarticCat/qc-parser-comb | fd7bbd09233c3f42b23236b242f344ea4d26080e | [
"MIT"
] | null | null | null | #pragma once
#include <concepts>
#include <cstddef>
namespace qcpc {
struct InputPos {
const char* current;
size_t line;
size_t column;
};
// TODO: refactor this CRTP
template<class Derived>
struct InputCRTP {
InputCRTP(const char* begin, const char* end) noexcept: _begin(begin), _end(end) {}
InputCRTP(const InputCRTP&) = delete;
InputCRTP(InputCRTP&&) = delete;
InputCRTP& operator=(const InputCRTP&) = delete;
InputCRTP& operator=(InputCRTP&&) = delete;
Derived& operator++() noexcept {
this->_next();
return *static_cast<Derived*>(this);
}
[[nodiscard]] const char& operator*() const noexcept {
return *this->_current;
}
[[nodiscard]] char operator[](size_t n) const noexcept {
return this->_current[n];
}
[[nodiscard]] bool is_boi() const noexcept {
return this->_current == this->_begin;
}
[[nodiscard]] bool is_eoi() const noexcept {
return this->_current == this->_end;
}
[[nodiscard]] const char* begin() const noexcept {
return this->_begin;
}
[[nodiscard]] const char* end() const noexcept {
return this->_end;
}
/// Return number of remaining characters.
[[nodiscard]] size_t size() const noexcept {
return this->_end - this->_current;
}
/// Return current pointer.
[[nodiscard]] const char* current() const noexcept {
return this->_current;
}
/// Return current position.
[[nodiscard]] InputPos pos() const noexcept {
return {this->_current, this->_line, this->_column};
}
/// Return current line.
[[nodiscard]] size_t line() const noexcept {
return this->_line;
}
/// Return current column.
[[nodiscard]] size_t column() const noexcept {
return this->_column;
}
/// Jump to given position. Caller should ensure the correctness of the argument.
void jump(InputPos pos) noexcept {
this->_current = pos.current;
this->_line = pos.line;
this->_column = pos.column;
}
/// Execute self-increment `n` times.
void advance(size_t n) noexcept {
for (size_t i = 0; i < n; ++i) this->_next();
}
protected:
const char* _begin = nullptr;
const char* _end = nullptr;
const char* _current = _begin;
size_t _line = 1;
size_t _column = 0;
InputCRTP() = default;
void _next() noexcept {
if (*this->_current++ == '\n') {
this->_line += 1;
this->_column = 0;
} else {
this->_column += 1;
}
}
};
template<class T>
concept InputType = std::derived_from<T, InputCRTP<T>>;
} // namespace qcpc
| 23.780702 | 87 | 0.593508 | QuarticCat |
c2e4039fb76b757181b5288641d4faf72000d513 | 4,086 | cpp | C++ | UVa 1161 - Objective Berlin/sample/1161 - Objective Berlin.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 1161 - Objective Berlin/sample/1161 - Objective Berlin.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 1161 - Objective Berlin/sample/1161 - Objective Berlin.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <bits/stdc++.h>
using namespace std;
const int MAXV = 40010;
const int MAXE = MAXV * 200 * 2;
const long long LLINF = 1LL<<62;
typedef struct Edge {
int v;
long long cap, flow;
Edge *next, *re;
} Edge;
class MaxFlow {
public:
Edge edge[MAXE], *adj[MAXV], *pre[MAXV], *arc[MAXV];
int e, n, level[MAXV], lvCnt[MAXV], Q[MAXV];
void Init(int x) {
n = x, e = 0;
for (int i = 0; i < n; ++i) adj[i] = NULL;
}
void Addedge(int x, int y, long long flow){
edge[e].v = y, edge[e].cap = flow, edge[e].next = adj[x];
edge[e].re = &edge[e+1], adj[x] = &edge[e++];
edge[e].v = x, edge[e].cap = 0, edge[e].next = adj[y];
edge[e].re = &edge[e-1], adj[y] = &edge[e++];
}
void Bfs(int v){
int front = 0, rear = 0, r = 0, dis = 0;
for (int i = 0; i < n; ++i) level[i] = n, lvCnt[i] = 0;
level[v] = 0, ++lvCnt[0];
Q[rear++] = v;
while (front != rear){
if (front == r) ++dis, r = rear;
v = Q[front++];
for (Edge *i = adj[v]; i != NULL; i = i->next) {
int t = i->v;
if (level[t] == n) level[t] = dis, Q[rear++] = t, ++lvCnt[dis];
}
}
}
long long Maxflow(int s, int t){
long long ret = 0;
int i, j;
Bfs(t);
for (i = 0; i < n; ++i) pre[i] = NULL, arc[i] = adj[i];
for (i = 0; i < e; ++i) edge[i].flow = edge[i].cap;
i = s;
while (level[s] < n){
while (arc[i] && (level[i] != level[arc[i]->v]+1 || !arc[i]->flow))
arc[i] = arc[i]->next;
if (arc[i]){
j = arc[i]->v;
pre[j] = arc[i];
i = j;
if (i == t){
long long update = LLINF;
for (Edge *p = pre[t]; p != NULL; p = pre[p->re->v])
if (update > p->flow) update = p->flow;
ret += update;
for (Edge *p = pre[t]; p != NULL; p = pre[p->re->v])
p->flow -= update, p->re->flow += update;
i = s;
}
}
else{
int depth = n-1;
for (Edge *p = adj[i]; p != NULL; p = p->next)
if (p->flow && depth > level[p->v]) depth = level[p->v];
if (--lvCnt[level[i]] == 0) return ret;
level[i] = depth+1;
++lvCnt[level[i]];
arc[i] = adj[i];
if (i != s) i = pre[i]->re->v;
}
}
return ret;
}
} g;
int mtime(int t) {
return t/100 * 60 + t%100;
}
int main() {
int n, m, ed_t;
char st_s[16], ed_s[16];
while (scanf("%d", &n) == 1) {
scanf("%s %s", st_s, ed_s);
scanf("%d", &ed_t);
ed_t = mtime(ed_t);
scanf("%d", &m);
map<string, int> R;
int I[8192][5];
for (int i = 1, size = 0; i <= m; i++) {
char s1[16], s2[16];
int cap, st, ed;
scanf("%s %s %d %d %d", s1, s2, &cap, &st, &ed);
int &u = R[s1], &v = R[s2];
if (u == 0) u = ++size;
if (v == 0) v = ++size;
I[i][0] = u, I[i][1] = v;
I[i][2] = cap;
I[i][3] = mtime(st);
I[i][4] = mtime(ed);
}
int &st = R[st_s], &ed = R[ed_s];
if (st == 0 || ed == 0) {
puts("0");
continue;
}
g.Init(2+m*2);
int source = 0, sink = 1;
for (int i = 1; i <= m; i++) {
g.Addedge(i*2, i*2+1, I[i][2]);
if (I[i][0] == st)
g.Addedge(source, i*2, LLINF);
if (I[i][1] == ed && I[i][4] <= ed_t)
g.Addedge(i*2+1, sink, LLINF);
for (int j = 1; j <= m; j++) {
if (i == j)
continue;
if (I[i][1] == I[j][0] && I[i][4]+30 <= I[j][3])
g.Addedge(i*2+1, j*2, LLINF);
}
}
int ret = g.Maxflow(source, sink);
printf("%d\n", ret);
}
return 0;
}
/*
4
lisbon
berlin
1500
9
lisbon london 6 1000 1100
london lisbon 6 1130 1230
lisbon paris 5 1000 1100
paris lisbon 4 1130 1230
london paris 1 1130 1300
london berlin 2 1340 1510
berlin london 2 1300 1430
paris berlin 10 1330 1500
berlin paris 9 1300 1430
*/
| 27.422819 | 80 | 0.423642 | tadvi |
c2e62c0276e99b1e6c74d32c45db6ada7e288c98 | 7,191 | cpp | C++ | Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Objects/GameFXCalls.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 231 | 2018-01-28T00:06:56.000Z | 2022-03-31T21:39:56.000Z | Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Objects/GameFXCalls.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 9 | 2016-02-10T10:46:16.000Z | 2017-12-06T17:27:51.000Z | Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Objects/GameFXCalls.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 66 | 2018-01-28T21:54:52.000Z | 2022-02-16T22:50:57.000Z | //
// GameFX Functions called into Basic3D-Integrated-Functions
//
// Includes
#include "CommonC.h"
#include "CObjectsNewC.h"
// Static
DARKSDK void GFCreateNodeTree ( float fX, float fY, float fZ )
{
CreateNodeTree ( fX, fY, fZ );
}
DARKSDK void GFAddNodeTreeObject ( int iID, int iType, int iArbitaryValue, int iCastShadow, int iPortalBlocker )
{
AddNodeTreeObject ( iID, iType, iArbitaryValue, iCastShadow, iPortalBlocker );
}
DARKSDK void GFAddNodeTreeLimb ( int iID, int iLimb, int iType, int iArbitaryValue, int iCastShadow, int iPortalBlocker )
{
AddNodeTreeLimb ( iID, iLimb, iType, iArbitaryValue, iCastShadow, iPortalBlocker );
}
DARKSDK void GFRemoveNodeTreeObject ( int iID )
{
RemoveNodeTreeObject ( iID );
}
DARKSDK void GFDeleteNodeTree ( void )
{
DeleteNodeTree();
}
DARKSDK void GFSetNodeTreeWireframeOn ( void )
{
SetNodeTreeWireframeOn();
}
DARKSDK void GFSetNodeTreeWireframeOff ( void )
{
SetNodeTreeWireframeOff();
}
DARKSDK void GFMakeNodeTreeCollisionBox ( float fX1, float fY1, float fZ1, float fX2, float fY2, float fZ2 )
{
MakeNodeTreeCollisionBox ( fX1, fY1, fZ1, fX2, fY2, fZ2 );
}
DARKSDK void GFSetNodeTreeTextureMode ( int iMode )
{
SetNodeTreeTextureMode ( iMode );
}
DARKSDK void GFDisableNodeTreeOcclusion ( void )
{
DisableNodeTreeOcclusion();
}
DARKSDK void GFEnableNodeTreeOcclusion ( void )
{
EnableNodeTreeOcclusion();
}
DARKSDK void GFSaveNodeTreeObjects ( LPSTR pFilename )
{
SaveNodeTreeObjects ( (DWORD)pFilename );
}
DARKSDK void GFSetNodeTreeEffectTechnique ( LPSTR pFilename )
{
SetNodeTreeEffectTechnique ( (DWORD)pFilename );
}
DARKSDK void GFLoadNodeTreeObjects ( LPSTR pFilename, int iDivideTextureSize )
{
LoadNodeTreeObjects ( (DWORD)pFilename, iDivideTextureSize );
}
DARKSDK void GFAttachObjectToNodeTree ( int iID )
{
AttachObjectToNodeTree ( iID );
}
DARKSDK void GFDetachObjectFromNodeTree ( int iID )
{
DetachObjectFromNodeTree ( iID );
}
DARKSDK void GFSetNodeTreePortalsOn ( void )
{
SetNodeTreePortalsOn();
}
DARKSDK void GFSetNodeTreeCulling ( int iFlag )
{
SetNodeTreeCulling(iFlag);
}
DARKSDK void GFSetNodeTreePortalsOff ( void )
{
SetNodeTreePortalsOff();
}
DARKSDK void GFBuildNodeTreePortals ( void )
{
BuildNodeTreePortals();
}
DARKSDK void GFSetNodeTreeScorchTexture ( int iImageID, int iWidth, int iHeight )
{
SetNodeTreeScorchTexture ( iImageID, iWidth, iHeight );
}
DARKSDK void GFAddNodeTreeScorch ( float fSize, int iType )
{
AddNodeTreeScorch ( fSize, iType );
}
DARKSDK void GFAddNodeTreeLight ( int iLightIndex, float fX, float fY, float fZ, float fRange )
{
AddNodeTreeLight ( iLightIndex, fX, fY, fZ, fRange );
}
// Static Expressions
DARKSDK int GFGetStaticHit ( float fOldX1, float fOldY1, float fOldZ1, float fOldX2, float fOldY2, float fOldZ2, float fNX1, float fNY1, float fNZ1, float fNX2, float fNY2, float fNZ2 )
{
return GetStaticHit ( fOldX1, fOldY1, fOldZ1, fOldX2, fOldY2, fOldZ2, fNX1, fNY1, fNZ1, fNX2, fNY2, fNZ2 );
}
DARKSDK int GFGetStaticLineOfSight ( float fSx, float fSy, float fSz, float fDx, float fDy, float fDz, float fWidth, float fAccuracy )
{
return GetStaticLineOfSight ( fSx, fSy, fSz, fDx, fDy, fDz, fWidth, fAccuracy );
}
DARKSDK int GFGetStaticRayCast ( float fSx, float fSy, float fSz, float fDx, float fDy, float fDz )
{
return GetStaticRayCast ( fSx, fSy, fSz, fDx, fDy, fDz );
}
DARKSDK int GFGetStaticVolumeCast ( float fX, float fY, float fZ, float fNewX, float fNewY, float fNewZ, float fSize )
{
return GetStaticVolumeCast ( fX, fY, fZ, fNewX, fNewY, fNewZ, fSize );
}
DARKSDK DWORD GFGetStaticX ( void )
{
return GetStaticX ( );
}
DARKSDK DWORD GFGetStaticY ( void )
{
return GetStaticY ( );
}
DARKSDK DWORD GFGetStaticZ ( void )
{
return GetStaticZ ( );
}
DARKSDK int GFGetStaticFloor ( void )
{
return GetStaticFloor ( );
}
DARKSDK int GFGetStaticColCount ( void )
{
return GetStaticColCount ( );
}
DARKSDK int GFGetStaticColValue ( void )
{
return GetStaticColValue ( );
}
DARKSDK DWORD GFGetStaticLineOfSightX ( void )
{
return GetStaticLineOfSightX ( );
}
DARKSDK DWORD GFGetStaticLineOfSightY ( void )
{
return GetStaticLineOfSightY ( );
}
DARKSDK DWORD GFGetStaticLineOfSightZ ( void )
{
return GetStaticLineOfSightZ ( );
}
// CSG Commands (CSG)
DARKSDK void GFPeformCSGUnion ( int iObjectA, int iObjectB )
{
PeformCSGUnion ( iObjectA, iObjectB );
}
DARKSDK void GFPeformCSGDifference ( int iObjectA, int iObjectB )
{
PeformCSGDifference ( iObjectA, iObjectB );
}
DARKSDK void GFPeformCSGIntersection ( int iObjectA, int iObjectB )
{
PeformCSGIntersection ( iObjectA, iObjectB );
}
DARKSDK void GFPeformCSGClip ( int iObjectA, int iObjectB )
{
PeformCSGClip ( iObjectA, iObjectB );
}
DARKSDK void GFPeformCSGUnionOnVertexData ( int iBrushMeshID )
{
PeformCSGUnionOnVertexData ( iBrushMeshID );
}
DARKSDK void GFPeformCSGDifferenceOnVertexData ( int iBrushMeshID )
{
PeformCSGDifferenceOnVertexData ( iBrushMeshID );
}
DARKSDK void GFPeformCSGIntersectionOnVertexData ( int iBrushMeshID )
{
PeformCSGIntersectionOnVertexData ( iBrushMeshID );
}
DARKSDK int GFObjectBlocking ( int iID, float X1, float Y1, float Z1, float X2, float Y2, float Z2 )
{
return ObjectBlocking ( iID, X1, Y1, Z1, X2, Y2, Z2 );
}
DARKSDK void GFReduceMesh ( int iMeshID, int iBlockMode, int iNearMode, int iGX, int iGY, int iGZ )
{
ReduceMesh ( iMeshID, iBlockMode, iNearMode, iGX, iGY, iGZ );
}
DARKSDK void GFMakeLODFromMesh ( int iMeshID, int iVertNum, int iNewMeshID )
{
MakeLODFromMesh ( iMeshID, iVertNum, iNewMeshID );
}
// Light Maps
DARKSDK void GFAddObjectToLightMapPool ( int iID )
{
AddObjectToLightMapPool ( iID );
}
DARKSDK void GFAddLimbToLightMapPool ( int iID, int iLimb )
{
AddLimbToLightMapPool ( iID, iLimb );
}
DARKSDK void GFAddStaticObjectsToLightMapPool ( void )
{
AddStaticObjectsToLightMapPool();
}
DARKSDK void GFAddLightMapLight ( float fX, float fY, float fZ, float fRadius, float fRed, float fGreen, float fBlue, float fBrightness, int bCastShadow )
{
AddLightMapLight ( fX, fY, fZ, fRadius, fRed, fGreen, fBlue, fBrightness, bCastShadow );
}
DARKSDK void GFFlushLightMapLights ( void )
{
FlushLightMapLights();
}
DARKSDK void GFCreateLightMaps ( int iLMSize, int iLMQuality, LPSTR dwPathForLightMaps )
{
CreateLightMaps ( iLMSize, iLMQuality, (DWORD)dwPathForLightMaps );
}
// Shadows
DARKSDK void GFSetGlobalShadowsOn ( void )
{
SetGlobalShadowsOn();
}
DARKSDK void GFSetGlobalShadowsOff ( void )
{
SetGlobalShadowsOff();
}
DARKSDK void GFSetShadowPosition ( int iMode, float fX, float fY, float fZ )
{
SetShadowPosition ( iMode, fX, fY, fZ );
}
DARKSDK void GFSetShadowColor ( int iRed, int iGreen, int iBlue, int iAlphaLevel )
{
SetShadowColor ( iRed, iGreen, iBlue, iAlphaLevel );
}
DARKSDK void GFSetShadowShades ( int iShades )
{
SetShadowShades ( iShades );
}
// Others
DARKSDK void GFAddLODToObject ( int iCurrentID, int iLODModelID, int iLODLevel, float fDistanceOfLOD )
{
AddLODToObject ( iCurrentID, iLODModelID, iLODLevel, fDistanceOfLOD );
}
| 23.347403 | 197 | 0.732026 | domydev |
c2e6a8c2a643c3ebaa5a3e859b778c1d15766783 | 1,571 | cpp | C++ | primer/chapter12/ex1.cpp | chenliangold4j/beBetter | e30b66c6c8def4c65e0de9364cd9199558ea3253 | [
"Apache-2.0"
] | null | null | null | primer/chapter12/ex1.cpp | chenliangold4j/beBetter | e30b66c6c8def4c65e0de9364cd9199558ea3253 | [
"Apache-2.0"
] | null | null | null | primer/chapter12/ex1.cpp | chenliangold4j/beBetter | e30b66c6c8def4c65e0de9364cd9199558ea3253 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <memory>
#include <string>
#include <list>
#include <vector>
using namespace std;
class StrBlob
{
public:
typedef vector<string>::size_type size_type;
StrBlob();
StrBlob(initializer_list<string> li);
size_type size() const { return data->size(); }
bool empty() const { return data->empty(); }
void push_back(const string &t) { data->push_back(t); }
void pop_back();
string &front();
string &back();
private:
/* 此类只有一个shared——ptr类型的属性。当 StrBlob发生拷贝,赋值和销毁时。就是将shared_ptr 拷贝赋值销毁。可以自动管理内存*/
shared_ptr<vector<string>> data;
void check(size_type i, const string &msg) const;
};
StrBlob::StrBlob() : data(make_shared<vector<string>>()) {}
StrBlob::StrBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il)) {}
void StrBlob::check(size_type i, const string &msg) const
{
if (i >= data->size())
{
throw out_of_range(msg);
}
}
string& StrBlob::back(){
check(0,"back on empty StrBolb");
return data->back();
}
void StrBlob::pop_back(){
check(0,"pop_back on empty StrBlob");
data->pop_back();
}
string &StrBlob::front(){
check(0,"front on empty StrBolb");
return data->front();
}
int main()
{
// 分享的指针,是一种智能指针。通过引用计数来自动销毁。
shared_ptr<string> p1;
shared_ptr<list<int>> p2;
// 用make_shared函数创建 ,
shared_ptr<int> p3 = make_shared<int>(42);
StrBlob b1;
{
StrBlob b2 = {"a","an","the"};
b1 = b2;
b2.push_back("about");
}
std::cout << b1.size()<< std::endl;
return 0;
}
| 22.126761 | 88 | 0.626989 | chenliangold4j |
c2e8503fb5d9eeb82f0269fff33c4c4f6958c0a2 | 1,666 | cpp | C++ | src/frontend/A64/translate/impl/data_processing_conditional_select.cpp | Esigodini/dynarmic | 664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54 | [
"0BSD"
] | 11 | 2020-05-23T22:12:33.000Z | 2021-06-23T08:11:45.000Z | src/frontend/A64/translate/impl/data_processing_conditional_select.cpp | Esigodini/dynarmic | 664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54 | [
"0BSD"
] | 1 | 2020-05-30T05:01:27.000Z | 2020-05-31T04:46:38.000Z | src/frontend/A64/translate/impl/data_processing_conditional_select.cpp | Esigodini/dynarmic | 664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54 | [
"0BSD"
] | 5 | 2020-05-23T04:10:48.000Z | 2022-03-23T14:58:28.000Z | /* This file is part of the dynarmic project.
* Copyright (c) 2018 MerryMage
* SPDX-License-Identifier: 0BSD
*/
#include "frontend/A64/translate/impl/impl.h"
namespace Dynarmic::A64 {
bool TranslatorVisitor::CSEL(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) {
const size_t datasize = sf ? 64 : 32;
const IR::U32U64 operand1 = X(datasize, Rn);
const IR::U32U64 operand2 = X(datasize, Rm);
const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, operand2);
X(datasize, Rd, result);
return true;
}
bool TranslatorVisitor::CSINC(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) {
const size_t datasize = sf ? 64 : 32;
const IR::U32U64 operand1 = X(datasize, Rn);
const IR::U32U64 operand2 = X(datasize, Rm);
const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, ir.Add(operand2, I(datasize, 1)));
X(datasize, Rd, result);
return true;
}
bool TranslatorVisitor::CSINV(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) {
const size_t datasize = sf ? 64 : 32;
const IR::U32U64 operand1 = X(datasize, Rn);
const IR::U32U64 operand2 = X(datasize, Rm);
const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, ir.Not(operand2));
X(datasize, Rd, result);
return true;
}
bool TranslatorVisitor::CSNEG(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) {
const size_t datasize = sf ? 64 : 32;
const IR::U32U64 operand1 = X(datasize, Rn);
const IR::U32U64 operand2 = X(datasize, Rm);
const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, ir.Add(ir.Not(operand2), I(datasize, 1)));
X(datasize, Rd, result);
return true;
}
} // namespace Dynarmic::A64
| 28.237288 | 109 | 0.668067 | Esigodini |
c2ea500f37bd476a634ce845d45bb46be48aca23 | 6,707 | hpp | C++ | include/ama/tensor/detail/tensor_outer.hpp | mattiapenati/amanita | c5c16d1f17e71151ce1d8e6972ddff6cec3c7305 | [
"BSD-3-Clause"
] | null | null | null | include/ama/tensor/detail/tensor_outer.hpp | mattiapenati/amanita | c5c16d1f17e71151ce1d8e6972ddff6cec3c7305 | [
"BSD-3-Clause"
] | null | null | null | include/ama/tensor/detail/tensor_outer.hpp | mattiapenati/amanita | c5c16d1f17e71151ce1d8e6972ddff6cec3c7305 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2011, Mattia Penati <mattia.penati@gmail.com>
* 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 Politecnico di Milano nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef AMA_TENSOR_DETAIL_TENSOR_OUTER_HPP
#define AMA_TENSOR_DETAIL_TENSOR_OUTER_HPP 1
#include <ama/tensor/detail/tensor_base.hpp>
#include <boost/mpl/advance.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/vector/vector0_c.hpp>
namespace ama
{
namespace tensor_
{
/* forward declaration*/
template <typename LEFT, typename RIGHT> class tensor_outer;
/* traits definition */
template <typename LEFT, typename RIGHT>
struct tensor_traits< tensor_outer<LEFT, RIGHT> >
{
typedef typename LEFT::value_type value_type;
typedef typename LEFT::dimension_type dimension_type;
typedef typename ::boost::mpl::plus<
typename LEFT::controvariant_type
, typename RIGHT::controvariant_type
>::type controvariant_type;
typedef typename ::boost::mpl::plus<
typename LEFT::covariant_type
, typename RIGHT::covariant_type
>::type covariant_type;
typedef ::boost::mpl::false_ is_assignable;
typedef ::boost::mpl::true_ is_temporary;
};
/* class declaration */
template <typename LEFT, typename RIGHT>
class tensor_outer:
public tensor_base< tensor_outer<LEFT, RIGHT> >
{
protected:
typedef tensor_base< tensor_outer<LEFT, RIGHT> > base_type;
typedef tensor_outer<LEFT, RIGHT> derived_type;
protected:
typedef LEFT left_operand_type;
typedef RIGHT right_operand_type;
public:
typedef typename base_type::value_type value_type;
public:
/* costructor */
tensor_outer(left_operand_type const & left,
right_operand_type const & right)
: m_left(left),
m_right(right) { }
public:
/* retrieve the value */
template <typename ILIST>
value_type at() const
{
namespace mpl = ::boost::mpl;
/* iterator */
typedef typename mpl::begin<ILIST>::type begin1;
typedef typename mpl::advance<begin1, typename LEFT::controvariant_type>::type begin2;
typedef typename mpl::advance<begin2, typename RIGHT::controvariant_type>::type begin3;
typedef typename mpl::advance<begin3, typename LEFT::covariant_type>::type begin4;
typedef typename mpl::advance<begin4, typename RIGHT::covariant_type>::type begin5;
typedef typename mpl::end<ILIST>::type end;
/* check for no errors in the code */
BOOST_MPL_ASSERT((mpl::equal_to<mpl::distance<end,begin5>,mpl::size_t<0> >));
/* split multi-index */
typedef typename mpl::fold<
mpl::iterator_range<begin1, begin2>
, mpl::vector0_c<size_t>
, mpl::push_back<mpl::_1, mpl::_2>
>::type controvariant_left;
typedef typename mpl::fold<
mpl::iterator_range<begin2, begin3>
, mpl::vector0_c<size_t>
, mpl::push_back<mpl::_1, mpl::_2>
>::type controvariant_right;
typedef typename mpl::fold<
mpl::iterator_range<begin3, begin4>
, mpl::vector0_c<size_t>
, mpl::push_back<mpl::_1, mpl::_2>
>::type covariant_left;
typedef typename mpl::fold<
mpl::iterator_range<begin4, begin5>
, mpl::vector0_c<size_t>
, mpl::push_back<mpl::_1, mpl::_2>
>::type covariant_right;
/* append the splittend multi-index */
typedef typename mpl::fold<
covariant_left
, controvariant_left
, mpl::push_back<mpl::_1, mpl::_2>
>::type left_ilist;
typedef typename mpl::fold<
covariant_right
, controvariant_right
, mpl::push_back<mpl::_1, mpl::_2>
>::type right_ilist;
return (m_left.template at<left_ilist>()) *
(m_right.template at<right_ilist>());
}
protected:
/* if the operand is temporary we save a copy, otherwise a reference */
typedef typename LEFT::is_temporary left_operand_is_temporary;
typedef typename ::boost::mpl::if_<
left_operand_is_temporary
, left_operand_type const
, left_operand_type const &
>::type const_left_operand_type;
/* if the operand is temporary we save a copy, otherwise a reference */
typedef typename RIGHT::is_temporary right_operand_is_temporary;
typedef typename ::boost::mpl::if_<
right_operand_is_temporary
, right_operand_type const
, right_operand_type const &
>::type const_right_operand_type;
/* members */
const_left_operand_type m_left;
const_right_operand_type m_right;
};
}
}
#endif /* AMA_TENSOR_DETAIL_TENSOR_OUTER_HPP */
| 36.650273 | 95 | 0.653645 | mattiapenati |
c2ec5ef92d269d50cebf881ca7db67a24b57e642 | 4,389 | cpp | C++ | zybo/ROOT_FS/lib/zynqpl/src/pcam/pcam.cpp | meiseihyu/ad-refkit | 69ef3a636326102591294eaabd765b55cab28944 | [
"MIT"
] | 8 | 2020-07-11T08:22:19.000Z | 2022-03-04T09:38:56.000Z | zybo/ROOT_FS/lib/zynqpl/src/pcam/pcam.cpp | meiseihyu/ad-refkit | 69ef3a636326102591294eaabd765b55cab28944 | [
"MIT"
] | 3 | 2020-04-20T14:21:38.000Z | 2020-08-07T03:34:23.000Z | zybo/ROOT_FS/lib/zynqpl/src/pcam/pcam.cpp | meiseihyu/ad-refkit | 69ef3a636326102591294eaabd765b55cab28944 | [
"MIT"
] | 7 | 2020-04-20T07:54:09.000Z | 2021-12-07T11:49:53.000Z | /**
* Pcam: Pcamの初期化・Pcamからの画像取得を行うクラス
*
* Copyright (C) 2019 Yuya Kudo.
*
* Authors:
* Yuya Kudo <ri0049ee@ed.ritsumei.ac.jp>
*/
#include <pcam/pcam.h>
namespace zynqpl {
Pcam::Pcam(const std::string& video_devname,
const std::string& iic_devname,
OV5640_cfg::mode_t mode,
OV5640_cfg::awb_t awb,
uint32_t pixelformat) :
width_(OV5640_cfg::resolutions[mode].width),
height_(OV5640_cfg::resolutions[mode].height) {
psgpio_ = std::make_unique<PSGPIO>();
psiic_ = std::make_unique<PSIIC>(iic_devname, OV5640_cfg::OV5640_SLAVE_ADDR);
reset();
init();
applyMode(mode);
applyAwb(awb);
video_ = std::make_unique<VideoController>(video_devname,
OV5640_cfg::resolutions[mode].width,
OV5640_cfg::resolutions[mode].height,
pixelformat);
}
Pcam::~Pcam() {
shutdown();
}
void Pcam::fetchFrame(uint8_t* frame) const {
auto v4l2_buf = video_->grub();
memcpy(frame, v4l2_buf, video_->buf_size);
video_->release();
}
uint32_t Pcam::getImageWidth() const {
return width_;
}
uint32_t Pcam::getImageHeight() const {
return height_;
}
void Pcam::init() const {
uint8_t id_h, id_l;
readReg(OV5640_cfg::REG_ID_H, id_h);
readReg(OV5640_cfg::REG_ID_H, id_h);
readReg(OV5640_cfg::REG_ID_L, id_l);
if (id_h != OV5640_cfg::DEV_ID_H_ || id_l != OV5640_cfg::DEV_ID_L_) {
char msg[100];
snprintf(msg, sizeof(msg), "Got %02x %02x. Expected %02x %02x\r\n",
id_h, id_l, OV5640_cfg::DEV_ID_H_, OV5640_cfg::DEV_ID_L_);
throw std::runtime_error(std::string(msg));
}
writeReg(0x3103, 0x11);
writeReg(0x3008, 0x82);
usleep(10000);
for(size_t i = 0; i < sizeof(OV5640_cfg::cfg_init_) / sizeof(OV5640_cfg::cfg_init_[0]); ++i) {
writeReg(OV5640_cfg::cfg_init_[i].addr, OV5640_cfg::cfg_init_[i].data);
}
}
void Pcam::shutdown() const {
psgpio_->turnOffPowerToCam();
usleep(10000);
}
void Pcam::reset() const {
psgpio_->turnOffPowerToCam();
usleep(10000);
psgpio_->turnOnPowerToCam();
usleep(10000);
}
void Pcam::applyMode(OV5640_cfg::mode_t mode) const {
if(mode >= OV5640_cfg::mode_t::MODE_END) {
throw std::runtime_error("OV5640 MODE setting is invalid");
}
writeReg(0x3008, 0x42);
const auto cfg_mode = &OV5640_cfg::modes[mode];
writeConfig(cfg_mode->cfg, cfg_mode->cfg_size);
writeReg(0x3008, 0x02);
}
void Pcam::applyAwb(OV5640_cfg::awb_t awb) const {
if(awb >= OV5640_cfg::awb_t::AWB_END) {
throw std::runtime_error("OV5640 AWB setting is invalid");
}
writeReg(0x3008, 0x42);
auto cfg_mode = &OV5640_cfg::awbs[awb];
writeConfig(cfg_mode->cfg, cfg_mode->cfg_size);
writeReg(0x3008, 0x02);
}
void Pcam::readReg(uint16_t reg_addr, uint8_t& buf) const {
buf = psiic_->iicRead(reg_addr);
usleep(10000);
}
void Pcam::writeReg(uint16_t reg_addr, uint8_t const reg_data) const {
auto cnt = 10;
while(true) {
psiic_->iicWrite(reg_addr, reg_data);
usleep(10000);
if(reg_addr == 0x3008) break;
uint8_t buf;
readReg(reg_addr, buf);
if(buf == reg_data) {
std::cout << "[PCam init : Status OK] ";
}
else {
std::cout << "[PCam init : Status NG] ";
}
printf("addr : 0x%04X, write : 0x%02X, read : 0x%02X\n", reg_addr, (int)reg_data, (int)buf);
if(buf == reg_data) break;
cnt--;
if(cnt == 0) {
throw std::runtime_error("process that write to reg by using iic is failure");
}
}
}
void Pcam::writeConfig(OV5640_cfg::config_word_t const* cfg, size_t cfg_size) const {
for(size_t i = 0; i < cfg_size; ++i) {
writeReg(cfg[i].addr, cfg[i].data);
}
}
}
| 30.268966 | 104 | 0.543176 | meiseihyu |
c2ed785f55a7573d277412689f1486f0a280f697 | 2,810 | cpp | C++ | CPPWorkspace/absolutecpp/main.cpp | troyAmlee/udemycpp | 42e1bdb4c29132ec8cac36f3f33d4f6283c5fb32 | [
"MIT"
] | null | null | null | CPPWorkspace/absolutecpp/main.cpp | troyAmlee/udemycpp | 42e1bdb4c29132ec8cac36f3f33d4f6283c5fb32 | [
"MIT"
] | null | null | null | CPPWorkspace/absolutecpp/main.cpp | troyAmlee/udemycpp | 42e1bdb4c29132ec8cac36f3f33d4f6283c5fb32 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int jogger();
double box();
double money();
double feetConversion();
double liquid();
double average();
int main(int argc, char **argv)
{
jogger();
box();
money();
feetConversion();
liquid();
average();
return 0;
}
int jogger(){
int miles;
cout << "Enter number of miles to jog: ";
cin >> miles;
int totalLaps = miles*14;
cout << "You need to jog " << totalLaps << " laps." << endl;
return 0;
}
double box(){
cout << "Welcome to the box calculator" << endl;
cout << "Please enter the dimensions of your box in inches: ";
int length;
int width;
int height;
cin >> length >> width >> height;
double boxArea = 2*(length*width+length*height+width*height);
double boxVolume = length*width*height;
cout << "Box surface area = " << boxArea << " square inches" << endl;
cout << "Box volume = " << boxVolume << " cubic inches" << endl;
return 0;
}
double money(){
cout << "How much change do you have?" << endl;
int quarters;
int dimes;
int nickels;
int pennies;
double totalQuarters;
double totalDimes;
double totalNickels;
double totalPennies;
cout << "Enter number of quarters: ";
cin >> quarters;
cout << "Enter number of dimes: ";
cin >> dimes;
cout << "Enter number of nickels: ";
cin >> nickels;
cout << "Enter number of pennies: ";
cin >> pennies;
totalQuarters = quarters*.25;
totalDimes = dimes*.10;
totalNickels = nickels*.05;
totalPennies = pennies*.01;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
double total = totalQuarters+totalDimes+totalNickels+totalPennies;
cout << quarters << " quarters, "
<< dimes << " dimes, "
<< nickels << " nickels, and "
<< pennies << " pennies = $" << total << endl;
return 0;
}
double feetConversion(){
int feet;
double yards;
double inches;
double centimeters;
double meters;
cout << "Please input number of feet to be converted: ";
cin >> feet;
yards = (feet*12)/36;
inches = feet*12;
centimeters = (feet*12)*2.54;
meters = (feet*12)*(2.54)/(100);
cout << "= " << yards << " yards" << endl
<< "= " << inches << " inches" << endl
<< "= " << centimeters << " centimeters" << endl
<< "= " << meters << " meters" << endl;
return 0;
}
double liquid(){
int ounces;
int leftoverOz;
int maxQuarts;
cout << "Please enter number of ounces: ";
cin >> ounces;
leftoverOz = ounces%32;
maxQuarts = ounces/32;
cout << ounces << " oz. = " << maxQuarts << " qt. "
<< leftoverOz << " oz." << endl;
return 0;
}
double average(){
cout << "Enter the price (x y z): " << endl;
double x;
double y;
double z;
cin >> x >> y >> z;
double sum;
sum = x + y + z;
double average_;
average_ = sum/3.0;
cout << "The average variable = " << average_ << endl;
} | 20.814815 | 70 | 0.619217 | troyAmlee |
c2f1302c71d1da7ca673350db5d7434427e266ba | 605 | cpp | C++ | 1160.cpp | Valarr/Uri | 807de771b14b0e60d44b23835ad9ee7423c83471 | [
"MIT"
] | null | null | null | 1160.cpp | Valarr/Uri | 807de771b14b0e60d44b23835ad9ee7423c83471 | [
"MIT"
] | null | null | null | 1160.cpp | Valarr/Uri | 807de771b14b0e60d44b23835ad9ee7423c83471 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
int numeroDeVezes, i, pa, pb;
double g1, g2;
scanf("%d",&numeroDeVezes);
while (numeroDeVezes){
scanf("%d %d %lf %lf",&pa,&pb,&g1,&g2);
i=0;
g1/=100;
g2/=100;
while(pa<=pb){
i++;
if(i>100){
break;
}
pa+=pa*g1;
pb+=pb*g2;
}
if(i>100){
printf("Mais de 1 seculo.\n");
}
else{
printf("%d anos.\n",i);
}
numeroDeVezes--;
}
return 0;
}
| 18.90625 | 47 | 0.38843 | Valarr |
c2f1870cecc05d2fbfeeabff05d6e14566d90b8d | 3,917 | cpp | C++ | Algorithms on Strings/assignment 3/suffix_tree_from_array/suffix_tree_from_array.cpp | ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization | 27f543ca0778d00ffd624ffcd18bf555660e0168 | [
"MIT"
] | null | null | null | Algorithms on Strings/assignment 3/suffix_tree_from_array/suffix_tree_from_array.cpp | ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization | 27f543ca0778d00ffd624ffcd18bf555660e0168 | [
"MIT"
] | null | null | null | Algorithms on Strings/assignment 3/suffix_tree_from_array/suffix_tree_from_array.cpp | ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization | 27f543ca0778d00ffd624ffcd18bf555660e0168 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <cstdio>
#include <map>
using std::make_pair;
using std::map;
using std::pair;
using std::string;
using std::vector;
using std::stack;
using std::cin;
using std::cout;
using std::endl;
struct suffix_tree_node {
suffix_tree_node* parent{ nullptr };
map<char, suffix_tree_node*> children;
int string_depth{ 0 };
int edge_start{ -1 };
int edge_end{ -1 };
};
suffix_tree_node snodes_buf[400000];
int cur_buf_index = 0;
inline suffix_tree_node* new_tree_node(suffix_tree_node* parent, int depth, int start, int end)
{
snodes_buf[cur_buf_index].parent = parent;
snodes_buf[cur_buf_index].string_depth = depth;
snodes_buf[cur_buf_index].edge_start = start;
snodes_buf[cur_buf_index].edge_end = end;
return &(snodes_buf[cur_buf_index++]);
}
inline suffix_tree_node* create_new_leaf(suffix_tree_node* node, const string& S, int suffix)
{
suffix_tree_node* leaf = new_tree_node(node, S.size() - suffix, suffix + node->string_depth, S.size() - 1);
node->children[S[leaf->edge_start]] = leaf;
return leaf;
}
inline suffix_tree_node* breake_edge(suffix_tree_node* node, const string& S, int start, int offset)
{
char startChar = S[start];
char midChar = S[start + offset];
suffix_tree_node* midNode = new_tree_node(node, node->string_depth + offset, start, start + offset - 1);
midNode->children[midChar] = node->children[startChar];
node->children[startChar]->parent = midNode;
node->children[startChar]->edge_start += offset;
node->children[startChar] = midNode;
return midNode;
}
suffix_tree_node* suffix_tree_from_array(const string& S, const vector<int>& order, const vector<int>& lcp_array)
{
suffix_tree_node* root = new_tree_node(nullptr, 0, -1, -1);
suffix_tree_node* curNode = root;
int lcpPrev = 0;
const int N = S.size();
for (int i = 0; i < N; ++i) {
auto suffix = order[i];
while (curNode->string_depth > lcpPrev) {
curNode = curNode->parent;
}
if (curNode->string_depth == lcpPrev) {
curNode = create_new_leaf(curNode, S, suffix);
}
else {
int edge_start = order[i - 1] + curNode->string_depth;
int offset = lcpPrev - curNode->string_depth;
suffix_tree_node* midNode = breake_edge(curNode, S, edge_start, offset);
curNode = create_new_leaf(midNode, S, suffix);
}
if (i < N - 1) {
lcpPrev = lcp_array[i];
}
}
return root;
}
void recursive_preorder_print(suffix_tree_node* node)
{
cout << node->edge_start << ' ' << node->edge_end + 1 << '\n';
for (auto& next : node->children) {
recursive_preorder_print(next.second);
}
}
void iterative_preorder_print(suffix_tree_node* root)
{
stack<suffix_tree_node*> nodeStack;
for (auto iter = root->children.rbegin(); iter != root->children.rend(); ++iter) {
nodeStack.push(iter->second);
}
while (!nodeStack.empty()) {
suffix_tree_node* node = nodeStack.top();
nodeStack.pop();
cout << node->edge_start << ' ' << node->edge_end + 1 << '\n';
for (auto iter = node->children.rbegin(); iter != node->children.rend(); ++iter) {
nodeStack.push(iter->second);
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
string text;
cin >> text;
vector<int> suffix_array(text.size());
vector<int> lcp_array(text.size() - 1);
for (int j = 0, N = text.size(); j < N; ++j) {
cin >> suffix_array[j];
}
for (int j = 0, N = text.size() - 1; j < N; ++j) {
cin >> lcp_array[j];
}
suffix_tree_node* root = suffix_tree_from_array(text, suffix_array, lcp_array);
cout << text << endl;
iterative_preorder_print(root);
return 0;
} | 26.113333 | 113 | 0.631606 | ChristineHu1207 |
c2f2b011439c92f9dbbea516f41ed755987f2a79 | 6,081 | cpp | C++ | util/Utilities.cpp | traviscross/libzina | 6583baa68549a7d90bf6f9af5836361e41b3cef5 | [
"Apache-2.0"
] | 21 | 2016-04-03T00:05:34.000Z | 2020-05-19T23:08:37.000Z | util/Utilities.cpp | traviscross/libzina | 6583baa68549a7d90bf6f9af5836361e41b3cef5 | [
"Apache-2.0"
] | null | null | null | util/Utilities.cpp | traviscross/libzina | 6583baa68549a7d90bf6f9af5836361e41b3cef5 | [
"Apache-2.0"
] | 4 | 2018-01-15T07:17:27.000Z | 2021-01-10T02:01:37.000Z | /*
Copyright 2016 Silent Circle, 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.
*/
//
// Created by werner on 07.06.16.
//
#include <sys/time.h>
#include <string.h>
#include <time.h>
#include "Utilities.h"
using namespace std;
using namespace zina;
bool Utilities::hasJsonKey(const cJSON* const root, const char* const key) {
if (root == nullptr)
return false;
cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), key);
return jsonItem != nullptr;
}
int32_t Utilities::getJsonInt(const cJSON* const root, const char* const name, int32_t error) {
if (root == nullptr)
return error;
cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name);
if (jsonItem == nullptr)
return error;
return jsonItem->valueint;
}
uint32_t Utilities::getJsonUInt(const cJSON* const root, const char* const name, uint32_t error) {
if (root == nullptr)
return error;
cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name);
if (jsonItem == nullptr)
return error;
if (jsonItem->valuedouble > 0xffffffff)
return 0xffffffff;
if (jsonItem->valuedouble < 0)
return 0;
return (uint32_t)jsonItem->valuedouble;
}
double Utilities::getJsonDouble(const cJSON* const root, const char* const name, double error) {
if (root == nullptr)
return error;
cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name);
if (jsonItem == nullptr)
return error;
return jsonItem->valuedouble;
}
const char *const Utilities::getJsonString(const cJSON* const root, const char* const name, const char *error) {
if (root == nullptr)
return error;
cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name);
if (jsonItem == nullptr)
return error;
return jsonItem->valuestring;
}
void Utilities::setJsonString(cJSON* const root, const char* const name, const char *value, const char *def) {
if (root == nullptr || name == nullptr)
return;
cJSON_AddStringToObject(root, name, value == nullptr ? def : value);
return;
}
bool Utilities::getJsonBool(const cJSON *const root, const char *const name, bool error) {
if (root == nullptr)
return error;
cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name);
if (jsonItem == nullptr)
return error;
if (jsonItem->type == cJSON_True || jsonItem->type == cJSON_False)
return jsonItem->type == cJSON_True;
return error;
}
shared_ptr<vector<string> >
Utilities::splitString(const string& data, const string delimiter)
{
shared_ptr<vector<string> > result = make_shared<vector<string> >();
if (data.empty() || (delimiter.empty() || delimiter.size() > 1)) {
return result;
}
string copy(data);
size_t pos = 0;
while ((pos = copy.find(delimiter)) != string::npos) {
string token = copy.substr(0, pos);
copy.erase(0, pos + 1);
result->push_back(token);
}
if (!copy.empty()) {
result->push_back(copy);
}
size_t idx = result->empty() ? 0: result->size() - 1;
while (idx != 0) {
if (result->at(idx).empty()) {
result->pop_back();
idx--;
}
else
break;
}
return result;
}
string Utilities::currentTimeMsISO8601()
{
char buffer[80];
char outbuf[80];
struct timeval tv;
struct tm timeinfo;
gettimeofday(&tv, NULL);
time_t currentTime = tv.tv_sec;
const char* format = "%FT%T";
strftime(buffer, 80, format ,gmtime_r(¤tTime, &timeinfo));
snprintf(outbuf, 80, "%s.%03dZ\n", buffer, static_cast<int>(tv.tv_usec / 1000));
return string(outbuf);
}
string Utilities::currentTimeISO8601()
{
char outbuf[80];
struct tm timeinfo;
time_t currentTime = time(NULL);
const char* format = "%FT%TZ";
strftime(outbuf, 80, format, gmtime_r(¤tTime, &timeinfo));
return string(outbuf);
}
uint64_t Utilities::currentTimeMillis()
{
struct timeval tv;
gettimeofday(&tv, 0);
uint64_t timeStamp = static_cast<uint64_t>(tv.tv_usec / 1000);
timeStamp += ((uint64_t) tv.tv_sec) * 1000;
return timeStamp;
}
void Utilities::wipeString(string &toWipe)
{
// This append is necessary: the GCC C++ string implementation uses shared strings, reference counted. Thus
// if we set the data buffer to 0 then all other references are also cleared. Appending a blank forces the string
// implementation to really copy the string and we can set the contents to 0. string.clear() does not clear the
// contents, just sets the length to 0 which is not good enough.
toWipe.append(" ");
wipeMemory((void*)toWipe.data(), toWipe.size());
toWipe.clear();
}
static const char decimal2hex[] = "0123456789ABCDEF";
string Utilities::urlEncode(string s)
{
const char *str = s.c_str();
vector<char> v(s.size());
v.clear();
for (size_t i = 0, l = s.size(); i < l; i++)
{
char c = str[i];
if ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '-' || c == '_' || c == '.' || c == '!' || c == '~' ||
c == '*' || c == '\'' || c == '(' || c == ')')
{
v.push_back(c);
}
else
{
v.push_back('%');
char d1 = decimal2hex[c >> 4];
char d2 = decimal2hex[c & 0x0F];
v.push_back(d1);
v.push_back(d2);
}
}
return string(v.cbegin(), v.cend());
}
| 28.549296 | 117 | 0.622102 | traviscross |
c2f2e59572bb049d10474f7bfed6b44408bd936c | 2,362 | cpp | C++ | dev/Basic/long/core/AgentsLookup.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 50 | 2018-12-21T08:21:38.000Z | 2022-01-24T09:47:59.000Z | dev/Basic/long/core/AgentsLookup.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 2 | 2018-12-19T13:42:47.000Z | 2019-05-13T04:11:45.000Z | dev/Basic/long/core/AgentsLookup.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 27 | 2018-11-28T07:30:34.000Z | 2022-02-05T02:22:26.000Z | /*
* Copyright Singapore-MIT Alliance for Research and Technology
*
* File: AgentsLookup.cpp
* Author: Pedro Gandola <pedrogandola@smart.mit.edu>
*
* Created on Feb 18, 2014, 1:32 PM
*/
#include "AgentsLookup.hpp"
using namespace sim_mob;
using namespace sim_mob::long_term;
namespace
{
/**
* Gets object for the given map testing if the key exists or not.
* @param map should be a map like map<K, T*> or map<K, const T*>.
* @param key to search
* @return object pointer or nullptr if key does not exists.
*/
template <typename T, typename M, typename K>
inline const T* getById(const M& map, const K& key)
{
typename M::const_iterator itr = map.find(key);
if (itr != map.end())
{
return (*itr).second;
}
return nullptr;
}
}
AgentsLookup::AgentsLookup() {}
AgentsLookup::~AgentsLookup()
{
reset();
}
void AgentsLookup::reset()
{
householdAgentsById.clear();
developerAgentsById.clear();
realEstateAgentsById.clear();
}
void AgentsLookup::addHouseholdAgent(const HouseholdAgent* agent)
{
if (agent && !getById<HouseholdAgent>(householdAgentsById, agent->GetId()))
{
householdAgentsById.insert(std::make_pair(agent->GetId(), agent));
}
}
void AgentsLookup::addDeveloperAgent(const DeveloperAgent* agent)
{
if (agent && !getById<DeveloperAgent>(developerAgentsById, agent->GetId()))
{
developerAgentsById.insert(std::make_pair(agent->GetId(), agent));
}
}
void AgentsLookup::addRealEstateAgent(const RealEstateAgent* agent)
{
if (agent && !getById<RealEstateAgent>(realEstateAgentsById, agent->GetId()))
{
realEstateAgentsById.insert(std::make_pair(agent->GetId(), agent));
}
}
const HouseholdAgent* AgentsLookup::getHouseholdAgentById(const BigSerial id) const
{
return getById<HouseholdAgent>(householdAgentsById, id);
}
const DeveloperAgent* AgentsLookup::getDeveloperAgentById(const BigSerial id) const
{
return getById<DeveloperAgent>(developerAgentsById, id);
}
const RealEstateAgent* AgentsLookup::getRealEstateAgentById(const BigSerial id) const
{
return getById<RealEstateAgent>(realEstateAgentsById, id);
}
LoggerAgent& AgentsLookup::getLogger()
{
return logger;
}
EventsInjector& AgentsLookup::getEventsInjector()
{
return injector;
}
| 24.350515 | 85 | 0.692633 | gusugusu1018 |
c2f39a09453322cc3ba48b9a2125b9c5fb169a50 | 2,672 | ipp | C++ | Siv3D/include/Siv3D/detail/MemoryViewReader.ipp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 2 | 2021-11-22T00:52:48.000Z | 2021-12-24T09:33:55.000Z | Siv3D/include/Siv3D/detail/MemoryViewReader.ipp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 32 | 2021-10-09T10:04:11.000Z | 2022-02-25T06:10:13.000Z | Siv3D/include/Siv3D/detail/MemoryViewReader.ipp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 1 | 2021-12-31T05:08:00.000Z | 2021-12-31T05:08:00.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
namespace s3d
{
inline constexpr MemoryViewReader::MemoryViewReader(const void* data, const size_t size_bytes) noexcept
: m_size{ static_cast<int64>(size_bytes) }
, m_ptr{ static_cast<const Byte*>(data) } {}
inline bool MemoryViewReader::supportsLookahead() const noexcept
{
return true;
}
inline bool MemoryViewReader::isOpen() const noexcept
{
return (m_ptr != nullptr);
}
inline int64 MemoryViewReader::size() const
{
return m_size;
}
inline int64 MemoryViewReader::getPos() const
{
return m_pos;
}
inline bool MemoryViewReader::setPos(const int64 pos)
{
if (not InRange<int64>(pos, 0, m_size))
{
return false;
}
m_pos = pos;
return true;
}
inline int64 MemoryViewReader::skip(const int64 offset)
{
m_pos = Clamp<int64>((m_pos + offset), 0, m_size);
return m_pos;
}
inline int64 MemoryViewReader::read(void* dst, const int64 size)
{
if (not dst)
{
return 0;
}
const int64 readSize = Clamp<int64>(size, 0, m_size - m_pos);
std::memcpy(dst, (m_ptr + m_pos), static_cast<size_t>(readSize));
m_pos += readSize;
return readSize;
}
inline int64 MemoryViewReader::read(void* dst, const int64 pos, const int64 size)
{
if (not dst)
{
return 0;
}
const int64 readSize = Clamp<int64>(size, 0, m_size - pos);
std::memcpy(dst, (m_ptr + pos), static_cast<size_t>(readSize));
m_pos = pos + readSize;
return readSize;
}
SIV3D_CONCEPT_TRIVIALLY_COPYABLE_
inline bool MemoryViewReader::read(TriviallyCopyable& dst)
{
return read(std::addressof(dst), sizeof(TriviallyCopyable)) == sizeof(TriviallyCopyable);
}
inline int64 MemoryViewReader::lookahead(void* dst, const int64 size) const
{
if (not dst)
{
return 0;
}
const int64 readSize = Clamp<int64>(size, 0, m_size - m_pos);
std::memcpy(dst, (m_ptr + m_pos), static_cast<size_t>(readSize));
return readSize;
}
inline int64 MemoryViewReader::lookahead(void* dst, const int64 pos, const int64 size) const
{
if (not dst)
{
return 0;
}
const int64 readSize = Clamp<int64>(size, 0, m_size - pos);
std::memcpy(dst, (m_ptr + m_pos), static_cast<size_t>(readSize));
return readSize;
}
SIV3D_CONCEPT_TRIVIALLY_COPYABLE_
inline bool MemoryViewReader::lookahead(TriviallyCopyable& dst) const
{
return lookahead(std::addressof(dst), sizeof(TriviallyCopyable)) == sizeof(TriviallyCopyable);
}
}
| 20.396947 | 104 | 0.668787 | tas9n |
c2feba820ed892f091589fae81d7ec042e8153c4 | 375 | cpp | C++ | ModernC++/3.2/funcs.cpp | Fernal73/LearnCpp | 100aa80e447fe7735d7f8217c2ec72ae32ed1c7f | [
"MIT"
] | null | null | null | ModernC++/3.2/funcs.cpp | Fernal73/LearnCpp | 100aa80e447fe7735d7f8217c2ec72ae32ed1c7f | [
"MIT"
] | null | null | null | ModernC++/3.2/funcs.cpp | Fernal73/LearnCpp | 100aa80e447fe7735d7f8217c2ec72ae32ed1c7f | [
"MIT"
] | null | null | null | #include <functional>
#include <iostream>
using namespace std;
int foo(int para) {
return para;
}
int main() {
// function wraps a function that take int paremeter and returns int value
function<int(int)> func = foo;
int important = 10;
function<int(int)> func2 = [&](int value) -> int {
return 1+value+important;
};
cout << func(10) << endl;
cout << func2(10) << endl;
}
| 18.75 | 74 | 0.677333 | Fernal73 |
c2ffeeb32f64d2f1a504fc5e2cf3297a4e69adab | 7,928 | cpp | C++ | mmcv/ops/csrc/parrots/corner_pool_parrots.cpp | Alsasolo/mmcv | 6dfc9312fa872c7fd63a5e6971e9ecca8e3d4ef1 | [
"Apache-2.0"
] | 3 | 2019-04-25T04:53:03.000Z | 2020-05-08T07:48:34.000Z | mmcv/ops/csrc/parrots/corner_pool_parrots.cpp | Alsasolo/mmcv | 6dfc9312fa872c7fd63a5e6971e9ecca8e3d4ef1 | [
"Apache-2.0"
] | 10 | 2020-10-15T19:31:38.000Z | 2021-03-21T16:16:28.000Z | mmcv/ops/csrc/parrots/corner_pool_parrots.cpp | Alsasolo/mmcv | 6dfc9312fa872c7fd63a5e6971e9ecca8e3d4ef1 | [
"Apache-2.0"
] | 1 | 2022-01-09T15:30:55.000Z | 2022-01-09T15:30:55.000Z | #include <parrots/compute/aten.hpp>
#include <parrots/extension.hpp>
#include <parrots/foundation/ssattrs.hpp>
#include "corner_pool_pytorch.h"
using namespace parrots;
#ifdef MMCV_WITH_CUDA
void bottom_pool_forward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = bottom_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void bottom_pool_backward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = bottom_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
void left_pool_forward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = left_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void left_pool_backward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = left_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
void right_pool_forward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = right_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void right_pool_backward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = right_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
void top_pool_forward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = top_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void top_pool_backward_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = top_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
#endif
void bottom_pool_forward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = bottom_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void bottom_pool_backward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = bottom_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
void left_pool_forward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = left_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void left_pool_backward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = left_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
void right_pool_forward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = right_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void right_pool_backward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = right_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
void top_pool_forward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input;
input = buildATensor(ctx, ins[0]);
auto out = top_pool_forward(input);
updateDArray(ctx, out, outs[0]);
}
void top_pool_backward_parrots_cpu(HostContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
at::Tensor input, grad_output;
input = buildATensor(ctx, ins[0]);
grad_output = buildATensor(ctx, ins[1]);
auto out = top_pool_backward(input, grad_output);
updateDArray(ctx, out, outs[0]);
}
PARROTS_EXTENSION_REGISTER(bottom_pool_forward)
.input(1)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(bottom_pool_forward_parrots)
#endif
.apply(bottom_pool_forward_parrots_cpu)
.done();
PARROTS_EXTENSION_REGISTER(bottom_pool_backward)
.input(2)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(bottom_pool_backward_parrots)
#endif
.apply(bottom_pool_backward_parrots_cpu)
.done();
PARROTS_EXTENSION_REGISTER(top_pool_forward)
.input(1)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(top_pool_forward_parrots)
#endif
.apply(top_pool_forward_parrots_cpu)
.done();
PARROTS_EXTENSION_REGISTER(top_pool_backward)
.input(2)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(top_pool_backward_parrots)
#endif
.apply(top_pool_backward_parrots_cpu)
.done();
PARROTS_EXTENSION_REGISTER(left_pool_forward)
.input(1)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(left_pool_forward_parrots)
#endif
.apply(left_pool_forward_parrots_cpu)
.done();
PARROTS_EXTENSION_REGISTER(left_pool_backward)
.input(2)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(left_pool_backward_parrots)
#endif
.apply(left_pool_backward_parrots_cpu)
.done();
PARROTS_EXTENSION_REGISTER(right_pool_forward)
.input(1)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(right_pool_forward_parrots)
#endif
.apply(right_pool_forward_parrots_cpu)
.done();
PARROTS_EXTENSION_REGISTER(right_pool_backward)
.input(2)
.output(1)
#ifdef MMCV_WITH_CUDA
.apply(right_pool_backward_parrots)
#endif
.apply(right_pool_backward_parrots_cpu)
.done();
| 33.880342 | 78 | 0.646821 | Alsasolo |
6c013b547378eafcac88200b21484c344818b634 | 4,406 | hh | C++ | include/formrow.hh | conclusiveeng/devclient | 98e3ab39acaab156ab52705be8b4d9213efe9633 | [
"BSD-2-Clause"
] | null | null | null | include/formrow.hh | conclusiveeng/devclient | 98e3ab39acaab156ab52705be8b4d9213efe9633 | [
"BSD-2-Clause"
] | null | null | null | include/formrow.hh | conclusiveeng/devclient | 98e3ab39acaab156ab52705be8b4d9213efe9633 | [
"BSD-2-Clause"
] | 1 | 2020-11-25T11:24:42.000Z | 2020-11-25T11:24:42.000Z | /*-
* SPDX-License-Identifier: BSD-2-Clause-FreeBSD
*
* Copyright (c) 2019 Conclusive Engineering
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#ifndef DEVCLIENT_FORMROW_HH
#define DEVCLIENT_FORMROW_HH
#include <gtkmm.h>
template <class T>
class FormRow: public Gtk::Box
{
public:
explicit FormRow(const Glib::ustring &label):
Gtk::Box(Gtk::Orientation::ORIENTATION_HORIZONTAL, 10),
m_label(label)
{
m_label.set_justify(Gtk::Justification::JUSTIFY_LEFT);
m_label.set_size_request(250, -1);
pack_start(m_label, false, true);
pack_start(m_widget, true, true);
show_all_children();
}
T &get_widget()
{
return (m_widget);
}
protected:
T m_widget;
Gtk::Label m_label;
};
class FormRowGpio: public Gtk::Box
{
public:
explicit FormRowGpio(const Glib::ustring &label):
Gtk::Box(Gtk::Orientation::ORIENTATION_HORIZONTAL, 10),
m_toggle("off"),
m_image("gtk-no", Gtk::ICON_SIZE_BUTTON),
m_label(label)
{
m_label.set_justify(Gtk::Justification::JUSTIFY_LEFT);
m_label.set_size_request(250, -1);
pack_start(m_label, false, true);
m_radio_in.set_label("input");
m_radio_out.set_label("output");
m_radio_out.join_group(m_radio_in);
m_toggle.set_sensitive(false);
m_image.set_sensitive(false);
pack_start(m_radio_in, true, true);
pack_start(m_radio_out, true, true);
pack_start(m_toggle, true, true);
pack_start(m_image, false, false);
m_toggle.signal_toggled().connect(sigc::mem_fun(*this, &FormRowGpio::toggled));
m_radio_in.signal_toggled().connect(sigc::mem_fun(*this, &FormRowGpio::in_toggled));
m_radio_out.signal_toggled().connect(sigc::mem_fun(*this, &FormRowGpio::out_toggled));
show_all_children();
}
void toggled()
{
bool active = m_toggle.get_active();
if (active) {
m_state_changed.emit(true);
m_toggle.set_label("on");
m_image.set_from_icon_name("gtk-yes", Gtk::ICON_SIZE_BUTTON);
} else {
m_state_changed.emit(false);
m_toggle.set_label("off");
m_image.set_from_icon_name("gtk-no", Gtk::ICON_SIZE_BUTTON);
}
}
void in_toggled()
{
m_toggle.set_sensitive(false);
m_image.set_sensitive(false);
m_direction_changed.emit(false);
}
void out_toggled()
{
m_toggle.set_sensitive(true);
m_image.set_sensitive(true);
m_direction_changed.emit(true);
}
bool get_direction()
{
return (m_radio_out.get_active());
}
void set_direction(bool output)
{
m_radio_in.set_active(!output);
m_radio_out.set_active(output);
m_direction_changed.emit(output);
}
bool get_state()
{
return (m_toggle.get_active());
}
void set_state(bool state)
{
m_toggle.set_active(state);
m_state_changed.emit(state);
}
void set_gpio_name(const std::string &name)
{
m_label.set_label(name);
}
sigc::signal<void(bool)> direction_changed()
{
return m_direction_changed;
}
sigc::signal<void(bool)> state_changed()
{
return m_state_changed;
}
protected:
Gtk::ToggleButton m_toggle;
Gtk::RadioButton m_radio_in;
Gtk::RadioButton m_radio_out;
Gtk::Image m_image;
Gtk::Label m_label;
sigc::signal<void(bool)> m_direction_changed;
sigc::signal<void(bool)> m_state_changed;
};
#endif //DEVCLIENT_FORMROW_HH
| 26.22619 | 88 | 0.73695 | conclusiveeng |
6c0361b1e8fbff232a724a27fda06a3c6e7cf9b9 | 1,282 | cpp | C++ | src/lib/src/cli/commands/load-tag-database-cli-command.cpp | Penguin-Guru/imgbrd-grabber | 69bdd5566dc2b2cb3a67456bf1a159d544699bc9 | [
"Apache-2.0"
] | 1,449 | 2015-03-16T02:21:41.000Z | 2022-03-31T22:49:10.000Z | src/lib/src/cli/commands/load-tag-database-cli-command.cpp | sisco0/imgbrd-grabber | 89bf97ccab3df62286784baac242f00bf006d562 | [
"Apache-2.0"
] | 2,325 | 2015-03-16T02:23:30.000Z | 2022-03-31T21:38:26.000Z | src/lib/src/cli/commands/load-tag-database-cli-command.cpp | evanjs/imgbrd-grabber | 491f8f3c05be3fc02bc10007735c5afa19d47449 | [
"Apache-2.0"
] | 242 | 2015-03-22T11:00:54.000Z | 2022-03-31T12:37:15.000Z | #include "load-tag-database-cli-command.h"
#include <QList>
#include "cli-command.h"
#include "logger.h"
#include "models/site.h"
#include "tools/tag-list-loader.h"
LoadTagDatabaseCliCommand::LoadTagDatabaseCliCommand(Profile *profile, const QList<Site*> &sites, int minTagCount, QObject *parent)
: CliCommand(parent), m_profile(profile), m_sites(sites), m_minTagCount(minTagCount)
{}
bool LoadTagDatabaseCliCommand::validate()
{
if (m_sites.isEmpty()) {
log("You must provide at least one source to load the tag database of", Logger::Error);
return false;
}
if (m_minTagCount < 100) {
log("Loading a tag database with a tag count under 100 can take a long time and generate lots of requests", Logger::Warning);
}
return true;
}
void LoadTagDatabaseCliCommand::run()
{
loadNext();
}
void LoadTagDatabaseCliCommand::loadNext()
{
Site *site = m_sites.takeFirst();
auto *loader = new TagListLoader(m_profile, site, m_minTagCount, this);
connect(loader, &TagListLoader::finished, this, &LoadTagDatabaseCliCommand::finishedLoading);
connect(loader, &TagListLoader::finished, loader, &TagListLoader::deleteLater);
loader->start();
}
void LoadTagDatabaseCliCommand::finishedLoading()
{
if (!m_sites.isEmpty()) {
loadNext();
return;
}
emit finished(0);
}
| 25.137255 | 131 | 0.74181 | Penguin-Guru |
6c05cc044385b6f0d31fec291717369ea3355a1b | 1,108 | hh | C++ | trick_source/codegen/Interface_Code_Gen/Utilities.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | null | null | null | trick_source/codegen/Interface_Code_Gen/Utilities.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | null | null | null | trick_source/codegen/Interface_Code_Gen/Utilities.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | null | null | null |
#ifndef UTILITIES_HH
#define UTILITIES_HH
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceLocation.h"
#include "HeaderSearchDirs.hh"
enum Color {
ERROR = 31,
WARNING = 33,
INFO = 34,
SKIP = 95
};
std::string sanitize(const std::string&);
std::string trim( const std::string& str, const std::string& whitespace = " \t\n\r" ) ;
bool isInUserCode( clang::CompilerInstance & ci , clang::SourceLocation sl , HeaderSearchDirs & hsd ) ;
bool isInUserOrTrickCode( clang::CompilerInstance & ci , clang::SourceLocation sl , HeaderSearchDirs & hsd ) ;
std::string getFileName( clang::CompilerInstance & ci , clang::SourceLocation sl , HeaderSearchDirs & hsd ) ;
char * almostRealPath( const std::string& in_path ) ;
char * almostRealPath( const char * in_path ) ;
std::string color(const Color& color, const std::string& text);
std::string bold(const std::string& text);
std::string underline(const std::string& text);
std::string underline(const std::string& text, unsigned length);
std::string quote(const std::string& text);
#endif
| 34.625 | 110 | 0.727437 | gilbertguoze |
6c06fadc0f70adb5c8e6e3f4b69c9d99bd228245 | 625 | hpp | C++ | src/Info.hpp | franpog859/darwinLogs | 1d0a9bdd7c928ceee96b3121e408fc1ee1d80e05 | [
"Apache-2.0"
] | 7 | 2019-02-21T10:50:09.000Z | 2019-10-16T06:22:27.000Z | src/Info.hpp | franpog859/darwinLogs | 1d0a9bdd7c928ceee96b3121e408fc1ee1d80e05 | [
"Apache-2.0"
] | null | null | null | src/Info.hpp | franpog859/darwinLogs | 1d0a9bdd7c928ceee96b3121e408fc1ee1d80e05 | [
"Apache-2.0"
] | 2 | 2019-10-16T17:34:25.000Z | 2020-01-18T20:40:02.000Z | #ifndef INFO_HPP
#define INFO_HPP
#include "Statistics.hpp"
#include "../lib/json.hpp"
struct Info {
int childrenNumber = 0;
int adultsNumber = 0;
int eldersNumber = 0;
int maleNumber = 0;
int femaleNumber = 0;
int maleAdultNumber = 0;
int femaleAdultNumber = 0;
int deathsNumber = 0;
int newbornsNumber = 0;
int straightCouplesNumber = 0;
int homoCouplesNumber = 0;
Statistics averageChildsStatistics;
Statistics averageAdultsStatistics;
Statistics averageEldersStatistics;
Statistics averageStatistics;
Statistics minimalSurvivalStatistics;
Statistics minimalReproductionStatistics;
};
#endif | 18.939394 | 42 | 0.768 | franpog859 |
6c07d27b25624931e756a63be014f42c7441e35d | 4,640 | cpp | C++ | modules/3d/src/rgbd/volume.cpp | HattrickGenerator/opencv | 7554b53adfff8996e576691af4242f6f4acdc8f3 | [
"Apache-2.0"
] | null | null | null | modules/3d/src/rgbd/volume.cpp | HattrickGenerator/opencv | 7554b53adfff8996e576691af4242f6f4acdc8f3 | [
"Apache-2.0"
] | null | null | null | modules/3d/src/rgbd/volume.cpp | HattrickGenerator/opencv | 7554b53adfff8996e576691af4242f6f4acdc8f3 | [
"Apache-2.0"
] | 1 | 2021-04-30T18:00:41.000Z | 2021-04-30T18:00:41.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "../precomp.hpp"
#include "tsdf.hpp"
#include "hash_tsdf.hpp"
#include "colored_tsdf.hpp"
namespace cv
{
Ptr<VolumeParams> VolumeParams::defaultParams(int _volumeKind)
{
VolumeParams params;
params.kind = _volumeKind;
params.maxWeight = 64;
params.raycastStepFactor = 0.25f;
params.unitResolution = 0; // unitResolution not used for TSDF
float volumeSize = 3.0f;
Matx44f pose = Affine3f().translate(Vec3f(-volumeSize / 2.f, -volumeSize / 2.f, 0.5f)).matrix;
params.pose = Mat(pose);
if(params.kind == VolumeKind::TSDF)
{
params.resolutionX = 512;
params.resolutionY = 512;
params.resolutionZ = 512;
params.voxelSize = volumeSize / 512.f;
params.depthTruncThreshold = 0.f; // depthTruncThreshold not required for TSDF
params.tsdfTruncDist = 7 * params.voxelSize; //! About 0.04f in meters
return makePtr<VolumeParams>(params);
}
else if(params.kind == VolumeKind::HASHTSDF)
{
params.unitResolution = 16;
params.voxelSize = volumeSize / 512.f;
params.depthTruncThreshold = 4.f;
params.tsdfTruncDist = 7 * params.voxelSize; //! About 0.04f in meters
return makePtr<VolumeParams>(params);
}
else if (params.kind == VolumeKind::COLOREDTSDF)
{
params.resolutionX = 512;
params.resolutionY = 512;
params.resolutionZ = 512;
params.voxelSize = volumeSize / 512.f;
params.depthTruncThreshold = 0.f; // depthTruncThreshold not required for TSDF
params.tsdfTruncDist = 7 * params.voxelSize; //! About 0.04f in meters
return makePtr<VolumeParams>(params);
}
CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters");
}
Ptr<VolumeParams> VolumeParams::coarseParams(int _volumeKind)
{
Ptr<VolumeParams> params = defaultParams(_volumeKind);
params->raycastStepFactor = 0.75f;
float volumeSize = 3.0f;
if(params->kind == VolumeKind::TSDF)
{
params->resolutionX = 128;
params->resolutionY = 128;
params->resolutionZ = 128;
params->voxelSize = volumeSize / 128.f;
params->tsdfTruncDist = 2 * params->voxelSize; //! About 0.04f in meters
return params;
}
else if(params->kind == VolumeKind::HASHTSDF)
{
params->voxelSize = volumeSize / 128.f;
params->tsdfTruncDist = 2 * params->voxelSize; //! About 0.04f in meters
return params;
}
else if (params->kind == VolumeKind::COLOREDTSDF)
{
params->resolutionX = 128;
params->resolutionY = 128;
params->resolutionZ = 128;
params->voxelSize = volumeSize / 128.f;
params->tsdfTruncDist = 2 * params->voxelSize; //! About 0.04f in meters
return params;
}
CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters");
}
Ptr<Volume> makeVolume(const Ptr<VolumeParams>& _volumeParams)
{
int kind = _volumeParams->kind;
if(kind == VolumeParams::VolumeKind::TSDF)
return makeTSDFVolume(*_volumeParams);
else if(kind == VolumeParams::VolumeKind::HASHTSDF)
return makeHashTSDFVolume(*_volumeParams);
else if(kind == VolumeParams::VolumeKind::COLOREDTSDF)
return makeColoredTSDFVolume(*_volumeParams);
CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters");
}
Ptr<Volume> makeVolume(int _volumeKind, float _voxelSize, Matx44f _pose,
float _raycastStepFactor, float _truncDist, int _maxWeight, float _truncateThreshold,
int _resolutionX, int _resolutionY, int _resolutionZ)
{
Point3i _presolution(_resolutionX, _resolutionY, _resolutionZ);
if (_volumeKind == VolumeParams::VolumeKind::TSDF)
{
return makeTSDFVolume(_voxelSize, _pose, _raycastStepFactor, _truncDist, _maxWeight, _presolution);
}
else if (_volumeKind == VolumeParams::VolumeKind::HASHTSDF)
{
return makeHashTSDFVolume(_voxelSize, _pose, _raycastStepFactor, _truncDist, _maxWeight, _truncateThreshold);
}
else if (_volumeKind == VolumeParams::VolumeKind::COLOREDTSDF)
{
return makeColoredTSDFVolume(_voxelSize, _pose, _raycastStepFactor, _truncDist, _maxWeight, _presolution);
}
CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters");
}
} // namespace cv
| 38.347107 | 117 | 0.663793 | HattrickGenerator |
6c0daab0dcd09f4db89ab3d5bc69ac391f09559a | 1,599 | cpp | C++ | src/shogun/converter/EmbeddingConverter.cpp | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | 2 | 2021-08-12T18:11:06.000Z | 2021-11-17T10:56:49.000Z | src/shogun/converter/EmbeddingConverter.cpp | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | null | null | null | src/shogun/converter/EmbeddingConverter.cpp | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | null | null | null | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Sergey Lisitsyn, Evan Shelhamer, Thoralf Klein, Soeren Sonnenburg,
* Chiyuan Zhang
*/
#include <shogun/converter/EmbeddingConverter.h>
#include <shogun/kernel/LinearKernel.h>
#include <shogun/distance/EuclideanDistance.h>
using namespace shogun;
namespace shogun
{
CEmbeddingConverter::CEmbeddingConverter()
: CConverter()
{
m_target_dim = 1;
m_distance = new CEuclideanDistance();
m_kernel = new CLinearKernel();
init();
}
CEmbeddingConverter::~CEmbeddingConverter()
{
SG_UNREF(m_distance);
SG_UNREF(m_kernel);
}
void CEmbeddingConverter::set_target_dim(int32_t dim)
{
ASSERT(dim>0)
m_target_dim = dim;
}
int32_t CEmbeddingConverter::get_target_dim() const
{
return m_target_dim;
}
void CEmbeddingConverter::set_distance(CDistance* distance)
{
SG_REF(distance);
SG_UNREF(m_distance);
m_distance = distance;
}
CDistance* CEmbeddingConverter::get_distance() const
{
SG_REF(m_distance);
return m_distance;
}
void CEmbeddingConverter::set_kernel(CKernel* kernel)
{
SG_REF(kernel);
SG_UNREF(m_kernel);
m_kernel = kernel;
}
CKernel* CEmbeddingConverter::get_kernel() const
{
SG_REF(m_kernel);
return m_kernel;
}
void CEmbeddingConverter::init()
{
SG_ADD(&m_target_dim, "target_dim",
"target dimensionality of preprocessor", ParameterProperties::HYPER);
SG_ADD(
&m_distance, "distance", "distance to be used for embedding",
ParameterProperties::HYPER);
SG_ADD(
&m_kernel, "kernel", "kernel to be used for embedding", ParameterProperties::HYPER);
}
}
| 19.9875 | 86 | 0.752971 | cloner1984 |
6c0e3472cd0f8f02f5e64cfbc93ef1174ed4003b | 3,025 | cpp | C++ | src/cascadia/TerminalSettingsEditor/PaddingConverter.cpp | hessedoneen/terminal | aa54de1d648f45920996aeba1edecc67237c6642 | [
"MIT"
] | 4 | 2021-05-11T06:11:52.000Z | 2021-07-31T22:32:57.000Z | src/cascadia/TerminalSettingsEditor/PaddingConverter.cpp | Apasys/terminal | c1f844307ca5d5d8d5a457faa616f5fa089aa771 | [
"MIT"
] | 2 | 2021-10-30T02:38:17.000Z | 2021-10-30T02:45:05.000Z | src/cascadia/TerminalSettingsEditor/PaddingConverter.cpp | Apasys/terminal | c1f844307ca5d5d8d5a457faa616f5fa089aa771 | [
"MIT"
] | 2 | 2021-02-02T22:12:35.000Z | 2021-05-04T23:24:57.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "PaddingConverter.h"
#include "PaddingConverter.g.cpp"
using namespace winrt::Windows;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Text;
namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
{
Foundation::IInspectable PaddingConverter::Convert(Foundation::IInspectable const& value,
Windows::UI::Xaml::Interop::TypeName const& /* targetType */,
Foundation::IInspectable const& /* parameter */,
hstring const& /* language */)
{
const auto& padding = winrt::unbox_value<hstring>(value);
const wchar_t singleCharDelim = L',';
std::wstringstream tokenStream(padding.c_str());
std::wstring token;
double maxVal = 0;
size_t* idx = nullptr;
// Get padding values till we run out of delimiter separated values in the stream
// Non-numeral values detected will default to 0
// std::getline will not throw exception unless flags are set on the wstringstream
// std::stod will throw invalid_argument exception if the input is an invalid double value
// std::stod will throw out_of_range exception if the input value is more than DBL_MAX
try
{
while (std::getline(tokenStream, token, singleCharDelim))
{
// std::stod internally calls wcstod which handles whitespace prefix (which is ignored)
// & stops the scan when first char outside the range of radix is encountered
// We'll be permissive till the extent that stod function allows us to be by default
// Ex. a value like 100.3#535w2 will be read as 100.3, but ;df25 will fail
const auto curVal = std::stod(token, idx);
if (curVal > maxVal)
{
maxVal = curVal;
}
}
}
catch (...)
{
// If something goes wrong, even if due to a single bad padding value, we'll return default 0 padding
maxVal = 0;
LOG_CAUGHT_EXCEPTION();
}
return winrt::box_value<double>(maxVal);
}
Foundation::IInspectable PaddingConverter::ConvertBack(Foundation::IInspectable const& value,
Windows::UI::Xaml::Interop::TypeName const& /* targetType */,
Foundation::IInspectable const& /*parameter*/,
hstring const& /* language */)
{
const auto padding{ winrt::unbox_value<double>(value) };
return winrt::box_value(winrt::to_hstring(padding));
}
}
| 45.833333 | 121 | 0.551736 | hessedoneen |
6c1137755d76ede42e7f26a3229ad4714f37eb02 | 4,633 | hpp | C++ | sprout/iterator/distance.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | 1 | 2020-02-04T05:16:01.000Z | 2020-02-04T05:16:01.000Z | sprout/iterator/distance.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | null | null | null | sprout/iterator/distance.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | null | null | null | #ifndef SPROUT_ITERATOR_DISTANCE_HPP
#define SPROUT_ITERATOR_DISTANCE_HPP
#include <iterator>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/iterator/next.hpp>
#include <sprout/iterator/type_traits/category.hpp>
#include <sprout/utility/pair/pair.hpp>
#include <sprout/adl/not_found.hpp>
namespace sprout_adl {
sprout::not_found_via_adl iterator_distance(...);
} // namespace sprout_adl
namespace sprout {
namespace iterator_detail {
template<typename RandomAccessIterator>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::is_constant_distance_iterator<RandomAccessIterator>::value,
typename std::iterator_traits<RandomAccessIterator>::difference_type
>::type
iterator_distance(RandomAccessIterator first, RandomAccessIterator last, std::random_access_iterator_tag*) {
return last - first;
}
template<typename InputIterator>
inline SPROUT_CONSTEXPR sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type>
iterator_distance_impl_1(
sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> const& current,
InputIterator last, typename std::iterator_traits<InputIterator>::difference_type n
)
{
typedef sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> type;
return current.first == last ? current
: n == 1 ? type(sprout::next(current.first), current.second + 1)
: sprout::iterator_detail::iterator_distance_impl_1(
sprout::iterator_detail::iterator_distance_impl_1(
current,
last, n / 2
),
last, n - n / 2
)
;
}
template<typename InputIterator>
inline SPROUT_CONSTEXPR sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type>
iterator_distance_impl(
sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> const& current,
InputIterator last, typename std::iterator_traits<InputIterator>::difference_type n
)
{
return current.first == last ? current
: sprout::iterator_detail::iterator_distance_impl(
sprout::iterator_detail::iterator_distance_impl_1(
current,
last, n
),
last, n * 2
)
;
}
template<typename InputIterator>
inline SPROUT_CONSTEXPR typename std::iterator_traits<InputIterator>::difference_type
iterator_distance(InputIterator first, InputIterator last, std::input_iterator_tag*) {
typedef sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> type;
return sprout::iterator_detail::iterator_distance_impl(type(first, 0), last, 1).second;
}
template<typename InputIterator>
inline SPROUT_CONSTEXPR typename std::enable_if<
std::is_literal_type<InputIterator>::value,
typename std::iterator_traits<InputIterator>::difference_type
>::type
iterator_distance(InputIterator first, InputIterator last) {
typedef typename std::iterator_traits<InputIterator>::iterator_category* category;
return sprout::iterator_detail::iterator_distance(first, last, category());
}
template<typename InputIterator>
inline SPROUT_CONSTEXPR typename std::enable_if<
!std::is_literal_type<InputIterator>::value,
typename std::iterator_traits<InputIterator>::difference_type
>::type
iterator_distance(InputIterator first, InputIterator last) {
return std::distance(first, last);
}
} // namespace iterator_detail
} // namespace sprout
namespace sprout_iterator_detail {
template<typename InputIterator>
inline SPROUT_CONSTEXPR typename std::iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last) {
using sprout::iterator_detail::iterator_distance;
using sprout_adl::iterator_distance;
return iterator_distance(first, last);
}
} // namespace sprout_iterator_detail
namespace sprout {
//
// distance
//
// effect:
// ADL callable iterator_distance(first, last) -> iterator_distance(first, last)
// otherwise, [first, last) is not LiteralType -> std::distance(first, last)
// otherwise, [first, last) is RandomAccessIterator && not Pointer -> last - first
// otherwise -> linearly count: first to last
//
template<typename InputIterator>
inline SPROUT_CONSTEXPR typename std::iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last) {
return sprout_iterator_detail::distance(first, last);
}
} // namespace sprout
#endif // #ifndef SPROUT_ITERATOR_DISTANCE_HPP
| 39.262712 | 117 | 0.751133 | osyo-manga |
6c120ec4711794fadcb50fe0695f0623c8ac08f0 | 1,639 | cpp | C++ | igl/edge_flaps.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | igl/edge_flaps.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | igl/edge_flaps.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "edge_flaps.h"
#include "unique_edge_map.h"
#include <vector>
#include <cassert>
IGL_INLINE void igl::edge_flaps(
const Eigen::MatrixXi & F,
const Eigen::MatrixXi & uE,
const Eigen::VectorXi & EMAP,
Eigen::MatrixXi & EF,
Eigen::MatrixXi & EI)
{
// Initialize to boundary value
EF.setConstant(uE.rows(),2,-1);
EI.setConstant(uE.rows(),2,-1);
// loop over all faces
for(int f = 0;f<F.rows();f++)
{
// loop over edges across from corners
for(int v = 0;v<3;v++)
{
// get edge id
const int e = EMAP(v*F.rows()+f);
// See if this is left or right flap w.r.t. edge orientation
if( F(f,(v+1)%3) == uE(e,0) && F(f,(v+2)%3) == uE(e,1))
{
EF(e,0) = f;
EI(e,0) = v;
}else
{
assert(F(f,(v+1)%3) == uE(e,1) && F(f,(v+2)%3) == uE(e,0));
EF(e,1) = f;
EI(e,1) = v;
}
}
}
}
IGL_INLINE void igl::edge_flaps(
const Eigen::MatrixXi & F,
Eigen::MatrixXi & uE,
Eigen::VectorXi & EMAP,
Eigen::MatrixXi & EF,
Eigen::MatrixXi & EI)
{
Eigen::MatrixXi allE;
std::vector<std::vector<int> > uE2E;
igl::unique_edge_map(F,allE,uE,EMAP,uE2E);
// Const-ify to call overload
const auto & cuE = uE;
const auto & cEMAP = EMAP;
return edge_flaps(F,cuE,cEMAP,EF,EI);
}
| 26.868852 | 79 | 0.596705 | aviadtzemah |
6c13f776d29e995deef1cf9b390891a093a070d2 | 165 | cpp | C++ | chapter-9/9.30.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-9/9.30.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-9/9.30.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // The one parameter version of resize requires that the element type must support value initialization, or it must has a default constructor if it is a class type.
| 82.5 | 164 | 0.8 | zero4drift |
6c1945d81e88dbc1dfda09dfb8cf840c8c3b917c | 407 | hh | C++ | drake/examples/user_libraries/color/Color.hh | wk8/elle | a66d3c0aeca86bcd13ec14d3797edc660b2496fc | [
"Apache-2.0"
] | 521 | 2016-02-14T00:39:01.000Z | 2022-03-01T22:39:25.000Z | drake/examples/user_libraries/color/Color.hh | mefyl/elle | a8154593c42743f45b9df09daf62b44630c24a02 | [
"Apache-2.0"
] | 8 | 2017-02-21T11:47:33.000Z | 2018-11-01T09:37:14.000Z | drake/examples/user_libraries/color/Color.hh | mefyl/elle | a8154593c42743f45b9df09daf62b44630c24a02 | [
"Apache-2.0"
] | 48 | 2017-02-21T10:18:13.000Z | 2022-03-25T02:35:20.000Z | #ifndef COLOR_COLOR_HH
# define COLOR_COLOR_HH
# include <ostream>
namespace color
{
struct Color
{
typedef uint8_t Intensity;
Color(Intensity r = 0,
Intensity g = 0,
Intensity b = 0);
Color(Color const&) = default;
virtual
~Color();
Intensity r, g, b;
};
}
std::ostream&
operator <<(std::ostream& out,
color::Color const& color);
#endif
| 14.034483 | 39 | 0.594595 | wk8 |
6c1e1c5adbdc187af8ebc7b6852137a7a46d2358 | 492 | hpp | C++ | common.hpp | totemofwolf/redis-cerberus | 69a12f6a88ce2628c041b7d74f7b27444c5778b2 | [
"MIT"
] | 264 | 2015-01-04T06:48:35.000Z | 2017-06-05T08:57:51.000Z | common.hpp | totemofwolf/redis-cerberus | 69a12f6a88ce2628c041b7d74f7b27444c5778b2 | [
"MIT"
] | 21 | 2015-08-25T07:44:24.000Z | 2017-04-13T10:01:56.000Z | common.hpp | totemofwolf/redis-cerberus | 69a12f6a88ce2628c041b7d74f7b27444c5778b2 | [
"MIT"
] | 76 | 2015-01-04T13:44:39.000Z | 2017-06-07T07:02:14.000Z | #ifndef __CERBERUS_COMMON_HPP__
#define __CERBERUS_COMMON_HPP__
#include <chrono>
#define VERSION "0.8.0-2018-05-02"
namespace cerb {
using byte = unsigned char;
using rint = int64_t;
using slot = unsigned int;
using msize_t = uint64_t;
typedef std::chrono::high_resolution_clock Clock;
typedef Clock::time_point Time;
typedef std::chrono::duration<double> Interval;
constexpr msize_t CLUSTER_SLOT_COUNT = 16384;
}
#endif /* __CERBERUS_COMMON_HPP__ */
| 20.5 | 53 | 0.727642 | totemofwolf |
6c209c427c0fd26541c0d983f71576c4296ef771 | 859 | hpp | C++ | src/mbgl/text/bidi.hpp | mapzak/mapbox-gl-native-android-minimod | 83f1350747be9a60eb0275bd1a8dcb8e5f027abe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/text/bidi.hpp | mapzak/mapbox-gl-native-android-minimod | 83f1350747be9a60eb0275bd1a8dcb8e5f027abe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/text/bidi.hpp | mapzak/mapbox-gl-native-android-minimod | 83f1350747be9a60eb0275bd1a8dcb8e5f027abe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #pragma once
#include <set>
#include <string>
#include <vector>
#include <memory>
#include <mbgl/util/noncopyable.hpp>
namespace mbgl {
class BiDi;
class BiDiImpl;
std::u16string applyArabicShaping(const std::u16string&);
class ProcessedBiDiText {
public:
ProcessedBiDiText(BiDi&);
std::vector<std::u16string> applyLineBreaking(std::set<int32_t>);
private:
void mergeParagraphLineBreaks(std::set<int32_t>&);
BiDi& bidi;
};
class BiDi : private util::noncopyable {
public:
BiDi();
~BiDi();
// Calling processText resets internal state, invalidating any existing ProcessedBiDiText
// objects
ProcessedBiDiText processText(const std::u16string&);
friend class ProcessedBiDiText;
private:
std::u16string getLine(int32_t start, int32_t end);
std::unique_ptr<BiDiImpl> impl;
};
} // end namespace mbgl
| 18.276596 | 93 | 0.718277 | mapzak |
6c218dfacf9f30759eeee36d48f91b71a81f22b1 | 1,549 | cpp | C++ | src/Robots/Skyline.cpp | Overture-7421/OvertureRobotCode_2020 | be9b69ea5f852b1077d1531b4f34921964544c86 | [
"BSD-3-Clause"
] | 1 | 2020-03-17T04:15:33.000Z | 2020-03-17T04:15:33.000Z | src/Robots/Skyline.cpp | Overture-7421/Overture-FRC | be9b69ea5f852b1077d1531b4f34921964544c86 | [
"BSD-3-Clause"
] | null | null | null | src/Robots/Skyline.cpp | Overture-7421/Overture-FRC | be9b69ea5f852b1077d1531b4f34921964544c86 | [
"BSD-3-Clause"
] | null | null | null | #include "Skyline.h"
#include "frc2/command/CommandScheduler.h"
#include <frc/smartdashboard/SmartDashboard.h>
Skyline::Skyline() : TimedRobot() {}
void Skyline::RobotInit() {
frc::SmartDashboard::PutNumber("Setpoint Pos", 0);
frc::SmartDashboard::PutBoolean("Setpoint Piston", false);
}
/**
* This function is called every robot packet, no matter the mode. Use
* this for items like diagnostics that you want to run during disabled,
* autonomous, teleoperated and test.
*
* <p> This runs after the mode specific periodic functions, but before
* LiveWindow and SmartDashboard integrated updating.
*/
void Skyline::RobotPeriodic() {
testMotor.set(frc::SmartDashboard::GetNumber("Setpoint Pos", 0));
frc::SmartDashboard::PutNumber("Pos", testMotor.getPosition());
testPiston.setState(frc::SmartDashboard::GetBoolean("Setpoint Piston", false));
}
/**
* This function is called once each time the robot enters Disabled mode. You
* can use it to reset any subsystem information you want to clear when the
* robot is disabled.
*/
void Skyline::DisabledInit() {}
void Skyline::DisabledPeriodic() {}
/**
* This autonomous runs the autonomous command selected by your {@link
* RobotContainer} class.
*/
void Skyline::AutonomousInit() {}
void Skyline::AutonomousPeriodic() {}
void Skyline::TeleopInit() {}
/**
* This function is called periodically during operator control.
*/
void Skyline::TeleopPeriodic() {}
/**
* This function is called periodically during test mode.
*/
void Skyline::TestPeriodic() {}
| 28.163636 | 83 | 0.726921 | Overture-7421 |
6c26a1e730a1e297207b53ab5d8085cd4308c998 | 9,570 | cpp | C++ | vidio_old.cpp | Steve132/vidio | b70778cb61ec3a95e1fbff36e8ab21c2c6b2fbad | [
"MIT"
] | null | null | null | vidio_old.cpp | Steve132/vidio | b70778cb61ec3a95e1fbff36e8ab21c2c6b2fbad | [
"MIT"
] | null | null | null | vidio_old.cpp | Steve132/vidio | b70778cb61ec3a95e1fbff36e8ab21c2c6b2fbad | [
"MIT"
] | null | null | null | #include "vidio.hpp"
#include "vidio_internal.hpp"
#include <list>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <unordered_map>
#include <iostream>
static std::string get_ffmpeg_prefix(const std::string& usr_override="")
{
std::list<std::string> possible_locations;
if(usr_override != "")
{
possible_locations.push_back(usr_override);
}
const std::vector<std::string>& pform=vidio::platform::get_default_ffmpeg_search_locations();
copy(pform.cbegin(),pform.cend(),std::back_inserter(possible_locations));
for(auto pl:possible_locations)
{
try
{
vidio::platform::create_process_reader_stream(pl+" -loglevel panic -hide_banner");
return pl;
}
catch(const std::exception& e)
{}
}
throw std::runtime_error("No executable ffmpeg process found");
}
inline static bool compute_bigendian()
{
union a
{
uint16_t s;
const uint8_t ub[2];
a():s(0x0001)
{}
} ai;
return ai.ub[0]!=0x01;
}
inline static bool is_bigendian()
{
static const bool test=compute_bigendian();
return test;
}
static std::string get_fmt_code(const std::uint32_t& typesize,const uint32_t num_channels)
{
const std::string types_le[2][4]={
{"gray8","ya8","rgb24","rgba"},
{"gray16","ya16","rgb48","rgba64"}
}; //AV_PIX_FMT_RGBA64BE_LIBAV or AV_PIX_FMT_RGBA64BE? try both
if(typesize > 2 || typesize < 1)
{
throw std::range_error("The typesize must be 1 or 2 (8-bit or 16-bit color ONLY)");
}
if(num_channels > 4 || num_channels < 1)
{
throw std::range_error("There must be at least 1 channel and less than 5 channels");
}
std::string typesel=types_le[typesize-1][num_channels-1];
if(typesize > 1)
{
if(is_bigendian())
{
typesel+="be";
}
else
{
typesel+="le";
}
}
return typesel;
}
namespace vidio
{
namespace priv
{
class StreamImpl
{
public:
std::string ffmpeg_path;
Size size;
uint32_t channels;
uint32_t typewidth;
double framerate;
bool is_open;
StreamImpl(
const Size& tsize,
const uint32_t& tchannels,
const uint32_t& ttypewidth,
const double& tframerate,
const std::string& search_path_override):
size(tsize),
channels(tchannels),
typewidth(ttypewidth),
framerate(tframerate)
{
ffmpeg_path=get_ffmpeg_prefix(search_path_override);
}
virtual ~StreamImpl()
{}
};
struct pfmtpair
{
uint32_t channels,typewidth;
};
typedef std::pair<std::string,pfmtpair> pfmttriple;
std::ostream& operator<<(std::ostream& out,const pfmtpair& pdata)
{
return out << pdata.channels << '.' << pdata.typewidth;
}
std::istream& operator>>(std::istream& ins,pfmttriple& pdata)
{
std::string tmp;
ins >> tmp >> pdata.first >> pdata.second.channels >> pdata.second.typewidth;
if(pdata.second.channels != 0)
{
uint32_t realtypewidth=pdata.second.typewidth / pdata.second.channels;
pdata.second.typewidth=1;
if(realtypewidth >= 16)
{
pdata.second.typewidth=2;
return ins;
}
std::string pstr("p");
for(int i=9;i<=16;i++)
{
std::string pistr=pstr+std::to_string(i);
if(pdata.first.find(pistr+"be") != std::string::npos || pdata.first.find(pistr+"le") != std::string::npos)
{
pdata.second.typewidth=2;
return ins;
}
}
}
return ins;
}
typedef std::unordered_map<std::string,pfmtpair> pfmtmap_type;
pfmtmap_type load_pfmt_map(const std::string& ffpath)
{
std::ostringstream cmd;
cmd << ffpath << " -v panic -pix_fmts";
std::shared_ptr<std::istream> pstreamptr=vidio::platform::create_process_reader_stream(cmd.str());
std::string tmp;
int dashcount;
for(int dashcount=0;*pstreamptr && dashcount < 5;)
{
int hscan=pstreamptr->get();
if(hscan == '-')
{
dashcount++;
}
else
{
dashcount=0;
}
}
return pfmtmap_type((std::istream_iterator<pfmttriple>(*pstreamptr)),std::istream_iterator<pfmttriple>());
}
struct ffprobe_info
{
Size size;
uint32_t channels;
uint32_t typewidth;
double framerate;
uint32_t num_frames;
ffprobe_info(std::string ffpath,const std::string& filename)
{
static pfmtmap_type pfmtmap=load_pfmt_map(ffpath);
std::cout << "NUMKEYS:" << pfmtmap.size() << std::endl;
for(auto fpair : pfmtmap)
{
std::cout << fpair.first << ":" << fpair.second << std::endl;
}
//platform::create_process_reader_streambuf(ffpath);
std::ostringstream cmd;
cmd << ffpath << " -v panic -select_streams V:0 -show_entries stream=width,height,pix_fmt,duration,nb_frames -of default=noprint_wrappers=1:nokey=1 -i " << filename;
std::shared_ptr<std::istream> pstreamptr=vidio::platform::create_process_reader_stream(cmd.str());
std::istream& pstream=*pstreamptr;
pstream >> size.width >> size.height;
std::string pix_fmt;
pstream >> pix_fmt;
pfmtpair pair=pfmtmap[pix_fmt];
channels=pair.channels;
typewidth=pair.typewidth;
double duration;
pstream >> duration >> num_frames;
framerate=duration/static_cast<double>(num_frames);
}
};
class ReaderImpl: public StreamImpl
{
public:
std::shared_ptr<std::istream> pstreamptr;
uint32_t num_frames;
ReaderImpl(
const std::string& filename,
const Size& tsize,
const uint32_t tchannels,
const uint32_t ttypewidth,
const double tframerate,
const std::string& extra_decode_ffmpeg_params,
const std::string& search_path_override):
StreamImpl(tsize,tchannels,ttypewidth,tframerate,search_path_override)
{
std::ostringstream cmdin;
std::ostringstream cmdout;
std::ostringstream cmd;
std::string ffprobe_path=ffmpeg_path;
auto ffb=ffprobe_path.rbegin();
*(ffb++)='b';*(ffb++)='o';*(ffb++)='r';*(ffb++)='p';
ffprobe_path.push_back('e');
ffprobe_info info(ffprobe_path,filename);
//Use :v:0 as the stream specifier for all options
//Use and -an -sn to disable other streams.
cmdout << " -an -sn";
//cmdin << " -loglevel trace -hide_banner";
cmdin << " -loglevel fatal -hide_banner";
//If size is not specified (0), do populate size datatype with probed info.
if(size.width==0 || size.height==0)
{
//size=populate from ffprobe
}
//otherwise, if its' specified, add a scaling filter tothe filterchain on output.
else
{
cmdout << " -s:v:0 " << size.width << "x" << size.height;
}
if(channels==0)
{
//channels=populate from ffprobe (probably do all the ffprobe populates at once if any of the info is unknown)
}
if(typewidth==0)
{
//typewidth=populate from ffprobe
}
if(framerate < 0.0)
{
//framerate=populate from ffprobe
}
else
{
//cmdin << " -framerate:v:0 " << framerate;
cmdout << " -r:v:0 " << framerate;
}
cmdout << " -c:v:0 rawvideo -f rawvideo -pix_fmt " << get_fmt_code(typewidth,channels);
cmdin << " " << extra_decode_ffmpeg_params;
cmd << ffmpeg_path << cmdin.str() << " -i " << filename << cmdout.str() << " - ";
pstreamptr=vidio::platform::create_process_reader_stream(cmd.str());
}
};
class WriterImpl: public StreamImpl
{
public:
std::shared_ptr<std::ostream> pstreamptr;
WriterImpl(
const std::string& filename,
const Size& tsize,
const uint32_t tchannels,
const uint32_t ttypewidth,
const double tframerate,
const std::string& extra_encode_ffmpeg_params,
const std::string& search_path_override):
StreamImpl(tsize,tchannels,ttypewidth,tframerate,search_path_override)
{
std::ostringstream cmdin;
std::ostringstream cmdout;
std::ostringstream cmd;
cmdin << " -f rawvideo -pixel_format " << get_fmt_code(typewidth,channels);
cmdin << " -framerate " << framerate;
cmdin << " -video_size " << size.width << "x" << size.height;
cmdout << " " << extra_encode_ffmpeg_params;
cmd << ffmpeg_path << cmdin.str() << " -i - " << cmdout.str() << " " << filename;
pstreamptr=vidio::platform::create_process_writer_stream(cmd.str());
}
};
}
const Size Size::Unknown=Size(0,0);
Stream::Stream(priv::StreamImpl* iptr):
impl(iptr),
size(iptr->size),
channels(iptr->channels),
typewidth(iptr->typewidth),
framerate(iptr->framerate),
is_open(iptr->is_open),
frame_buffer_size(size.width*size.height*channels*typewidth)
{}
Stream::~Stream()
{}
Reader::Reader( const std::string& filename,
const Size& tsize,
const uint32_t tchannels,
const uint32_t ttypewidth,
const double tframerate,
const std::string& extra_decode_ffmpeg_params,
const std::string& search_path_override):
Stream( new priv::ReaderImpl(
filename,
tsize,
tchannels,
ttypewidth,
tframerate,
extra_decode_ffmpeg_params,
search_path_override)
),
framesinstream(dynamic_cast<priv::ReaderImpl*>(impl.get())->pstreamptr),
num_frames(dynamic_cast<const priv::ReaderImpl*>(impl.get())->num_frames)
{}
Writer::Writer(const std::string& filename,
const Size& tsize,
const uint32_t tchannels,
const uint32_t ttypewidth,
const double tframerate,
const std::string& extra_encode_ffmpeg_params,
const std::string& search_path_override):
Stream(new priv::WriterImpl(
filename,
tsize,
tchannels,
ttypewidth,
tframerate,
extra_encode_ffmpeg_params,
search_path_override)),
framesoutstream(dynamic_cast<priv::WriterImpl*>(impl.get())->pstreamptr)
{}
}
//eventually use HW formats. https://www.ffmpeg.org/doxygen/2.5/pixfmt_8h.html#a9a8e335cf3be472042bc9f0cf80cd4c5
| 24.664948 | 168 | 0.667607 | Steve132 |
6c27bd30c637d5f913a2d4a908847ba465466143 | 45,201 | cc | C++ | src/asm/riscv-jit.cc | csail-csg/riscv-meta | 4258e8e8784ad2fb2bc77f9d867fe762f86561aa | [
"BSD-3-Clause"
] | 6 | 2019-02-07T18:22:17.000Z | 2021-11-05T01:43:09.000Z | src/asm/riscv-jit.cc | csail-csg/riscv-meta | 4258e8e8784ad2fb2bc77f9d867fe762f86561aa | [
"BSD-3-Clause"
] | null | null | null | src/asm/riscv-jit.cc | csail-csg/riscv-meta | 4258e8e8784ad2fb2bc77f9d867fe762f86561aa | [
"BSD-3-Clause"
] | 2 | 2018-02-06T13:26:41.000Z | 2020-12-06T09:46:16.000Z | //
// riscv-jit.cc
//
// DANGER - This is machine generated code
//
#include <cstdint>
#include <cstdlib>
#include <cassert>
#include "riscv-types.h"
#include "riscv-endian.h"
#include "riscv-jit.h"
#include "riscv-meta.h"
#include "riscv-codec.h"
using namespace riscv;
uint64_t riscv::emit_lui(ireg5 rd, simm32 imm20)
{
decode dec;
if (!(rd.valid() && imm20.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lui;
dec.rd = rd;
dec.imm = imm20;
return encode_inst(dec);
}
uint64_t riscv::emit_auipc(ireg5 rd, offset32 oimm20)
{
decode dec;
if (!(rd.valid() && oimm20.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_auipc;
dec.rd = rd;
dec.imm = oimm20;
return encode_inst(dec);
}
uint64_t riscv::emit_jal(ireg5 rd, offset21 jimm20)
{
decode dec;
if (!(rd.valid() && jimm20.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_jal;
dec.rd = rd;
dec.imm = jimm20;
return encode_inst(dec);
}
uint64_t riscv::emit_jalr(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_jalr;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_beq(ireg5 rs1, ireg5 rs2, offset13 sbimm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && sbimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_beq;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = sbimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_bne(ireg5 rs1, ireg5 rs2, offset13 sbimm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && sbimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_bne;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = sbimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_blt(ireg5 rs1, ireg5 rs2, offset13 sbimm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && sbimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_blt;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = sbimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_bge(ireg5 rs1, ireg5 rs2, offset13 sbimm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && sbimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_bge;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = sbimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_bltu(ireg5 rs1, ireg5 rs2, offset13 sbimm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && sbimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_bltu;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = sbimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_bgeu(ireg5 rs1, ireg5 rs2, offset13 sbimm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && sbimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_bgeu;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = sbimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_lb(ireg5 rd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lb;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_lh(ireg5 rd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lh;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_lw(ireg5 rd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lw;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_lbu(ireg5 rd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lbu;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_lhu(ireg5 rd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lhu;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_sb(ireg5 rs1, ireg5 rs2, offset12 simm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && simm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sb;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = simm12;
return encode_inst(dec);
}
uint64_t riscv::emit_sh(ireg5 rs1, ireg5 rs2, offset12 simm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && simm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sh;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = simm12;
return encode_inst(dec);
}
uint64_t riscv::emit_sw(ireg5 rs1, ireg5 rs2, offset12 simm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && simm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sw;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = simm12;
return encode_inst(dec);
}
uint64_t riscv::emit_addi(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_addi;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_slti(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_slti;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_sltiu(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sltiu;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_xori(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_xori;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_ori(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_ori;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_andi(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_andi;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_slli_rv32i(ireg5 rd, ireg5 rs1, uimm5 shamt5)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt5.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_slli_rv32i;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt5;
return encode_inst(dec);
}
uint64_t riscv::emit_srli_rv32i(ireg5 rd, ireg5 rs1, uimm5 shamt5)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt5.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_srli_rv32i;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt5;
return encode_inst(dec);
}
uint64_t riscv::emit_srai_rv32i(ireg5 rd, ireg5 rs1, uimm5 shamt5)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt5.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_srai_rv32i;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt5;
return encode_inst(dec);
}
uint64_t riscv::emit_add(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_add;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_sub(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sub;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_sll(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sll;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_slt(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_slt;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_sltu(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sltu;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_xor(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_xor;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_srl(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_srl;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_sra(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sra;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_or(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_or;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_and(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_and;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fence(arg4 pred, arg4 succ)
{
decode dec;
if (!(pred.valid() && succ.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fence;
dec.pred = pred;
dec.succ = succ;
return encode_inst(dec);
}
uint64_t riscv::emit_fence_i()
{
decode dec;
dec.op = riscv_op_fence_i;
return encode_inst(dec);
}
uint64_t riscv::emit_lwu(ireg5 rd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lwu;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_ld(ireg5 rd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_ld;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_sd(ireg5 rs1, ireg5 rs2, offset12 simm12)
{
decode dec;
if (!(rs1.valid() && rs2.valid() && simm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.imm = simm12;
return encode_inst(dec);
}
uint64_t riscv::emit_slli_rv64i(ireg5 rd, ireg5 rs1, uimm6 shamt6)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt6.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_slli_rv64i;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt6;
return encode_inst(dec);
}
uint64_t riscv::emit_srli_rv64i(ireg5 rd, ireg5 rs1, uimm6 shamt6)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt6.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_srli_rv64i;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt6;
return encode_inst(dec);
}
uint64_t riscv::emit_srai_rv64i(ireg5 rd, ireg5 rs1, uimm6 shamt6)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt6.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_srai_rv64i;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt6;
return encode_inst(dec);
}
uint64_t riscv::emit_addiw(ireg5 rd, ireg5 rs1, simm12 imm12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && imm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_addiw;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = imm12;
return encode_inst(dec);
}
uint64_t riscv::emit_slliw(ireg5 rd, ireg5 rs1, uimm5 shamt5)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt5.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_slliw;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt5;
return encode_inst(dec);
}
uint64_t riscv::emit_srliw(ireg5 rd, ireg5 rs1, uimm5 shamt5)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt5.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_srliw;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt5;
return encode_inst(dec);
}
uint64_t riscv::emit_sraiw(ireg5 rd, ireg5 rs1, uimm5 shamt5)
{
decode dec;
if (!(rd.valid() && rs1.valid() && shamt5.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sraiw;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = shamt5;
return encode_inst(dec);
}
uint64_t riscv::emit_addw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_addw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_subw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_subw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_sllw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sllw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_srlw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_srlw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_sraw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sraw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_mul(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_mul;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_mulh(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_mulh;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_mulhsu(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_mulhsu;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_mulhu(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_mulhu;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_div(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_div;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_divu(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_divu;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_rem(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_rem;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_remu(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_remu;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_mulw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_mulw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_divw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_divw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_divuw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_divuw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_remw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_remw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_remuw(ireg5 rd, ireg5 rs1, ireg5 rs2)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_remuw;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
return encode_inst(dec);
}
uint64_t riscv::emit_lr_w(ireg5 rd, ireg5 rs1, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lr_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_sc_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sc_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoswap_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoswap_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoadd_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoadd_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoxor_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoxor_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoor_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoor_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoand_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoand_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amomin_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amomin_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amomax_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amomax_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amominu_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amominu_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amomaxu_w(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amomaxu_w;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_lr_d(ireg5 rd, ireg5 rs1, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_lr_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_sc_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sc_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoswap_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoswap_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoadd_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoadd_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoxor_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoxor_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoor_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoor_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amoand_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amoand_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amomin_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amomin_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amomax_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amomax_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amominu_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amominu_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_amomaxu_d(ireg5 rd, ireg5 rs1, ireg5 rs2, arg1 aq, arg1 rl)
{
decode dec;
if (!(rd.valid() && rs1.valid() && rs2.valid() && aq.valid() && rl.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_amomaxu_d;
dec.rd = rd;
dec.rs1 = rs1;
dec.rs2 = rs2;
dec.aq = aq;
dec.rl = rl;
return encode_inst(dec);
}
uint64_t riscv::emit_ecall()
{
decode dec;
dec.op = riscv_op_ecall;
return encode_inst(dec);
}
uint64_t riscv::emit_ebreak()
{
decode dec;
dec.op = riscv_op_ebreak;
return encode_inst(dec);
}
uint64_t riscv::emit_uret()
{
decode dec;
dec.op = riscv_op_uret;
return encode_inst(dec);
}
uint64_t riscv::emit_sret()
{
decode dec;
dec.op = riscv_op_sret;
return encode_inst(dec);
}
uint64_t riscv::emit_hret()
{
decode dec;
dec.op = riscv_op_hret;
return encode_inst(dec);
}
uint64_t riscv::emit_mret()
{
decode dec;
dec.op = riscv_op_mret;
return encode_inst(dec);
}
uint64_t riscv::emit_dret()
{
decode dec;
dec.op = riscv_op_dret;
return encode_inst(dec);
}
uint64_t riscv::emit_sfence_vm(ireg5 rs1)
{
decode dec;
if (!(rs1.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_sfence_vm;
dec.rs1 = rs1;
return encode_inst(dec);
}
uint64_t riscv::emit_wfi()
{
decode dec;
dec.op = riscv_op_wfi;
return encode_inst(dec);
}
uint64_t riscv::emit_csrrw(ireg5 rd, ireg5 rs1, uimm12 csr12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && csr12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_csrrw;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = csr12;
return encode_inst(dec);
}
uint64_t riscv::emit_csrrs(ireg5 rd, ireg5 rs1, uimm12 csr12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && csr12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_csrrs;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = csr12;
return encode_inst(dec);
}
uint64_t riscv::emit_csrrc(ireg5 rd, ireg5 rs1, uimm12 csr12)
{
decode dec;
if (!(rd.valid() && rs1.valid() && csr12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_csrrc;
dec.rd = rd;
dec.rs1 = rs1;
dec.imm = csr12;
return encode_inst(dec);
}
uint64_t riscv::emit_csrrwi(ireg5 rd, uimm5 zimm, uimm12 csr12)
{
decode dec;
if (!(rd.valid() && zimm.valid() && csr12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_csrrwi;
dec.rd = rd;
dec.imm = zimm;
dec.imm = csr12;
return encode_inst(dec);
}
uint64_t riscv::emit_csrrsi(ireg5 rd, uimm5 zimm, uimm12 csr12)
{
decode dec;
if (!(rd.valid() && zimm.valid() && csr12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_csrrsi;
dec.rd = rd;
dec.imm = zimm;
dec.imm = csr12;
return encode_inst(dec);
}
uint64_t riscv::emit_csrrci(ireg5 rd, uimm5 zimm, uimm12 csr12)
{
decode dec;
if (!(rd.valid() && zimm.valid() && csr12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_csrrci;
dec.rd = rd;
dec.imm = zimm;
dec.imm = csr12;
return encode_inst(dec);
}
uint64_t riscv::emit_flw(freg5 frd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(frd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_flw;
dec.rd = frd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_fsw(ireg5 rs1, freg5 frs2, offset12 simm12)
{
decode dec;
if (!(rs1.valid() && frs2.valid() && simm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsw;
dec.rs1 = rs1;
dec.rs2 = frs2;
dec.imm = simm12;
return encode_inst(dec);
}
uint64_t riscv::emit_fmadd_s(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmadd_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fmsub_s(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmsub_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fnmsub_s(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fnmsub_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fnmadd_s(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fnmadd_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fadd_s(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fadd_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fsub_s(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsub_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fmul_s(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmul_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fdiv_s(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fdiv_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fsgnj_s(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsgnj_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fsgnjn_s(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsgnjn_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fsgnjx_s(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsgnjx_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fmin_s(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmin_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fmax_s(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmax_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fsqrt_s(freg5 frd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsqrt_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fle_s(ireg5 rd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(rd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fle_s;
dec.rd = rd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_flt_s(ireg5 rd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(rd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_flt_s;
dec.rd = rd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_feq_s(ireg5 rd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(rd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_feq_s;
dec.rd = rd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_w_s(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_w_s;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_wu_s(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_wu_s;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_s_w(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_s_w;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_s_wu(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_s_wu;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fmv_x_s(ireg5 rd, freg5 frs1)
{
decode dec;
if (!(rd.valid() && frs1.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmv_x_s;
dec.rd = rd;
dec.rs1 = frs1;
return encode_inst(dec);
}
uint64_t riscv::emit_fclass_s(ireg5 rd, freg5 frs1)
{
decode dec;
if (!(rd.valid() && frs1.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fclass_s;
dec.rd = rd;
dec.rs1 = frs1;
return encode_inst(dec);
}
uint64_t riscv::emit_fmv_s_x(freg5 frd, ireg5 rs1)
{
decode dec;
if (!(frd.valid() && rs1.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmv_s_x;
dec.rd = frd;
dec.rs1 = rs1;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_l_s(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_l_s;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_lu_s(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_lu_s;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_s_l(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_s_l;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_s_lu(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_s_lu;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fld(freg5 frd, ireg5 rs1, offset12 oimm12)
{
decode dec;
if (!(frd.valid() && rs1.valid() && oimm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fld;
dec.rd = frd;
dec.rs1 = rs1;
dec.imm = oimm12;
return encode_inst(dec);
}
uint64_t riscv::emit_fsd(ireg5 rs1, freg5 frs2, offset12 simm12)
{
decode dec;
if (!(rs1.valid() && frs2.valid() && simm12.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsd;
dec.rs1 = rs1;
dec.rs2 = frs2;
dec.imm = simm12;
return encode_inst(dec);
}
uint64_t riscv::emit_fmadd_d(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmadd_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fmsub_d(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmsub_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fnmsub_d(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fnmsub_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fnmadd_d(freg5 frd, freg5 frs1, freg5 frs2, freg5 frs3, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && frs3.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fnmadd_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rs3 = frs3;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fadd_d(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fadd_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fsub_d(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsub_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fmul_d(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmul_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fdiv_d(freg5 frd, freg5 frs1, freg5 frs2, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fdiv_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fsgnj_d(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsgnj_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fsgnjn_d(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsgnjn_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fsgnjx_d(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsgnjx_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fmin_d(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmin_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fmax_d(freg5 frd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(frd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmax_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_s_d(freg5 frd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_s_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_d_s(freg5 frd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_d_s;
dec.rd = frd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fsqrt_d(freg5 frd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fsqrt_d;
dec.rd = frd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fle_d(ireg5 rd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(rd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fle_d;
dec.rd = rd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_flt_d(ireg5 rd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(rd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_flt_d;
dec.rd = rd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_feq_d(ireg5 rd, freg5 frs1, freg5 frs2)
{
decode dec;
if (!(rd.valid() && frs1.valid() && frs2.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_feq_d;
dec.rd = rd;
dec.rs1 = frs1;
dec.rs2 = frs2;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_w_d(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_w_d;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_wu_d(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_wu_d;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_d_w(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_d_w;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_d_wu(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_d_wu;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fclass_d(ireg5 rd, freg5 frs1)
{
decode dec;
if (!(rd.valid() && frs1.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fclass_d;
dec.rd = rd;
dec.rs1 = frs1;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_l_d(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_l_d;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_lu_d(ireg5 rd, freg5 frs1, arg3 rm)
{
decode dec;
if (!(rd.valid() && frs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_lu_d;
dec.rd = rd;
dec.rs1 = frs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fmv_x_d(ireg5 rd, freg5 frs1)
{
decode dec;
if (!(rd.valid() && frs1.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmv_x_d;
dec.rd = rd;
dec.rs1 = frs1;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_d_l(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_d_l;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fcvt_d_lu(freg5 frd, ireg5 rs1, arg3 rm)
{
decode dec;
if (!(frd.valid() && rs1.valid() && rm.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fcvt_d_lu;
dec.rd = frd;
dec.rs1 = rs1;
dec.rm = rm;
return encode_inst(dec);
}
uint64_t riscv::emit_fmv_d_x(freg5 frd, ireg5 rs1)
{
decode dec;
if (!(frd.valid() && rs1.valid())) return 0; /* illegal instruction */
dec.op = riscv_op_fmv_d_x;
dec.rd = frd;
dec.rs1 = rs1;
return encode_inst(dec);
}
| 24.249464 | 118 | 0.65264 | csail-csg |
6c2962777801cc4f90a55341e8dc85b7d16b4e25 | 15,223 | cpp | C++ | remodet_repository_wdh_part/src/caffe/remo/visualizer.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/src/caffe/remo/visualizer.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/src/caffe/remo/visualizer.cpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | #include "caffe/remo/visualizer.hpp"
namespace caffe {
static bool DRAW_HANDS = false;
template <typename Dtype>
Visualizer<Dtype>::Visualizer(cv::Mat& image, int max_display_size) {
const int width = image.cols;
const int height = image.rows;
const int maxsize = (width > height) ? width : height;
const Dtype ratio = (Dtype)max_display_size / maxsize;
const int display_width = static_cast<int>(width * ratio);
const int display_height = static_cast<int>(height * ratio);
cv::resize(image, image_, cv::Size(display_width,display_height), cv::INTER_LINEAR);
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(const BoundingBox<Dtype>& bbox, const int id) {
draw_bbox(0,255,0,bbox,id);
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(int r, int g, int b, const BoundingBox<Dtype>& bbox,
const int id) {
cv::Point top_left_pt(static_cast<int>(bbox.x1_ * image_.cols),
static_cast<int>(bbox.y1_ * image_.rows));
cv::Point bottom_right_pt(static_cast<int>(bbox.x2_ * image_.cols),
static_cast<int>(bbox.y2_ * image_.rows));
cv::rectangle(image_, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3);
// draw person id
if (id >= 1) {
cv::Point bottom_left_pt1(static_cast<int>(bbox.x1_ * image_.cols + 5),
static_cast<int>(bbox.y2_ * image_.rows - 5));
cv::Point bottom_left_pt2(static_cast<int>(bbox.x1_ * image_.cols + 3),
static_cast<int>(bbox.y2_ * image_.rows - 3));
char buffer[50];
snprintf(buffer, sizeof(buffer), "%d", id);
cv::putText(image_, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image_, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
}
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(const BoundingBox<Dtype>& bbox, const int id, cv::Mat* out_image) {
draw_bbox(0,255,0,bbox,id,out_image);
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(int r, int g, int b, const BoundingBox<Dtype>& bbox,
const int id, cv::Mat* out_image) {
cv::Mat image;
image_.copyTo(image);
cv::Point top_left_pt(static_cast<int>(bbox.x1_ * image.cols),
static_cast<int>(bbox.y1_ * image.rows));
cv::Point bottom_right_pt(static_cast<int>(bbox.x2_ * image.cols),
static_cast<int>(bbox.y2_ * image.rows));
cv::rectangle(image, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3);
// draw person id
if (id >= 1) {
cv::Point bottom_left_pt1(static_cast<int>(bbox.x1_ * image.cols + 5),
static_cast<int>(bbox.y2_ * image.rows - 5));
cv::Point bottom_left_pt2(static_cast<int>(bbox.x1_ * image.cols + 3),
static_cast<int>(bbox.y2_ * image.rows - 3));
char buffer[50];
snprintf(buffer, sizeof(buffer), "%d", id);
cv::putText(image, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
}
// output
*out_image = image;
}
template <typename Dtype>
void Visualizer<Dtype>::draw_hand(const PMeta<Dtype>& meta, cv::Mat* image) {
int re = 3, rw = 4;
// int le = 6, lw = 7;
Dtype scale_hand = 1;
// RIGHT
if (meta.kps[re].v > 0.05 && meta.kps[rw].v > 0.05) {
// draw right hand
// four corners
float xe = meta.kps[re].x;
float ye = meta.kps[re].y;
float xw = meta.kps[rw].x;
float yw = meta.kps[rw].y;
float dx = xw - xe;
float dy = yw - ye;
float norm = sqrt(dx*dx+dy*dy);
dx /= norm;
dy /= norm;
cv::Point2f p1,p2,p3,p4;
p1.x = xw + norm*scale_hand*dy*0.5*9/16;
p1.y = yw - norm*scale_hand*dx*0.5*9/16;
p2.x = xw - norm*scale_hand*dy*0.5*9/16;
p2.y = yw + norm*scale_hand*dx*0.5*9/16;
p3.x = p1.x + norm*scale_hand*dx;
p3.y = p1.y + norm*scale_hand*dy;
p4.x = p2.x + norm*scale_hand*dx;
p4.y = p2.y + norm*scale_hand*dy;
// get bbox
float xmin,ymin,xmax,ymax;
xmin = std::min(std::min(std::min(p1.x,p2.x),p3.x),p4.x);
xmin = std::min(std::max(xmin,float(0.)),float(1.));
ymin = std::min(std::min(std::min(p1.y,p2.y),p3.y),p4.y);
ymin = std::min(std::max(ymin,float(0.)),float(1.));
xmax = std::max(std::max(std::max(p1.x,p2.x),p3.x),p4.x);
xmax = std::min(std::max(xmax,float(0.)),float(1.));
ymax = std::max(std::max(std::max(p1.y,p2.y),p3.y),p4.y);
ymax = std::min(std::max(ymax,float(0.)),float(1.));
// get min square box include <...>
float cx = (xmin+xmax)/2;
float cy = (ymin+ymax)/2;
float wh = std::max(xmax-xmin,(ymax-ymin)*9/16);
xmin = cx - wh/2;
xmax = cx + wh/2;
ymin = cy - wh*16/9/2;
ymax = cy + wh*16/9/2;
xmin = std::min(std::max(xmin,float(0.)),float(1.));
ymin = std::min(std::max(ymin,float(0.)),float(1.));
xmax = std::min(std::max(xmax,float(0.)),float(1.));
ymax = std::min(std::max(ymax,float(0.)),float(1.));
cv::Point top_left_pt(xmin*image->cols,ymin*image->rows);
cv::Point bottom_right_pt(xmax*image->cols,ymax*image->rows);
cv::rectangle(*image, top_left_pt, bottom_right_pt, cv::Scalar(0,0,255), 3);
}
// LEFT
// if (meta.kps[le].v > 0.05 && meta.kps[lw].v > 0.05) {
// // draw left hand
// float xe = meta.kps[le].x;
// float ye = meta.kps[le].y;
// float xw = meta.kps[lw].x;
// float yw = meta.kps[lw].y;
// float dx = xw - xe;
// float dy = yw - ye;
// float norm = sqrt(dx*dx+dy*dy);
// dx /= norm;
// dy /= norm;
// cv::Point2f p1,p2,p3,p4;
// p1.x = xw + norm*scale_hand*dy*0.5*9/16;
// p1.y = yw - norm*scale_hand*dx*0.5*9/16;
// p2.x = xw - norm*scale_hand*dy*0.5*9/16;
// p2.y = yw + norm*scale_hand*dx*0.5*9/16;
// p3.x = p1.x + norm*scale_hand*dx;
// p3.y = p1.y + norm*scale_hand*dy;
// p4.x = p2.x + norm*scale_hand*dx;
// p4.y = p2.y + norm*scale_hand*dy;
// // get bbox
// float xmin,ymin,xmax,ymax;
// xmin = std::min(std::min(std::min(p1.x,p2.x),p3.x),p4.x);
// xmin = std::min(std::max(xmin,float(0.)),float(1.));
// ymin = std::min(std::min(std::min(p1.y,p2.y),p3.y),p4.y);
// ymin = std::min(std::max(ymin,float(0.)),float(1.));
// xmax = std::max(std::max(std::max(p1.x,p2.x),p3.x),p4.x);
// xmax = std::min(std::max(xmax,float(0.)),float(1.));
// ymax = std::max(std::max(std::max(p1.y,p2.y),p3.y),p4.y);
// ymax = std::min(std::max(ymax,float(0.)),float(1.));
// // get min square box include <...>
// float cx = (xmin+xmax)/2;
// float cy = (ymin+ymax)/2;
// float wh = std::max(xmax-xmin,(ymax-ymin)*9/16);
// xmin = cx - wh/2;
// xmax = cx + wh/2;
// ymin = cy - wh*16/9/2;
// ymax = cy + wh*16/9/2;
// xmin = std::min(std::max(xmin,float(0.)),float(1.));
// ymin = std::min(std::max(ymin,float(0.)),float(1.));
// xmax = std::min(std::max(xmax,float(0.)),float(1.));
// ymax = std::min(std::max(ymax,float(0.)),float(1.));
// cv::Point top_left_pt(xmin*image->cols,ymin*image->rows);
// cv::Point bottom_right_pt(xmax*image->cols,ymax*image->rows);
// cv::rectangle(*image, top_left_pt, bottom_right_pt, cv::Scalar(0,0,255), 3);
// }
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(const vector<PMeta<Dtype> >& meta) {
draw_bbox(0,255,0,DRAW_HANDS,meta);
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(int r, int g, int b, bool draw_hands, const vector<PMeta<Dtype> >& meta) {
if (meta.size() == 0) return;
for (int i = 0; i < meta.size(); ++i) {
const BoundingBox<Dtype>& bbox = meta[i].bbox;
const int id = meta[i].id;
const Dtype similarity = meta[i].similarity;
const Dtype max_back_similarity = meta[i].max_back_similarity;
int xmin = (int)(bbox.x1_*image_.cols);
int xmax = (int)(bbox.x2_*image_.cols);
int ymin = (int)(bbox.y1_*image_.rows);
int ymax = (int)(bbox.y2_*image_.rows);
xmin = std::max(std::min(xmin,image_.cols-1),0);
xmax = std::max(std::min(xmax,image_.cols-1),0);
ymin = std::max(std::min(ymin,image_.rows-1),0);
ymax = std::max(std::min(ymax,image_.rows-1),0);
cv::Point top_left_pt(xmin,ymin);
cv::Point bottom_right_pt(xmax,ymax);
cv::rectangle(image_, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3);
//--------------------------------------------------------------------------
if (draw_hands) {
draw_hand(meta[i],&image_);
}
//--------------------------------------------------------------------------
if (id >= 1) {
// id
cv::Point bottom_left_pt1(xmin+5,ymax-5);
cv::Point bottom_left_pt2(xmin+3,ymax-3);
char buffer[50];
snprintf(buffer, sizeof(buffer), "%d", id);
cv::putText(image_, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image_, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
// similarity
cv::Point bottom_right_pt1(xmax-150,ymax-5);
cv::Point bottom_right_pt2(xmax-148,ymax-3);
char sm_buffer[50];
snprintf(sm_buffer, sizeof(sm_buffer), "%.2f/%.2f", (float)similarity, (float)max_back_similarity);
cv::putText(image_, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image_, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
}
}
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(const vector<PMeta<Dtype> >& meta,
cv::Mat* out_image) {
draw_bbox(0,255,0,DRAW_HANDS,meta,out_image);
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(int r, int g, int b, bool draw_hands, const vector<PMeta<Dtype> >& meta,
cv::Mat* out_image) {
cv::Mat image;
image_.copyTo(image);
if (meta.size() > 0) {
for (int i = 0; i < meta.size(); ++i) {
const BoundingBox<Dtype>& bbox = meta[i].bbox;
const int id = meta[i].id;
const Dtype similarity = meta[i].similarity;
const Dtype max_back_similarity = meta[i].max_back_similarity;
int xmin = (int)(bbox.x1_*image.cols);
int xmax = (int)(bbox.x2_*image.cols);
int ymin = (int)(bbox.y1_*image.rows);
int ymax = (int)(bbox.y2_*image.rows);
xmin = std::max(std::min(xmin,image.cols-1),0);
xmax = std::max(std::min(xmax,image.cols-1),0);
ymin = std::max(std::min(ymin,image.rows-1),0);
ymax = std::max(std::min(ymax,image.rows-1),0);
cv::Point top_left_pt(xmin,ymin);
cv::Point bottom_right_pt(xmax,ymax);
cv::rectangle(image, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3);
//------------------------------------------------------------------------
// draw hands
if (draw_hands) {
draw_hand(meta[i],&image);
}
//------------------------------------------------------------------------
if (id >= 1) {
cv::Point bottom_left_pt1(xmin+5,ymax-5);
cv::Point bottom_left_pt2(xmin+3,ymax-3);
char buffer[50];
snprintf(buffer, sizeof(buffer), "%d", id);
cv::putText(image, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
// similarity
cv::Point bottom_right_pt1(xmax-150,ymax-5);
cv::Point bottom_right_pt2(xmax-148,ymax-3);
char sm_buffer[50];
snprintf(sm_buffer, sizeof(sm_buffer), "%.2f/%.2f", (float)similarity, (float)max_back_similarity);
cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
}
}
*out_image = image;
} else {
*out_image = image;
}
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(const vector<PMeta<Dtype> >& meta,
const cv::Mat& src_image, cv::Mat* out_image) {
draw_bbox(0,255,0,DRAW_HANDS,meta,src_image,out_image);
}
template <typename Dtype>
void Visualizer<Dtype>::draw_bbox(int r, int g, int b, bool draw_hands, const vector<PMeta<Dtype> >& meta,
const cv::Mat& src_image, cv::Mat* out_image) {
cv::Mat image;
src_image.copyTo(image);
if (meta.size() > 0) {
for (int i = 0; i < meta.size(); ++i) {
const BoundingBox<Dtype>& bbox = meta[i].bbox;
const int id = meta[i].id;
const Dtype similarity = meta[i].similarity;
const Dtype max_back_similarity = meta[i].max_back_similarity;
int xmin = (int)(bbox.x1_*image.cols);
int xmax = (int)(bbox.x2_*image.cols);
int ymin = (int)(bbox.y1_*image.rows);
int ymax = (int)(bbox.y2_*image.rows);
xmin = std::max(std::min(xmin,image.cols-1),0);
xmax = std::max(std::min(xmax,image.cols-1),0);
ymin = std::max(std::min(ymin,image.rows-1),0);
ymax = std::max(std::min(ymax,image.rows-1),0);
cv::Point top_left_pt(xmin,ymin);
cv::Point bottom_right_pt(xmax,ymax);
cv::rectangle(image, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3);
// -----------------------------------------------------------------------
// draw hands
if (draw_hands) {
draw_hand(meta[i],&image);
}
// -----------------------------------------------------------------------
if (id >= 1) {
cv::Point bottom_left_pt1(xmin+5,ymax-5);
cv::Point bottom_left_pt2(xmin+3,ymax-3);
char buffer[50];
snprintf(buffer, sizeof(buffer), "%d", id);
cv::putText(image, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
// similarity
cv::Point bottom_right_pt1(xmax-150,ymax-5);
cv::Point bottom_right_pt2(xmax-148,ymax-3);
char sm_buffer[50];
snprintf(sm_buffer, sizeof(sm_buffer), "%.2f/%.2f", (float)similarity, (float)max_back_similarity);
cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2);
cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2);
}
}
*out_image = image;
} else {
*out_image = image;
}
}
template <typename Dtype>
void Visualizer<Dtype>::save(const cv::Mat& image, const std::string& save_dir, const int image_id) {
char imagename [256];
sprintf(imagename, "%s/%10d.jpg", save_dir.c_str(), image_id);
cv::imwrite(imagename, image);
}
template <typename Dtype>
void Visualizer<Dtype>::save(const std::string& save_dir, const int image_id) {
char imagename [256];
sprintf(imagename, "%s/%10d.jpg", save_dir.c_str(), image_id);
cv::imwrite(imagename, image_);
}
INSTANTIATE_CLASS(Visualizer);
}
| 43.247159 | 116 | 0.591605 | UrwLee |
6c2a6a022e735a4a6e358275906b4d5a5dbecc8d | 956 | hpp | C++ | include/h3api/H3AdventureMap/H3MapOceanBottle.hpp | Patrulek/H3API | 91f10de37c6b86f3160706c1fdf4792f927e9952 | [
"MIT"
] | 14 | 2020-09-07T21:49:26.000Z | 2021-11-29T18:09:41.000Z | include/h3api/H3AdventureMap/H3MapOceanBottle.hpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 2 | 2021-02-12T15:52:31.000Z | 2021-02-12T16:21:24.000Z | include/h3api/H3AdventureMap/H3MapOceanBottle.hpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 8 | 2021-02-12T15:52:41.000Z | 2022-01-31T15:28:10.000Z | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// rosekavalierhc@gmail.com //
// Created or last updated on: 2021-02-02 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#pragma once
#include "h3api/H3Base.hpp"
#include "h3api/H3AdventureMap/H3MapSign.hpp"
namespace h3
{
_H3API_DECLARE_(MapitemOceanBottle);
#pragma pack(push, 4)
struct H3OceanBottle : H3Signpost
{
};
struct H3MapitemOceanBottle : H3MapitemSign
{
};
#pragma pack(pop) /* align-4 */
} /* namespace h3 */
| 28.969697 | 70 | 0.384937 | Patrulek |
6c2d2289ef49a99011d46242b204db085668532a | 1,655 | hpp | C++ | include/UnityEngine/ProBuilder/IHasDefault.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/UnityEngine/ProBuilder/IHasDefault.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/UnityEngine/ProBuilder/IHasDefault.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/byref.hpp"
// Completed includes
// Type namespace: UnityEngine.ProBuilder
namespace UnityEngine::ProBuilder {
// Forward declaring type: IHasDefault
class IHasDefault;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::UnityEngine::ProBuilder::IHasDefault);
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::ProBuilder::IHasDefault*, "UnityEngine.ProBuilder", "IHasDefault");
// Type namespace: UnityEngine.ProBuilder
namespace UnityEngine::ProBuilder {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.ProBuilder.IHasDefault
// [TokenAttribute] Offset: FFFFFFFF
class IHasDefault {
public:
// public System.Void SetDefaultValues()
// Offset: 0xFFFFFFFFFFFFFFFF
void SetDefaultValues();
}; // UnityEngine.ProBuilder.IHasDefault
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::ProBuilder::IHasDefault::SetDefaultValues
// Il2CppName: SetDefaultValues
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ProBuilder::IHasDefault::*)()>(&UnityEngine::ProBuilder::IHasDefault::SetDefaultValues)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::IHasDefault*), "SetDefaultValues", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 42.435897 | 179 | 0.713595 | RedBrumbler |
6c2f3c41138479b0abd7e08d47e7020ba98a911c | 1,443 | cpp | C++ | Final/Final/UI/ItemUserWidget.cpp | GZhonghui/Intern2022 | f1b8ea0bb0dc98c1a5ca96b07b327352bef27a7e | [
"MIT"
] | 1 | 2022-02-25T06:07:35.000Z | 2022-02-25T06:07:35.000Z | Final/Final/UI/ItemUserWidget.cpp | GZhonghui/Intern2022 | f1b8ea0bb0dc98c1a5ca96b07b327352bef27a7e | [
"MIT"
] | null | null | null | Final/Final/UI/ItemUserWidget.cpp | GZhonghui/Intern2022 | f1b8ea0bb0dc98c1a5ca96b07b327352bef27a7e | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "ItemUserWidget.h"
void UItemUserWidget::UpdateArms()
{
WearMe.ExecuteIfBound(SaveID);
}
void UItemUserWidget::GetUpdate()
{
MeUpdated.ExecuteIfBound();
}
void UItemUserWidget::Set(int ItemID, int Count)
{
auto GI = Cast<UMainGameInstance>(GetGameInstance());
if (GI)
{
if (GI->ItemsName.Contains(ItemID))
{
FString ImagePath = GI->ItemsIconPath[ItemID];
UTexture2D* Texture = Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(ImagePath)));
ImageIcon->SetBrushFromTexture(Texture);
if (Count) ItemNumber->SetText(FText::FromString(FString::FromInt(Count)));
else ItemNumber->SetText(FText::FromString(""));
SaveID = ItemID;
SaveNumber = Count;
}
}
}
int UItemUserWidget::CanRightClick()
{
auto GI = Cast<UMainGameInstance>(GetGameInstance());
if (GI)
{
if (GI->ItemsName.Contains(SaveID) && SaveNumber && GI->ItemsUsage[SaveID])
{
return GI->ItemsUsage[SaveID];
}
else return 0;
}
return 0;
}
class TSubclassOf<AActor> UItemUserWidget::GetWearableClass()
{
auto GI = Cast<UMainGameInstance>(GetGameInstance());
TSubclassOf<AActor> EmptyResult;
if (GI)
{
if (GI->ItemsMesh.Contains(SaveID))
{
return GI->ItemsMesh[SaveID];
}
else return EmptyResult;
}
return EmptyResult;
}
void UItemUserWidget::UseOne()
{
SaveNumber -= 1;
MeUpdated.ExecuteIfBound();
} | 19.24 | 107 | 0.710326 | GZhonghui |
6c30ab0fe4f19b91cafd968cff6bae99acb31d67 | 3,722 | hpp | C++ | include/knapsack/branch_and_bound.hpp | fhamonic/knapsack | c5105720b3770fc76d54f14d5001fcc7ac3ec69a | [
"BSL-1.0"
] | 1 | 2021-09-23T09:49:15.000Z | 2021-09-23T09:49:15.000Z | include/knapsack/branch_and_bound.hpp | fhamonic/knapsack | c5105720b3770fc76d54f14d5001fcc7ac3ec69a | [
"BSL-1.0"
] | null | null | null | include/knapsack/branch_and_bound.hpp | fhamonic/knapsack | c5105720b3770fc76d54f14d5001fcc7ac3ec69a | [
"BSL-1.0"
] | null | null | null | #ifndef FHAMONIC_KNAPSACK_BRANCH_AND_BOUND_HPP
#define FHAMONIC_KNAPSACK_BRANCH_AND_BOUND_HPP
#include <numeric>
#include <stack>
#include <vector>
#include <range/v3/algorithm/remove_if.hpp>
#include <range/v3/algorithm/sort.hpp>
#include <range/v3/view/zip.hpp>
#include "knapsack/instance.hpp"
#include "knapsack/solution.hpp"
namespace fhamonic {
namespace knapsack {
template <typename Value, typename Cost>
class BranchAndBound {
public:
using TInstance = Instance<Value, Cost>;
using TItem = typename TInstance::Item;
using TSolution = Solution<Value, Cost>;
private:
double computeUpperBound(const std::vector<TItem> & sorted_items,
std::size_t depth, Value bound_value,
Cost bound_budget_left) {
for(; depth < sorted_items.size(); ++depth) {
const TItem & item = sorted_items[depth];
if(bound_budget_left <= item.cost)
return bound_value + bound_budget_left * item.getRatio();
bound_budget_left -= item.cost;
bound_value += item.value;
}
return bound_value;
}
std::stack<std::size_t> iterative_bnb(
const std::vector<TItem> & sorted_items, Cost budget_left) {
const std::size_t nb_items = sorted_items.size();
std::size_t depth = 0;
Value value = 0;
Value best_value = 0;
std::stack<std::size_t> stack;
std::stack<std::size_t> best_stack;
goto begin;
backtrack:
while(!stack.empty()) {
depth = stack.top();
stack.pop();
value -= sorted_items[depth].value;
budget_left += sorted_items[depth].cost;
for(++depth; depth < nb_items; ++depth) {
if(budget_left < sorted_items[depth].cost) continue;
if(computeUpperBound(sorted_items, depth, value, budget_left) <=
best_value)
goto backtrack;
begin:
value += sorted_items[depth].value;
budget_left -= sorted_items[depth].cost;
stack.push(depth);
}
if(value <= best_value) continue;
best_value = value;
best_stack = stack;
}
return best_stack;
}
public:
BranchAndBound() {}
TSolution solve(const TInstance & instance) {
TSolution solution(instance);
if(instance.itemCount() > 0) {
std::vector<TItem> sorted_items = instance.getItems();
std::vector<int> permuted_id(instance.itemCount());
std::iota(permuted_id.begin(), permuted_id.end(), 0);
auto zip_view = ranges::view::zip(sorted_items, permuted_id);
auto end = ranges::remove_if(zip_view, [&](const auto & r) {
return r.first.cost > instance.getBudget();
});
const ptrdiff_t new_size = std::distance(zip_view.begin(), end);
sorted_items.erase(sorted_items.begin() + new_size,
sorted_items.end());
permuted_id.erase(permuted_id.begin() + new_size,
permuted_id.end());
ranges::sort(zip_view,
[](auto p1, auto p2) { return p1.first < p2.first; });
std::stack<std::size_t> best_stack =
iterative_bnb(sorted_items, instance.getBudget());
while(!best_stack.empty()) {
solution.add(permuted_id[best_stack.top()]);
best_stack.pop();
}
}
return solution;
}
};
} // namespace knapsack
} // namespace fhamonic
#endif // FHAMONIC_KNAPSACK_BRANCH_AND_BOUND_HPP | 34.785047 | 80 | 0.577646 | fhamonic |
6c344fb83abb466ca791d120fe3a3836d79f8607 | 1,895 | cpp | C++ | generated-sources/cpp-qt5/mojang-api/client/com.github.asyncmc.mojang.api.cpp.qt5.model/OAISecurityAnswer.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/cpp-qt5/mojang-api/client/com.github.asyncmc.mojang.api.cpp.qt5.model/OAISecurityAnswer.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/cpp-qt5/mojang-api/client/com.github.asyncmc.mojang.api.cpp.qt5.model/OAISecurityAnswer.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | /**
* Mojang API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 2020-06-05
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAISecurityAnswer.h"
#include "OAIHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace OpenAPI {
OAISecurityAnswer::OAISecurityAnswer(QString json) {
init();
this->fromJson(json);
}
OAISecurityAnswer::OAISecurityAnswer() {
init();
}
OAISecurityAnswer::~OAISecurityAnswer() {
this->cleanup();
}
void
OAISecurityAnswer::init() {
id = 0;
m_id_isSet = false;
}
void
OAISecurityAnswer::cleanup() {
}
OAISecurityAnswer*
OAISecurityAnswer::fromJson(QString json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
OAISecurityAnswer::fromJsonObject(QJsonObject pJson) {
::OpenAPI::setValue(&id, pJson["id"], "qint32", "");
}
QString
OAISecurityAnswer::asJson ()
{
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject
OAISecurityAnswer::asJsonObject() {
QJsonObject obj;
if(m_id_isSet){
obj.insert("id", QJsonValue(id));
}
return obj;
}
qint32
OAISecurityAnswer::getId() {
return id;
}
void
OAISecurityAnswer::setId(qint32 id) {
this->id = id;
this->m_id_isSet = true;
}
bool
OAISecurityAnswer::isSet(){
bool isObjectUpdated = false;
do{
if(m_id_isSet){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| 18.221154 | 109 | 0.686544 | AsyncMC |
6c38a6065b6bb78c7d8bd2ac427691d52e72586a | 3,105 | cpp | C++ | 3.7.0/clang-tools-extra-3.7.0.src/clang-tidy/google/IntegerTypesCheck.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 3 | 2016-02-10T14:18:40.000Z | 2018-02-05T03:15:56.000Z | 3.7.0/clang-tools-extra-3.7.0.src/clang-tidy/google/IntegerTypesCheck.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 1 | 2016-02-10T15:40:03.000Z | 2016-02-10T15:40:03.000Z | 3.7.0/clang-tools-extra-3.7.0.src/clang-tidy/google/IntegerTypesCheck.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | null | null | null | //===--- IntegerTypesCheck.cpp - clang-tidy -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IntegerTypesCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/TargetInfo.h"
namespace clang {
namespace tidy {
namespace google {
namespace runtime {
using namespace ast_matchers;
void IntegerTypesCheck::registerMatchers(MatchFinder *Finder) {
// Find all TypeLocs.
Finder->addMatcher(typeLoc().bind("tl"), this);
}
void IntegerTypesCheck::check(const MatchFinder::MatchResult &Result) {
// The relevant Style Guide rule only applies to C++.
if (!Result.Context->getLangOpts().CPlusPlus)
return;
auto TL = *Result.Nodes.getNodeAs<TypeLoc>("tl");
SourceLocation Loc = TL.getLocStart();
if (Loc.isInvalid() || Loc.isMacroID())
return;
// Look through qualification.
if (auto QualLoc = TL.getAs<QualifiedTypeLoc>())
TL = QualLoc.getUnqualifiedLoc();
auto BuiltinLoc = TL.getAs<BuiltinTypeLoc>();
if (!BuiltinLoc)
return;
bool IsSigned;
unsigned Width;
const TargetInfo &TargetInfo = Result.Context->getTargetInfo();
// Look for uses of short, long, long long and their unsigned versions.
switch (BuiltinLoc.getTypePtr()->getKind()) {
case BuiltinType::Short:
Width = TargetInfo.getShortWidth();
IsSigned = true;
break;
case BuiltinType::Long:
Width = TargetInfo.getLongWidth();
IsSigned = true;
break;
case BuiltinType::LongLong:
Width = TargetInfo.getLongLongWidth();
IsSigned = true;
break;
case BuiltinType::UShort:
Width = TargetInfo.getShortWidth();
IsSigned = false;
break;
case BuiltinType::ULong:
Width = TargetInfo.getLongWidth();
IsSigned = false;
break;
case BuiltinType::ULongLong:
Width = TargetInfo.getLongLongWidth();
IsSigned = false;
break;
default:
return;
}
// We allow "unsigned short port" as that's reasonably common and required by
// the sockets API.
const StringRef Port = "unsigned short port";
const char *Data = Result.SourceManager->getCharacterData(Loc);
if (!std::strncmp(Data, Port.data(), Port.size()) &&
!isIdentifierBody(Data[Port.size()]))
return;
std::string Replacement =
((IsSigned ? SignedTypePrefix : UnsignedTypePrefix) + Twine(Width) +
(AddUnderscoreT ? "_t" : "")).str();
// We don't add a fix-it as changing the type can easily break code,
// e.g. when a function requires a 'long' argument on all platforms.
// QualTypes are printed with implicit quotes.
diag(Loc, "consider replacing %0 with '%1'") << BuiltinLoc.getType()
<< Replacement;
}
} // namespace runtime
} // namespace google
} // namespace tidy
} // namespace clang
| 29.571429 | 80 | 0.655395 | androm3da |
6c396882b41745ec719bb3277321f334a8d14ff9 | 558 | cpp | C++ | test/20171018/source/std/test20171018/source/sxy/sequence/rand.cpp | DesZou/Eros | f49c9ce1dfe193de8199163286afc28ff8c52eef | [
"MIT"
] | 1 | 2017-10-12T13:49:10.000Z | 2017-10-12T13:49:10.000Z | test/20171018/source/std/test20171018/source/sxy/sequence/rand.cpp | DesZou/Eros | f49c9ce1dfe193de8199163286afc28ff8c52eef | [
"MIT"
] | null | null | null | test/20171018/source/std/test20171018/source/sxy/sequence/rand.cpp | DesZou/Eros | f49c9ce1dfe193de8199163286afc28ff8c52eef | [
"MIT"
] | 1 | 2017-10-12T13:49:38.000Z | 2017-10-12T13:49:38.000Z | //Serene
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<ctime>
using namespace std;
const int n=200000,f=100,q=200000;
int m,k;
int main() {
freopen("sequence.in","w",stdout);
srand((unsigned)time(NULL));
m=rand()%f+1;k=rand()%(n/4)+1;
cout<<n<<" "<<m<<" "<<k<<"\n";
int x,y;
for(int i=1;i<=n;++i) {
x=rand()%f+1;
cout<<x<<" ";
}
cout<<"\n"<<q<<"\n";
for(int i=1;i<=q;++i) {
x=rand()%n+1;
if(x!=n) y=rand()%(n-x+1); else y=0;
cout<<x<<" "<<x+y<<"\n";
}
return 0;
}
| 17.4375 | 38 | 0.557348 | DesZou |
6c3d3e4d198a428c654c1703399d7755f6c7c411 | 6,836 | cpp | C++ | examples/EchoClientServer.cpp | whamon35/NetTcp | db49b774abadde40132058040fdf92b60ae178c2 | [
"MIT"
] | 3 | 2020-05-16T14:00:40.000Z | 2022-03-16T10:09:37.000Z | examples/EchoClientServer.cpp | whamon35/NetTcp | db49b774abadde40132058040fdf92b60ae178c2 | [
"MIT"
] | null | null | null | examples/EchoClientServer.cpp | whamon35/NetTcp | db49b774abadde40132058040fdf92b60ae178c2 | [
"MIT"
] | 1 | 2022-02-25T10:49:12.000Z | 2022-02-25T10:49:12.000Z |
// ─────────────────────────────────────────────────────────────
// INCLUDE
// ─────────────────────────────────────────────────────────────
#include <MyServer.hpp>
#include <MySocket.hpp>
// Dependencies
#include <Net/Tcp/NetTcp.hpp>
#include <spdlog/sinks/stdout_color_sinks.h>
#ifdef _MSC_VER
# include <spdlog/sinks/msvc_sink.h>
#endif
// Qt
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QTimer>
// ─────────────────────────────────────────────────────────────
// DECLARATION
// ─────────────────────────────────────────────────────────────
std::shared_ptr<spdlog::logger> appLog = std::make_shared<spdlog::logger>("app");
std::shared_ptr<spdlog::logger> serverLog = std::make_shared<spdlog::logger>("server");
std::shared_ptr<spdlog::logger> clientLog = std::make_shared<spdlog::logger>("client");
class App
{
public:
int counter = 0;
uint16_t port = 9999;
QString ip = QStringLiteral("127.0.0.1");
MyServer server;
MySocket client;
bool multiThreaded = false;
QTimer timer;
public:
void start()
{
appLog->info("Init application");
server.multiThreaded = multiThreaded;
// Send Echo counter every seconds
QObject::connect(&timer, &QTimer::timeout,
[this]()
{
if(client.isConnected())
{
Q_EMIT client.sendString("Echo " + QString::number(counter++));
}
});
// Print the message that echoed from server socket
QObject::connect(&client, &MySocket::stringReceived,
[this](const QString value)
{
clientLog->info("Rx \"{}\" from server {}:{}", qPrintable(value), qPrintable(client.peerAddress()),
signed(client.peerPort()));
});
// Print the message that received from client socket
QObject::connect(&server, &MyServer::stringReceived,
[](const QString value, const QString address, const quint16 port)
{ serverLog->info("Rx \"{}\" from server {}:{}", qPrintable(value), qPrintable(address), port); });
QObject::connect(
&server, &net::tcp::Server::isRunningChanged, [](bool value) { serverLog->info("isRunning : {}", value); });
QObject::connect(&server, &net::tcp::Server::isListeningChanged,
[](bool value) { serverLog->info("isBounded : {}", value); });
QObject::connect(
&client, &net::tcp::Socket::isRunningChanged, [](bool value) { clientLog->info("isRunning : {}", value); });
QObject::connect(&client, &net::tcp::Socket::isConnectedChanged,
[this](bool value)
{
clientLog->info("isConnected : {}", value);
// Reset counter at connection/disconnection
counter = 0;
});
QObject::connect(&server, &net::tcp::Server::acceptError,
[](int value, const QString& error) { serverLog->error("accept error : {}", error.toStdString()); });
QObject::connect(&client, &net::tcp::Socket::socketError,
[](int value, const QString& error) { clientLog->error("socket error : {}", error.toStdString()); });
QObject::connect(&server, &net::tcp::Server::newClient,
[](const QString& address, const quint16 port)
{ serverLog->info("New Client {}:{}", qPrintable(address), signed(port)); });
QObject::connect(&server, &net::tcp::Server::clientLost,
[](const QString& address, const quint16 port)
{ serverLog->info("Client Disconnected {}:{}", qPrintable(address), signed(port)); });
QObject::connect(&client, &net::tcp::Socket::txBytesTotalChanged,
[](quint64 total) { clientLog->info("Sent bytes : {}", total); });
serverLog->info("Start server on address {}:{}", qPrintable(ip), signed(port));
// server.start(port) can be called to listen from every interfaces
server.start(ip, port);
client.setUseWorkerThread(multiThreaded);
clientLog->info("Start client to connect to address {}, on port {}", qPrintable(ip), signed(port));
client.start(ip, port);
appLog->info("Start application");
timer.start(1);
}
};
static void installLoggers()
{
#ifdef _MSC_VER
const auto msvcSink = std::make_shared<spdlog::sinks::msvc_sink_mt>();
msvcSink->set_level(spdlog::level::debug);
net::tcp::Logger::registerSink(msvcSink);
appLog->sinks().emplace_back(msvcSink);
clientLog->sinks().emplace_back(msvcSink);
serverLog->sinks().emplace_back(msvcSink);
#endif
const auto stdoutSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
stdoutSink->set_level(spdlog::level::debug);
net::tcp::Logger::registerSink(stdoutSink);
appLog->sinks().emplace_back(stdoutSink);
clientLog->sinks().emplace_back(stdoutSink);
serverLog->sinks().emplace_back(stdoutSink);
}
int main(int argc, char* argv[])
{
installLoggers();
QCoreApplication app(argc, argv);
// ────────── COMMAND PARSER ──────────────────────────────────────
QCommandLineParser parser;
parser.setApplicationDescription("Echo Client Server");
parser.addHelpOption();
QCommandLineOption multiThreadOption(QStringList() << "t",
QCoreApplication::translate("main", "Make the worker live in a different thread. Default false"));
parser.addOption(multiThreadOption);
QCommandLineOption portOption(QStringList() << "s"
<< "src",
QCoreApplication::translate("main", "Port for rx packet. Default \"9999\"."),
QCoreApplication::translate("main", "port"));
portOption.setDefaultValue("9999");
parser.addOption(portOption);
QCommandLineOption ipOption(QStringList() << "i"
<< "ip",
QCoreApplication::translate("main", "Ip address of multicast group. Default \"127.0.0.1\""),
QCoreApplication::translate("main", "ip"));
ipOption.setDefaultValue(QStringLiteral("127.0.0.1"));
parser.addOption(ipOption);
// Process the actual command line arguments given by the user
parser.process(app);
// ────────── APPLICATION ──────────────────────────────────────
// Register types for to use SharedDatagram in signals
net::tcp::registerQmlTypes();
// Create the app and start it
App echo;
bool ok;
const auto port = parser.value(portOption).toInt(&ok);
if(ok)
echo.port = port;
const auto ip = parser.value(ipOption);
if(!ip.isEmpty())
echo.ip = ip;
echo.multiThreaded = parser.isSet(multiThreadOption);
echo.start();
// Start event loop
return QCoreApplication::exec();
}
| 36.951351 | 120 | 0.581773 | whamon35 |
6c3f945302ef140ba265e55112522a7cb3521338 | 1,131 | cpp | C++ | pulse_integration_quality_analysis/one_value_per_cycle/pulse_integration_quality_analysis_test_bench.cpp | knodel/hzdr-mu2e-daq-algo-cores | ae646f66e3b71ef7b06013b4d835cc61d1221ffc | [
"BSD-3-Clause"
] | 1 | 2020-11-17T15:21:04.000Z | 2020-11-17T15:21:04.000Z | pulse_integration_quality_analysis/one_value_per_cycle/pulse_integration_quality_analysis_test_bench.cpp | knodel/hzdr-mu2e-daq-algo-cores | ae646f66e3b71ef7b06013b4d835cc61d1221ffc | [
"BSD-3-Clause"
] | null | null | null | pulse_integration_quality_analysis/one_value_per_cycle/pulse_integration_quality_analysis_test_bench.cpp | knodel/hzdr-mu2e-daq-algo-cores | ae646f66e3b71ef7b06013b4d835cc61d1221ffc | [
"BSD-3-Clause"
] | null | null | null | #include "pulse_integration_quality_analysis_core.h"
#include "stdio.h"
int main(int argc, char* argv[]){
in_stream_t in;
out_stream_t out;
report result;
double value = 0;
FILE* file = NULL;
if(argc >= 2) file = fopen(argv[1], "r");
else file = fopen("", "r");
if(file == NULL){
perror("\n\nUnable to open input file!");
return 1;
}
printf("file opened\n");
//read file
for(int i=0; i<data_len; i++){
if(fscanf(file, "%lf", &value) != 1) printf("file too short\n");
in << value;
}
fclose(file);
file = NULL;
printf("data read\n");
//execute core
analysis_core(in, out, trigger_delay_);
printf("core executed\n");
//print results
if(argc == 3){
file = fopen(argv[2], "w");
if(!file) perror("output file not opened!");
}
printf("results:\n");
while(!out.empty()){
out >> result;
//printf(" energy: %f, time: %d, quality: %d\n", result.pulse_energy, result.pulse_time, result.quality);
printf("%f\t%d\t%d\n", result.pulse_energy, result.pulse_time, result.quality);
if(file) fprintf(file, "%d\t%f\t%d\n", result.pulse_time, result.pulse_energy, result.quality);
}
return 0;
}
| 22.62 | 109 | 0.639257 | knodel |
6c4170bbef711dac041c5778430bfde2bf5a3345 | 4,095 | hpp | C++ | src/compiler/syntax/token.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 10 | 2020-01-23T20:41:19.000Z | 2021-12-28T20:24:44.000Z | src/compiler/syntax/token.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 22 | 2021-03-25T16:22:08.000Z | 2022-03-17T12:50:38.000Z | src/compiler/syntax/token.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | null | null | null | #ifndef TIRO_COMPILER_SYNTAX_TOKEN_HPP
#define TIRO_COMPILER_SYNTAX_TOKEN_HPP
#include "common/format.hpp"
#include "compiler/source_range.hpp"
#include <string_view>
namespace tiro {
/// List of all known tokens.
///
/// Note: if you add a new keyword, you will likely want to
/// add the string --> token_type mapping in lexer.cpp (keywords_table) as well.
enum class TokenType : u8 {
Unexpected = 0, // Unexpected character
Eof,
Comment,
// Primitives
Identifier, // ordinary variable names
Symbol, // #name
Integer, // 0 1 0x123 0b0100 0o456
Float, // 123.456
TupleField, // tuple index after dot, e.g. the "1" in "a.1"
// Strings
StringStart, // ' or "
StringContent, // raw string literal content
StringVar, // $ single identifier follows
StringBlockStart, // ${ terminated by StringBlockEnd
StringBlockEnd, // }
StringEnd, // matching ' or "
// Keywords
KwAssert,
KwBreak,
KwConst,
KwContinue,
KwDefer,
KwElse,
KwExport,
KwFalse,
KwFor,
KwFunc,
KwIf,
KwImport,
KwIn,
KwNull,
KwReturn,
KwTrue,
KwVar,
KwWhile,
// Contextual keywords
KwMap,
KwSet,
// Reserved
KwAs,
KwCatch,
KwClass,
KwInterface,
KwIs,
KwPackage,
KwProtocol,
KwScope,
KwStruct,
KwSwitch,
KwThrow,
KwTry,
KwYield,
// Braces
LeftParen, // (
RightParen, // )
LeftBracket, // [
RightBracket, // ]
LeftBrace, // {
RightBrace, // }
// Operators
Dot, // .
Comma, // ,
Colon, // :
Semicolon, // ;
Question, // ?
QuestionDot, // ?.
QuestionLeftParen, // ?(
QuestionLeftBracket, // ?[
QuestionQuestion, // ??
Plus, // +
Minus, // -
Star, // *
StarStar, // **
Slash, // /
Percent, // %
PlusEquals, // +=
MinusEquals, // -=
StarEquals, // *=
StarStarEquals, // **=
SlashEquals, // /=
PercentEquals, // %=
PlusPlus, // ++
MinusMinus, // --
BitwiseNot, // ~
BitwiseOr, // |
BitwiseXor, // ^
BitwiseAnd, // &
LeftShift, // <<
RightShift, // >>
LogicalNot, // !
LogicalOr, // ||
LogicalAnd, // &&
Equals, // =
EqualsEquals, // ==
NotEquals, // !=
Less, // <
Greater, // >
LessEquals, // <=
GreaterEquals, // >=
// Must keep in sync with largest value!
MAX_VALUE = GreaterEquals
};
/// Returns the name of the enum identifier.
std::string_view to_string(TokenType tok);
/// Returns a human readable string for the given token.
std::string_view to_description(TokenType tok);
/// Returns the raw numeric value of the given token type.
constexpr auto to_underlying(TokenType type) {
return static_cast<std::underlying_type_t<TokenType>>(type);
}
/// A token represents a section of source code text together with its lexical type.
/// Tokens are returned by the lexer.
class Token final {
public:
Token() = default;
Token(TokenType type, const SourceRange& range)
: type_(type)
, range_(range) {}
/// Type of the token.
TokenType type() const { return type_; }
void type(TokenType t) { type_ = t; }
/// Source code part that contains the token.
const SourceRange& range() const { return range_; }
void range(const SourceRange& range) { range_ = range; }
void format(FormatStream& stream) const;
private:
TokenType type_ = TokenType::Unexpected;
SourceRange range_;
};
} // namespace tiro
TIRO_ENABLE_FREE_TO_STRING(tiro::TokenType)
TIRO_ENABLE_MEMBER_FORMAT(tiro::Token)
#endif // TIRO_COMPILER_SYNTAX_TOKEN_HPP
| 24.230769 | 84 | 0.544567 | mbeckem |
6c420cb1e6155c986b1f524cf212aeeca719f9fe | 4,229 | cc | C++ | GUI/Texture.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | GUI/Texture.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | GUI/Texture.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #include <cmath>
#include "GUI/LogUtils.h"
#include "Texture.h"
using namespace SideCar::GUI;
GLenum Texture::bestTextureType_ = GLenum(-1);
bool Texture::isPowerOfTwoSizeRequired_ = true;
Logger::Log&
Texture::Log()
{
static Logger::Log& log_ = Logger::Log::Find("SideCar.GUI.Texture");
return log_;
}
GLenum
Texture::GetBestTextureType()
{
Logger::ProcLog log("GetBestTextureType", Log());
if (int(bestTextureType_) != -1) {
LOGINFO << GetTextureTypeTag(bestTextureType_) << std::endl;
return bestTextureType_;
}
// Basic goal is to use a non-power of two texture type since it will save texture memory and improve
// performance. First, check OpenGL version. If version 2.0 or higher than 2D textures are not constrained
// to power of two dimensions so use them.
//
QString versionText(reinterpret_cast<const char*>(glGetString(GL_VERSION)));
LOGDEBUG << "versionText: " << versionText << std::endl;
bool ok = true;
float version = versionText.section(' ', 0, 0).toFloat(&ok);
LOGDEBUG << "version: " << version << std::endl;
if (ok && version > 2.0) {
LOGDEBUG << "using GL_TEXTURE_2D (non-power-of-2)" << std::endl;
bestTextureType_ = GL_TEXTURE_2D;
isPowerOfTwoSizeRequired_ = false;
return bestTextureType_;
}
QString extensionsText(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)));
LOGDEBUG << "extensions: " << extensionsText << std::endl;
QStringList extensions = extensionsText.split(' ');
#ifdef GL_TEXTURE_RECTANGLE_ARB
if (extensions.contains("GL_ARB_texture_rectangle")) {
LOGDEBUG << "usng GL_TEXTURE_RECTANGLE_ARB" << std::endl;
bestTextureType_ = GL_TEXTURE_RECTANGLE_ARB;
isPowerOfTwoSizeRequired_ = false;
return bestTextureType_;
}
#endif
#ifdef GL_TEXTURE_RECTANGLE_EXT
if (extensions.contains("GL_EXT_texture_rectangle")) {
LOGDEBUG << "usng GL_TEXTURE_RECTANGLE_EXT" << std::endl;
bestTextureType_ = GL_TEXTURE_RECTANGLE_EXT;
isPowerOfTwoSizeRequired_ = false;
return bestTextureType_;
}
#endif
LOGDEBUG << "usng GL_TEXTURE_2D (power-of-2)" << std::endl;
bestTextureType_ = GL_TEXTURE_2D;
isPowerOfTwoSizeRequired_ = true;
return bestTextureType_;
}
bool
Texture::IsPowerOfTwoSizeRequired()
{
GetBestTextureType();
return isPowerOfTwoSizeRequired_;
}
GLuint
Texture::GetBestTextureSpan(GLuint span)
{
if (IsPowerOfTwoSizeRequired()) return GetPowerOf2Span(span);
return span;
}
GLuint
Texture::GetPowerOf2Span(GLuint span)
{
return GLuint(::pow(2, ::ceil(::log2(span))));
}
QString
Texture::GetTextureTypeTag(GLenum type)
{
switch (type) {
case GL_TEXTURE_2D: return "GL_TEXTURE_2D";
#ifdef GL_TEXTURE_RECTANGLE_ARB
case GL_TEXTURE_RECTANGLE_ARB: return "GL_TEXTURE_RECTANGLE_ARB";
#else
#ifdef GL_TEXTURE_RECTANGLE_EXT
case GL_TEXTURE_RECTANGLE_EXT: return "GL_TEXTURE_RECTANGLE_EXT";
#endif
#endif
default: return "UNKNOWN";
}
}
Texture::Texture(GLenum type, GLuint id, GLuint width, GLuint height) :
type_(type), id_(id), width_(width), height_(height), xMin_(0.0), yMin_(0.0)
{
Logger::ProcLog log("Texture", Log());
LOGINFO << "type: " << GetTextureTypeTag(type) << " id: " << id << " width: " << width
<< " height: " << height
<< std::endl;
if (isPowerOfTwoSizeRequired_) {
width = GetBestTextureSpan(width);
height = GetBestTextureSpan(height);
LOGDEBUG << "powerOf2 width: " << width << " height: " << height << std::endl;
}
switch (type) {
case GL_TEXTURE_2D:
xMax_ = float(width_) / float(width);
yMax_ = float(height_) / float(height);
break;
#ifdef GL_TEXTURE_RECTANGLE_ARB
case GL_TEXTURE_RECTANGLE_ARB:
#else
#ifdef GL_TEXTURE_RECTANGLE_EXT
case GL_TEXTURE_RECTANGLE_EXT:
#endif
#endif
xMax_ = width_;
yMax_ = height_;
break;
}
LOGDEBUG << "xMax: " << xMax_ << " yMax: " << yMax_ << std::endl;
}
void
Texture::setBounds(GLfloat xMin, GLfloat yMin, GLfloat xMax, GLfloat yMax)
{
xMin_ = xMin;
yMin_ = yMin;
xMax_ = xMax;
yMax_ = yMax;
}
| 27.461039 | 110 | 0.67179 | jwillemsen |
6c421fd5d713c493d471a890593b775c1d3704a9 | 26,497 | cpp | C++ | tms_rc/tms_rc_katana/KNI_4.3.0/demo/kni_test/kni_test.cpp | SigmaHayashi/ros_tms_for_smart_previewed_reality | 4ace908bd3da0519246b3c45d0230cbd02e49da0 | [
"BSD-3-Clause"
] | null | null | null | tms_rc/tms_rc_katana/KNI_4.3.0/demo/kni_test/kni_test.cpp | SigmaHayashi/ros_tms_for_smart_previewed_reality | 4ace908bd3da0519246b3c45d0230cbd02e49da0 | [
"BSD-3-Clause"
] | null | null | null | tms_rc/tms_rc_katana/KNI_4.3.0/demo/kni_test/kni_test.cpp | SigmaHayashi/ros_tms_for_smart_previewed_reality | 4ace908bd3da0519246b3c45d0230cbd02e49da0 | [
"BSD-3-Clause"
] | null | null | null | /**********************************************************************************
* Katana Native Interface - A C++ interface to the robot arm Katana.
* Copyright (C) 2005-2009 Neuronics AG
* Check out the AUTHORS file for detailed contact information.
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**********************************************************************************/
//////////////////////////////////////////////////////////////////////////////////
// test.cpp
// test program for KNI libraries
//////////////////////////////////////////////////////////////////////////////////
#include "kniBase.h"
#include <iostream>
#include <cstdio>
#include <memory>
#include <vector>
#include <fstream>
//////////////////////////////////////////////////////////////////////////////////
#define LEFT false
#define RIGHT true
//////////////////////////////////////////////////////////////////////////////////
const double PI = 3.14159265358979323846;
<<<<<<< HEAD
struct TPoint
{
double X, Y, Z;
double phi, theta, psi;
};
struct TCurrentMot
{
int idx;
bool running;
bool dir;
};
struct Tpos
{
static std::vector< int > x, y, z, u, v, w;
static const int xArr[], yArr[], zArr[], uArr[], vArr[], wArr[];
};
// Katana obj.
std::auto_ptr< CLMBase > katana;
//////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
if (argc != 3)
{
std::cout << "---------------------------------\n";
std::cout << "usage for socket connection: kni_test CONFIGFILE IP_ADDR\n";
std::cout << "---------------------------------\n";
return 0;
}
std::cout << "-----------------\n";
std::cout << "KNI_TEST DEMO STARTED\n";
std::cout << "-----------------\n";
//----------------------------------------------------------------//
// open device:
//----------------------------------------------------------------//
std::auto_ptr< CCdlSocket > device;
std::auto_ptr< CCplSerialCRC > protocol;
try
{
int port = 5566;
device.reset(new CCdlSocket(argv[2], port));
std::cout << "-------------------------------------------\n";
std::cout << "success: port " << port << " open\n";
std::cout << "-------------------------------------------\n";
//--------------------------------------------------------//
// init protocol:
//--------------------------------------------------------//
protocol.reset(new CCplSerialCRC());
std::cout << "-------------------------------------------\n";
std::cout << "success: protocol class instantiated\n";
std::cout << "-------------------------------------------\n";
protocol->init(device.get()); // fails if no response from Katana
std::cout << "-------------------------------------------\n";
std::cout << "success: communication with Katana initialized\n";
std::cout << "-------------------------------------------\n";
//--------------------------------------------------------//
// init robot:
//--------------------------------------------------------//
katana.reset(new CLMBase());
katana->create(argv[1], protocol.get());
}
catch (Exception &e)
{
std::cout << "ERROR: " << e.message() << std::endl;
return -1;
}
std::cout << "-------------------------------------------\n";
std::cout << "success: katana initialized\n";
std::cout << "-------------------------------------------\n";
// set linear velocity to 60
katana->setMaximumLinearVelocity(60);
// declare information variables
int nOfMot = katana->getNumberOfMotors(); // number of motors
int controller; // controller type: 0 for position, 1 for current
const char *model; // katana model name
std::vector< TPoint > points(0); // list of points used for motion
// declare temporary variables
std::vector< int > encoders(nOfMot, 0);
std::vector< double > pose(6, 0.0);
TCurrentMot mot[6];
for (int i = 0; i < 6; i++)
{
mot[i].running = false;
mot[i].idx = i;
mot[i].dir = RIGHT;
}
int tmp_int;
// calibration
std::cout << "- Calibrating Katana, please wait for termination..." << std::endl;
katana->calibrate();
std::cout << " ...done." << std::endl;
// get controller information
std::cout << "- Check if Katana has position or current controllers..." << std::endl;
controller = katana->getCurrentControllerType(1);
for (short motorNumber = 1; motorNumber < nOfMot; ++motorNumber)
{
tmp_int = katana->getCurrentControllerType(motorNumber + 1);
if (tmp_int != controller)
{
std::cout << "*** ERROR: Katana has mixed controller types on its axes! ***" << std::endl;
return 1;
}
}
std::cout << " Katana has all ";
controller == 0 ? std::cout << "position" : std::cout << "current";
std::cout << " controllers." << std::endl;
std::cout << " ...done." << std::endl;
// read current force if current controller installed
if (controller == 1)
{
std::cout << "- Read forces..." << std::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber)
{
std::cout << " Motor " << (motorNumber + 1) << ": " << katana->getForce(motorNumber + 1) << std::endl;
}
std::cout << " ...done." << std::endl;
}
// get Katana model name
std::cout << "- Get Katana model name..." << std::endl;
model = katana->GetBase()->GetGNL()->modelName;
std::cout << " " << model << std::endl;
std::cout << " ...done." << std::endl;
// switch motors off
std::cout << "- Switch robot off..." << std::endl;
katana->switchRobotOff();
std::cout << " Robot off" << std::endl;
std::cout << " ...done." << std::endl;
// get robot encoders
std::cout << "- Read robot encoders..." << std::endl;
std::cout << " Encoder values:";
katana->getRobotEncoders(encoders.begin(), encoders.end());
for (std::vector< int >::iterator i = encoders.begin(); i != encoders.end(); ++i)
{
std::cout << " " << *i;
}
std::cout << std::endl;
std::cout << " ...done." << std::endl;
// switch motors on
std::cout << "- Switch motors on..." << std::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber)
{
katana->switchMotorOn((short)motorNumber);
std::cout << " Motor " << (motorNumber + 1) << " on" << std::endl;
}
std::cout << " ...done." << std::endl;
// move single axes (inc, dec, mov, incDegrees, decDegrees, movDegrees, moveMotorByEnc, moveMotorBy, moveMotorToEnc,
// moveMotorTo)
std::cout << "- Move single axes..." << std::endl;
katana->dec(0, 10000, true);
std::cout << " Motor 1 decreased by 10000 encoders" << std::endl;
katana->inc(1, 10000, true);
std::cout << " Motor 2 increased by 10000 encoders" << std::endl;
katana->decDegrees(2, 70, true);
std::cout << " Motor 3 decreased by 70 degrees" << std::endl;
katana->mov(3, 20000, true);
std::cout << " "
<< "Motor 4 moved to encoder position 20000" << std::endl;
katana->movDegrees(4, 90, true);
std::cout << " Motor 5 moved to position 90 degrees" << std::endl;
katana->incDegrees(5, -35, true);
std::cout << " Motor 6 increased by -35 degrees" << std::endl;
katana->moveMotorBy(0, 0.2, true);
std::cout << " Motor 1 moved by 0.2 rad" << std::endl;
katana->moveMotorByEnc(1, -5000, true);
std::cout << " Motor 2 moved by -5000 encoders" << std::endl;
katana->moveMotorTo(2, 3.1, true);
std::cout << " Motor 3 moved to 3.1 rad" << std::endl;
katana->moveMotorToEnc(3, 10000, true);
std::cout << " Motor 4 moved to 10000 encoders" << std::endl;
std::cout << " ...done." << std::endl;
// move all axes (moveRobotToEnc)
std::cout << "- Move all axes..." << std::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber)
{
encoders[motorNumber] = 30500;
if (motorNumber == 1 || motorNumber == 2)
encoders[motorNumber] = -30500;
}
katana->moveRobotToEnc(encoders, true);
std::cout << " Robot moved to encoder position 30500 -30500 -30500 30500 30500 30500" << std::endl;
std::cout << " ...done." << std::endl;
// get coordinates
std::cout << "- Get coordinates..." << std::endl;
{
double x, y, z, phi, theta, psi;
katana->getCoordinates(x, y, z, phi, theta, psi);
std::cout << " Current coordinates: " << x << " " << y << " " << z << " " << phi << " " << theta << " " << psi
<< std::endl;
}
std::cout << " ...done." << std::endl;
// get coordinates from given encoders
std::cout << "- Get coordinates from given encoders..." << std::endl;
{
encoders[0] = encoders[3] = encoders[4] = encoders[5] = 25000;
encoders[1] = encoders[2] = -25000;
katana->getCoordinatesFromEncoders(pose, encoders);
std::cout << " Encoders: 25000 -25000 -25000 25000 25000 25000" << std::endl;
std::cout << " Coordinates: " << pose[0] << " " << pose[1] << " " << pose[2] << " " << pose[3] << " " << pose[4]
<< " " << pose[5] << std::endl;
}
std::cout << " ...done." << std::endl;
// calculate inverse kinematics
std::cout << "- Calculate inverse kinematics..." << std::endl;
{
katana->IKCalculate(pose[0], pose[1], pose[2], pose[3], pose[4], pose[5], encoders.begin());
std::cout << " encoders.size(): " << encoders.size() << std::endl;
std::cout << " Possible encoders: " << encoders[0] << " " << encoders[1] << " " << encoders[2] << " "
<< encoders[3] << " " << encoders[4] << " " << encoders[5] << std::endl;
}
std::cout << " ...done." << std::endl;
// move robot to pose
std::cout << "- Move robot to pose..." << std::endl;
katana->moveRobotTo(pose, true);
std::cout << " Coordinates: " << pose[0] << " " << pose[1] << " " << pose[2] << " " << pose[3] << " " << pose[4]
<< " " << pose[5] << std::endl;
std::cout << " ...done." << std::endl;
// load points file
{
using namespace std;
cout << "- Load points file..." << endl;
ifstream listfile(model);
if (!listfile)
{
cout << "*** ERROR: File '" << model << "' not found or access denied! ***" << endl;
return 1;
}
string line;
vector< string > tokens;
const string delimiter = ",";
int lines = 0;
while (!listfile.eof())
{
listfile >> line;
string::size_type lastPos = line.find_first_not_of(delimiter, 0);
string::size_type pos = line.find_first_of(delimiter, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(line.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = line.find_first_not_of(delimiter, pos);
// Find next "non-delimiter"
pos = line.find_first_of(delimiter, lastPos);
}
TPoint point;
point.X = atof((tokens.at(0)).data());
point.Y = atof((tokens.at(1)).data());
point.Z = atof((tokens.at(2)).data());
point.phi = atof((tokens.at(3)).data());
point.theta = atof((tokens.at(4)).data());
point.psi = atof((tokens.at(5)).data());
points.push_back(point);
++lines;
tokens.clear();
}
cout << " " << lines << " points loaded." << endl;
cout << " ...done." << endl;
}
// move to point in list
std::cout << "- Move in point list..." << std::endl;
{
int i, j;
bool wait;
std::cout << " Single p2p movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i)
{
katana->moveRobotTo(points[i].X, points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi);
}
std::cout << " ...done." << std::endl;
std::cout << " Single linear movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i)
{
katana->moveRobotLinearTo(points[i].X, points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi);
}
std::cout << " ...done." << std::endl;
std::cout << " Concatenated p2p movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i)
{
j = (i + points.size() - 1) % points.size();
wait = false;
if (i == ((int)points.size() - 1))
wait = true;
katana->movP2P(points[j].X, points[j].Y, points[j].Z, points[j].phi, points[j].theta, points[j].psi, points[i].X,
points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi, true, 70.0, wait);
}
std::cout << " ...done." << std::endl;
std::cout << " Concatenated linear movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i)
{
j = (i + points.size() - 1) % points.size();
wait = false;
if (i == ((int)points.size() - 1))
wait = true;
katana->movLM2P(points[j].X, points[j].Y, points[j].Z, points[j].phi, points[j].theta, points[j].psi, points[i].X,
points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi, true, 100.0, wait);
}
std::cout << " ...done." << std::endl;
}
std::cout << " ...done." << std::endl;
// move all axes (moveRobotToEnc)
std::cout << "- Move all axes..." << std::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber)
{
encoders[motorNumber] = 30500;
if (motorNumber == 1 || motorNumber == 2)
encoders[motorNumber] = -30500;
}
katana->moveRobotToEnc(encoders, true);
std::cout << " Robot moved to encoder position 30500 -30500 -30500 30500 30500 30500" << std::endl;
std::cout << " ...done." << std::endl;
return 0;
}
//////////////////////////////////////////////////////////////////////////////////
=======
struct TPoint {
double X, Y, Z;
double phi, theta, psi;
};
struct TCurrentMot {
int idx;
bool running;
bool dir;
};
struct Tpos{
static std::vector<int> x,y,z,u,v,w;
static const int xArr[], yArr[], zArr[], uArr[], vArr[], wArr[];
};
//Katana obj.
std::auto_ptr<CLMBase> katana;
//////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
if (argc != 3) {
std::cout << "---------------------------------\n";
std::cout << "usage for socket connection: kni_test CONFIGFILE IP_ADDR\n";
std::cout << "---------------------------------\n";
return 0;
}
std::cout << "-----------------\n";
std::cout << "KNI_TEST DEMO STARTED\n";
std::cout << "-----------------\n";
//----------------------------------------------------------------//
//open device:
//----------------------------------------------------------------//
std::auto_ptr<CCdlSocket> device;
std::auto_ptr<CCplSerialCRC> protocol;
try {
int port = 5566;
device.reset(new CCdlSocket(argv[2], port));
std::cout << "-------------------------------------------\n";
std::cout << "success: port " << port << " open\n";
std::cout << "-------------------------------------------\n";
//--------------------------------------------------------//
//init protocol:
//--------------------------------------------------------//
protocol.reset(new CCplSerialCRC());
std::cout << "-------------------------------------------\n";
std::cout << "success: protocol class instantiated\n";
std::cout << "-------------------------------------------\n";
protocol->init(device.get()); //fails if no response from Katana
std::cout << "-------------------------------------------\n";
std::cout << "success: communication with Katana initialized\n";
std::cout << "-------------------------------------------\n";
//--------------------------------------------------------//
//init robot:
//--------------------------------------------------------//
katana.reset(new CLMBase());
katana->create(argv[1], protocol.get());
} catch(Exception &e) {
std::cout << "ERROR: " << e.message() << std::endl;
return -1;
}
std::cout << "-------------------------------------------\n";
std::cout << "success: katana initialized\n";
std::cout << "-------------------------------------------\n";
//set linear velocity to 60
katana->setMaximumLinearVelocity(60);
// declare information variables
int nOfMot = katana->getNumberOfMotors(); // number of motors
int controller; // controller type: 0 for position, 1 for current
const char* model; // katana model name
std::vector<TPoint> points(0); // list of points used for motion
// declare temporary variables
std::vector<int> encoders(nOfMot, 0);
std::vector<double> pose(6, 0.0);
TCurrentMot mot[6];
for (int i = 0; i< 6; i++){
mot[i].running = false;
mot[i].idx = i;
mot[i].dir = RIGHT;
}
int tmp_int;
// calibration
std::cout << "- Calibrating Katana, please wait for termination..." << std::endl;
katana->calibrate();
std::cout << " ...done." << std::endl;
// get controller information
std::cout << "- Check if Katana has position or current controllers..." << std::endl;
controller = katana->getCurrentControllerType(1);
for(short motorNumber = 1; motorNumber < nOfMot; ++motorNumber) {
tmp_int = katana->getCurrentControllerType(motorNumber+1);
if (tmp_int != controller) {
std::cout << "*** ERROR: Katana has mixed controller types on its axes! ***" << std::endl;
return 1;
}
}
std::cout << " Katana has all ";
controller == 0 ? std::cout << "position" : std::cout << "current";
std::cout << " controllers." << std::endl;
std::cout << " ...done." << std::endl;
// read current force if current controller installed
if (controller == 1) {
std::cout << "- Read forces..." << std::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber) {
std::cout << " Motor " << (motorNumber+1) << ": " << katana->getForce(motorNumber+1) << std::endl;
}
std::cout << " ...done." << std::endl;
}
// get Katana model name
std::cout << "- Get Katana model name..." << std ::endl;
model = katana->GetBase()->GetGNL()->modelName;
std::cout << " " << model << std::endl;
std::cout << " ...done." << std::endl;
// switch motors off
std::cout << "- Switch robot off..." << std ::endl;
katana->switchRobotOff();
std::cout << " Robot off" << std::endl;
std::cout << " ...done." << std::endl;
// get robot encoders
std::cout << "- Read robot encoders..." << std ::endl;
std::cout << " Encoder values:";
katana->getRobotEncoders(encoders.begin(), encoders.end());
for (std::vector<int>::iterator i= encoders.begin(); i != encoders.end(); ++i) {
std::cout << " " << *i;
}
std::cout << std::endl;
std::cout << " ...done." << std::endl;
// switch motors on
std::cout << "- Switch motors on..." << std ::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber) {
katana->switchMotorOn((short)motorNumber);
std::cout << " Motor " << (motorNumber+1) << " on" << std::endl;
}
std::cout << " ...done." << std::endl;
// move single axes (inc, dec, mov, incDegrees, decDegrees, movDegrees, moveMotorByEnc, moveMotorBy, moveMotorToEnc, moveMotorTo)
std::cout << "- Move single axes..." << std ::endl;
katana->dec(0, 10000, true);
std::cout << " Motor 1 decreased by 10000 encoders" << std::endl;
katana->inc(1, 10000, true);
std::cout << " Motor 2 increased by 10000 encoders" << std::endl;
katana->decDegrees(2, 70, true);
std::cout << " Motor 3 decreased by 70 degrees" << std::endl;
katana->mov(3, 20000, true);
std::cout << " " << "Motor 4 moved to encoder position 20000" << std::endl;
katana->movDegrees(4, 90, true);
std::cout << " Motor 5 moved to position 90 degrees" << std::endl;
katana->incDegrees(5, -35, true);
std::cout << " Motor 6 increased by -35 degrees" << std::endl;
katana->moveMotorBy(0, 0.2, true);
std::cout << " Motor 1 moved by 0.2 rad" << std::endl;
katana->moveMotorByEnc(1, -5000, true);
std::cout << " Motor 2 moved by -5000 encoders" << std::endl;
katana->moveMotorTo(2, 3.1, true);
std::cout << " Motor 3 moved to 3.1 rad" << std::endl;
katana->moveMotorToEnc(3, 10000, true);
std::cout << " Motor 4 moved to 10000 encoders" << std::endl;
std::cout << " ...done." << std::endl;
// move all axes (moveRobotToEnc)
std::cout << "- Move all axes..." << std ::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber) {
encoders[motorNumber] = 30500;
if (motorNumber == 1 || motorNumber == 2)
encoders[motorNumber] = -30500;
}
katana->moveRobotToEnc(encoders, true);
std::cout << " Robot moved to encoder position 30500 -30500 -30500 30500 30500 30500" << std::endl;
std::cout << " ...done." << std::endl;
// get coordinates
std::cout << "- Get coordinates..." << std ::endl;
{
double x, y, z, phi, theta, psi;
katana->getCoordinates(x, y, z, phi, theta, psi);
std::cout << " Current coordinates: " << x << " " << y << " " << z << " " << phi << " " << theta << " " << psi << std::endl;
}
std::cout << " ...done." << std::endl;
// get coordinates from given encoders
std::cout << "- Get coordinates from given encoders..." << std ::endl;
{
encoders[0] = encoders[3] = encoders[4] = encoders[5] = 25000;
encoders[1] = encoders[2] = -25000;
katana->getCoordinatesFromEncoders(pose, encoders);
std::cout << " Encoders: 25000 -25000 -25000 25000 25000 25000" << std::endl;
std::cout << " Coordinates: " << pose[0] << " " << pose[1] << " " << pose[2] << " " << pose[3] << " " << pose[4] << " " << pose[5] << std::endl;
}
std::cout << " ...done." << std::endl;
// calculate inverse kinematics
std::cout << "- Calculate inverse kinematics..." << std ::endl;
{
katana->IKCalculate(pose[0], pose[1], pose[2], pose[3], pose[4], pose[5], encoders.begin());
std::cout << " encoders.size(): " << encoders.size() << std::endl;
std::cout << " Possible encoders: " << encoders[0] << " " << encoders[1] << " " << encoders[2] << " " << encoders[3] << " " << encoders[4] << " " << encoders[5] << std::endl;
}
std::cout << " ...done." << std::endl;
// move robot to pose
std::cout << "- Move robot to pose..." << std ::endl;
katana->moveRobotTo(pose, true);
std::cout << " Coordinates: " << pose[0] << " " << pose[1] << " " << pose[2] << " " << pose[3] << " " << pose[4] << " " << pose[5] << std::endl;
std::cout << " ...done." << std::endl;
// load points file
{
using namespace std;
cout << "- Load points file..." << endl;
ifstream listfile(model);
if(!listfile) {
cout << "*** ERROR: File '" << model << "' not found or access denied! ***" << endl;
return 1;
}
string line;
vector<string> tokens;
const string delimiter = ",";
int lines = 0;
while(!listfile.eof()) {
listfile >> line;
string::size_type lastPos = line.find_first_not_of(delimiter, 0);
string::size_type pos = line.find_first_of(delimiter, lastPos);
while (string::npos != pos || string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(line.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = line.find_first_not_of(delimiter, pos);
// Find next "non-delimiter"
pos = line.find_first_of(delimiter, lastPos);
}
TPoint point;
point.X = atof((tokens.at(0)).data());
point.Y = atof((tokens.at(1)).data());
point.Z = atof((tokens.at(2)).data());
point.phi = atof((tokens.at(3)).data());
point.theta = atof((tokens.at(4)).data());
point.psi = atof((tokens.at(5)).data());
points.push_back( point );
++lines;
tokens.clear();
}
cout << " " << lines << " points loaded." << endl;
cout << " ...done." << endl;
}
// move to point in list
std::cout << "- Move in point list..." << std ::endl;
{
int i, j;
bool wait;
std::cout << " Single p2p movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i) {
katana->moveRobotTo(points[i].X, points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi);
}
std::cout << " ...done." << std::endl;
std::cout << " Single linear movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i) {
katana->moveRobotLinearTo(points[i].X, points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi);
}
std::cout << " ...done." << std::endl;
std::cout << " Concatenated p2p movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i) {
j = (i + points.size() - 1) % points.size();
wait = false;
if (i == ((int)points.size()-1)) wait = true;
katana->movP2P(points[j].X, points[j].Y, points[j].Z, points[j].phi, points[j].theta, points[j].psi, points[i].X, points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi, true, 70.0, wait);
}
std::cout << " ...done." << std::endl;
std::cout << " Concatenated linear movements..." << std::flush;
for (i = 0; i < (int)points.size(); ++i) {
j = (i + points.size() - 1) % points.size();
wait = false;
if (i == ((int)points.size()-1)) wait = true;
katana->movLM2P(points[j].X, points[j].Y, points[j].Z, points[j].phi, points[j].theta, points[j].psi, points[i].X, points[i].Y, points[i].Z, points[i].phi, points[i].theta, points[i].psi, true, 100.0, wait);
}
std::cout << " ...done." << std::endl;
}
std::cout << " ...done." << std::endl;
// move all axes (moveRobotToEnc)
std::cout << "- Move all axes..." << std ::endl;
for (short motorNumber = 0; motorNumber < nOfMot; ++motorNumber) {
encoders[motorNumber] = 30500;
if (motorNumber == 1 || motorNumber == 2)
encoders[motorNumber] = -30500;
}
katana->moveRobotToEnc(encoders, true);
std::cout << " Robot moved to encoder position 30500 -30500 -30500 30500 30500 30500" << std::endl;
std::cout << " ...done." << std::endl;
return 0;
}
//////////////////////////////////////////////////////////////////////////////////
>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7
| 37.852857 | 210 | 0.525833 | SigmaHayashi |
6c43ab09963e0439d1d595c18b4f3e760296a1dc | 528 | cpp | C++ | bin-int/Debug-windows-x86_64/NextEngine/unity_ZQ3LOIMG5RJ3ZMYP.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | 1 | 2021-09-10T18:19:16.000Z | 2021-09-10T18:19:16.000Z | bin-int/Debug-windows-x86_64/NextEngine/unity_ZQ3LOIMG5RJ3ZMYP.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | null | null | null | bin-int/Debug-windows-x86_64/NextEngine/unity_ZQ3LOIMG5RJ3ZMYP.cpp | CompilerLuke/NextEngine | aa1a8e9d9370bce004dba00854701597cab74989 | [
"MIT"
] | 2 | 2020-04-02T06:46:56.000Z | 2021-06-17T16:47:57.000Z | #include "stdafx.h"
#include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\VULKAN\vk_model.cpp"
#include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\VULKAN\vk_shader.cpp"
#include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\VULKAN\vk_texture.cpp"
#include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\assets.cpp"
#include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\assimp_model_loader.cpp"
| 31.058824 | 103 | 0.80303 | CompilerLuke |
6c441fce0124f90618f104f6f1b4701c655985ff | 3,700 | hpp | C++ | src/libraries/dynamicMesh/dynamicMesh/meshCut/splitCell/splitCell.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/dynamicMesh/meshCut/splitCell/splitCell.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/dynamicMesh/meshCut/splitCell/splitCell.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::splitCell
Description
Description of cell after splitting. Contains cellLabel and pointers
to cells it it split in. See directedRefinement.
SourceFiles
splitCell.cpp
\*---------------------------------------------------------------------------*/
#ifndef splitCell_H
#define splitCell_H
#include "label.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
// Forward declaration of classes
/*---------------------------------------------------------------------------*\
Class splitCell Declaration
\*---------------------------------------------------------------------------*/
class splitCell
{
// Private data
//- Unsplit cell label. Only uptodate if this cell is 'live'
// (i.e. no master or slave)
label cellI_;
//- Parent splitCell or null
splitCell* parent_;
//- Cells replacing this or null
splitCell* master_;
splitCell* slave_;
// Private Member Functions
//- Disallow default bitwise copy construct
splitCell(const splitCell&);
//- Disallow default bitwise assignment
void operator=(const splitCell&);
public:
// Constructors
//- Construct from cell number and parent
splitCell(const label cellI, splitCell* parent);
//- Destructor
~splitCell();
// Member Functions
// Access
label cellLabel() const
{
return cellI_;
}
label& cellLabel()
{
return cellI_;
}
splitCell* parent() const
{
return parent_;
}
splitCell*& parent()
{
return parent_;
}
splitCell* master() const
{
return master_;
}
splitCell*& master()
{
return master_;
}
splitCell* slave() const
{
return slave_;
}
splitCell*& slave()
{
return slave_;
}
//- Check if this is master cell of split
bool isMaster() const;
//- Check if this is unrefined (i.e. has no master or slave)
bool isUnrefined() const;
//- Returns other half of split cell. I.e. slave if this is master.
splitCell* getOther() const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 24.666667 | 79 | 0.455405 | MrAwesomeRocks |
6c455ef3724021c6b498bbd436724308fba0ef95 | 3,161 | cpp | C++ | BasicLayoutDemo/mainwindow.cpp | waitwalker/QtWidgetDemos | fe0ef951b9e058a93ada4b3399c4daa900694131 | [
"MIT"
] | 1 | 2021-09-03T08:52:55.000Z | 2021-09-03T08:52:55.000Z | BasicLayoutDemo/mainwindow.cpp | waitwalker/QtWidgetDemos | fe0ef951b9e058a93ada4b3399c4daa900694131 | [
"MIT"
] | null | null | null | BasicLayoutDemo/mainwindow.cpp | waitwalker/QtWidgetDemos | fe0ef951b9e058a93ada4b3399c4daa900694131 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QTextEdit>
#include <QFormLayout>
#include <QComboBox>
#include <QSpinBox>
#include <QDialogButtonBox>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget *containerWidget = new QWidget(this);
this->setCentralWidget(containerWidget);
QVBoxLayout *verticalLayout = new QVBoxLayout(containerWidget);
// 按钮容器
QGroupBox *buttonsGroup = new QGroupBox("按钮容器");
QHBoxLayout *buttonContainer = new QHBoxLayout;
QPushButton *button1 = new QPushButton("button1");
QPushButton *button2 = new QPushButton("button2");
QPushButton *button3 = new QPushButton("button3");
QPushButton *button4 = new QPushButton("button4");
QPushButton *button5 = new QPushButton("button5");
buttonContainer->addWidget(button1);
buttonContainer->addWidget(button2);
buttonContainer->addWidget(button3);
buttonContainer->addWidget(button4);
buttonContainer->addWidget(button5);
buttonsGroup->setLayout(buttonContainer);
verticalLayout->addWidget(buttonsGroup);
// Grid容器
QGroupBox *gridGroup = new QGroupBox("Grid");
QGridLayout *gridLayout = new QGridLayout;
QLabel *label1 = new QLabel("Line 1");
QLineEdit *lineEdit1 = new QLineEdit;
QLabel *label2 = new QLabel("Line 2");
QLineEdit *lineEdit2 = new QLineEdit;
QLabel *label3 = new QLabel("Line 3");
QLineEdit *lineEdit3 = new QLineEdit;
gridLayout->addWidget(label1,0,0);
gridLayout->addWidget(lineEdit1,0,1);
gridLayout->addWidget(label2,1,0);
gridLayout->addWidget(lineEdit2,1,1);
gridLayout->addWidget(label3,2,0);
gridLayout->addWidget(lineEdit3,2,1);
QTextEdit *textEdit = new QTextEdit;
textEdit->setPlainText("文本输入框");
// 从第一行,第3列(0,1,2)开始,占4行1列
gridLayout->addWidget(textEdit,0,2,4,1);
// 设置当前列所占
gridLayout->setColumnStretch(2,5);
gridGroup->setLayout(gridLayout);
verticalLayout->addWidget(gridGroup);
QGroupBox *formGroup = new QGroupBox("Form");
QFormLayout *formLayout = new QFormLayout;
formLayout->addRow(new QLabel("Line 1", new QLineEdit));
formLayout->addRow(new QLabel("Line 2", new QComboBox));
formLayout->addRow(new QLabel("Line 3", new QSpinBox));
formLayout->addWidget(new QLineEdit);
formGroup->setLayout(formLayout);
verticalLayout->addWidget(formGroup);
QTextEdit *bottomEdit = new QTextEdit;
bottomEdit->setPlainText("Bottom edit");
verticalLayout->addWidget(bottomEdit);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Close);
connect(buttonBox,&QDialogButtonBox::accepted,[=](){
qDebug()<<"OK clicked";
});
connect(buttonBox,&QDialogButtonBox::rejected,[=](){
qDebug()<<"Close clicked";
this->hide();
});
verticalLayout->addWidget(buttonBox);
verticalLayout->addStretch();
}
MainWindow::~MainWindow()
{
delete ui;
}
| 29.542056 | 103 | 0.700095 | waitwalker |
6c47855ad32ae38d7865f06e98fb58dbea3ea85e | 3,960 | cpp | C++ | libro/SpinPQ.cpp | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | 1 | 2017-06-01T00:21:16.000Z | 2017-06-01T00:21:16.000Z | libro/SpinPQ.cpp | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | 3 | 2017-06-01T00:26:16.000Z | 2020-05-09T21:06:27.000Z | libro/SpinPQ.cpp | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | null | null | null | //
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// 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
\brief Definitions for ro::SpinPQ
*/
#include "libro/SpinPQ.h"
#include "libga/spin.h"
#include "libro/PairRel.h"
#include "libro/ro.h"
#include <array>
#include <string>
#include <sstream>
namespace ro
{
// static
std::pair<ga::Spinor, ga::Spinor>
SpinPQ :: pairPQ
( ga::BiVector const & phi
, ga::BiVector const & theta
, ga::BiVector const & basePlane
)
{
std::pair<ga::Spinor, ga::Spinor> spinPair;
ga::Spinor const ephP{ ga::exp( .5 * phi) };
ga::Spinor const enhP{ ephP.reverse() };
ga::Spinor const ephT{ ga::exp( .5 * theta) };
ga::Spinor const enhT{ ephT.reverse() };
ga::Spinor const P0{ -ephT * basePlane * enhP };
ga::Spinor const Q0{ ephP * enhT };
spinPair = { P0, Q0 };
return spinPair;
}
// static
SpinPQ
SpinPQ :: from
( ga::BiVector const & phi
, ga::BiVector const & theta
, ga::BiVector const & basePlane
)
{
return SpinPQ(pairPQ(phi, theta, basePlane));
}
// static
SpinPQ
SpinPQ :: from
( std::pair<ga::Rigid, ga::Rigid> const & oriPair
)
{
ro::PairRel const roRel(oriPair.first, oriPair.second);
ga::BiVector const basePrime{ ga::E123 * roRel.baseVector2w1() };
return from(roRel.angle1w0(), roRel.angle2w0(), basePrime);
}
// explicit
SpinPQ :: SpinPQ
( std::pair<ga::Spinor, ga::Spinor> const & pairPQ
)
: thePQ{ pairPQ }
{ }
// explicit
SpinPQ :: SpinPQ
( ro::Pair const & anyRO
)
: thePQ{ from(anyRO.pair()).thePQ }
{ }
double
SpinPQ :: tripleProductGap
( std::pair<ga::Vector, ga::Vector> const & uvPair
) const
{
ga::Spinor const & PP = thePQ.first;
ga::Spinor const & QQ = thePQ.second;
ga::Vector const & uu = uvPair.first;
ga::Vector const & vv = uvPair.second;
ga::Spinor const triPro{ PP * uu * QQ * vv };
return triPro.theS.theValue;
}
bool
SpinPQ :: isValid
() const
{
return
( thePQ.first.isValid()
&& thePQ.second.isValid()
);
}
OriPair
SpinPQ :: pair
() const
{
// shortand names for current values
ga::Spinor const & PP = thePQ.first;
ga::Spinor const & QQ = thePQ.second;
// dependent RO recovery
static ga::BiVector const depPhi{ ga::bZero };
ga::BiVector const depTheta{ (-2.*ga::logG2(QQ)).theB };
ga::BiVector const basePlane{ -(QQ * PP).theB };
ga::Vector const baseVec{ -ga::E123 * basePlane };
// gather into orientation pair
static ga::Rigid const ori1w0{ ga::Rigid::identity() };
ga::Rigid const ori2w0(baseVec, ga::Pose(depTheta));
// and return as RO object
return { ori1w0, ori2w0 };
}
std::string
SpinPQ :: infoString
( std::string const & title
, std::string const & fmt
) const
{
std::ostringstream oss;
if (! title.empty())
{
oss << title << std::endl;
}
if (isValid())
{
oss
<< thePQ.first.infoStringFmt("P", fmt)
<< " " << thePQ.second.infoStringFmt("Q", fmt)
;
}
else
{
oss << " <null>";
}
return oss.str();
}
} // ro
| 22.122905 | 72 | 0.674495 | transpixel |
6c482133827736d165d01d873f1aef248b736198 | 4,860 | hpp | C++ | src/OpenSimBindings/UndoableUiModel.hpp | ComputationalBiomechanicsLab/opensim-creator | e5c4b24f5ef3bffe10c84899d0a0c79037020b6d | [
"Apache-2.0"
] | 5 | 2021-07-13T12:03:29.000Z | 2021-12-22T20:21:58.000Z | src/OpenSimBindings/UndoableUiModel.hpp | ComputationalBiomechanicsLab/opensim-creator | e5c4b24f5ef3bffe10c84899d0a0c79037020b6d | [
"Apache-2.0"
] | 180 | 2022-01-27T15:25:15.000Z | 2022-03-30T13:41:12.000Z | src/OpenSimBindings/UndoableUiModel.hpp | ComputationalBiomechanicsLab/opensim-creator | e5c4b24f5ef3bffe10c84899d0a0c79037020b6d | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "src/OpenSimBindings/UiModel.hpp"
#include "src/Utils/CircularBuffer.hpp"
#include <memory>
#include <optional>
namespace OpenSim {
class Model;
class Component;
}
namespace SimTK {
class State;
}
namespace osc {
// a "UI-ready" OpenSim::Model with undo/redo and rollback support
//
// this is what the top-level editor screens are managing. As the user makes
// edits to the model, the current/undo/redo states are being updated. This
// class also has light support for handling "rollbacks", which is where the
// implementation detects that the user modified the model into an invalid state
// and the implementation tried to fix the problem by rolling back to an earlier
// (hopefully, valid) undo state
struct UndoableUiModel final {
UiModel current;
CircularBuffer<UiModel, 32> undo;
CircularBuffer<UiModel, 32> redo;
// holding space for a "damaged" model
//
// this is set whenever the implementation detects that the current
// model was damaged by a modification (i.e. the model does not survive a
// call to .initSystem with its modified properties).
//
// The implementation will try to recover from the damage by popping models
// from the undo buffer and making them `current`. It will then store the
// damaged model here for later cleanup (by the user of this class, which
// should `std::move` out the damaged instance)
//
// the damaged model is kept "alive" so that any pointers into the model are
// still valid. The reason this is important is because the damage may have
// been done midway through a larger process (e.g. rendering) and there may
// be local (stack-allocated) pointers into the damaged model's components.
// In that case, it is *probably* safer to let that process finish with a
// damaged model than potentially segfault.
std::optional<UiModel> damaged;
// make a new undoable UI model
UndoableUiModel();
explicit UndoableUiModel(std::unique_ptr<OpenSim::Model> model);
[[nodiscard]] constexpr bool canUndo() const noexcept {
return !undo.empty();
}
void doUndo();
[[nodiscard]] constexpr bool canRedo() const noexcept {
return !redo.empty();
}
void doRedo();
[[nodiscard]] OpenSim::Model& model() const noexcept {
return *current.model;
}
void setModel(std::unique_ptr<OpenSim::Model>);
// this should be called before any modification is made to the current model
//
// it gives the implementation a chance to save a known-to-be-undamaged
// version of `current` before any potential damage happens
void beforeModifyingModel();
// this should be called after any modification is made to the current model
//
// it "commits" the modification by calling `on_model_modified` on the model
// in a way that will "rollback" if comitting the change throws an exception
void afterModifyingModel();
// tries to rollback the model to an earlier state, throwing an exception if
// that isn't possible (e.g. because there are no earlier states)
void forciblyRollbackToEarlierState();
[[nodiscard]] OpenSim::Component* getSelection() noexcept {
return current.selected;
}
void setSelection(OpenSim::Component* c) {
current.selected = c;
}
[[nodiscard]] OpenSim::Component* getHover() noexcept {
return current.hovered;
}
void setHover(OpenSim::Component* c) {
current.hovered = c;
}
[[nodiscard]] OpenSim::Component* getIsolated() noexcept {
return current.isolated;
}
void setIsolated(OpenSim::Component* c) {
current.isolated = c;
}
[[nodiscard]] SimTK::State& state() noexcept {
return *current.state;
}
void clearAnyDamagedModels();
// declare the death of a component pointer
//
// this happens when we know that OpenSim has destructed a component in
// the model indirectly (e.g. it was destructed by an OpenSim container)
// and that we want to ensure the pointer isn't still held by this state
void declareDeathOf(OpenSim::Component const* c) noexcept {
if (current.selected == c) {
current.selected = nullptr;
}
if (current.hovered == c) {
current.hovered = nullptr;
}
if (current.isolated == c) {
current.isolated = nullptr;
}
}
};
}
| 34.714286 | 85 | 0.620165 | ComputationalBiomechanicsLab |
6c49251988a31d236810dd74ca1c8e9a4e4237ce | 15,696 | cpp | C++ | src/Tools/TriangulatePolygon/TriangulatePolygon.cpp | Terryhata6/Mengine | dfe36fdc84d7398fbbbd199feffc46c6f157f1d4 | [
"MIT"
] | null | null | null | src/Tools/TriangulatePolygon/TriangulatePolygon.cpp | Terryhata6/Mengine | dfe36fdc84d7398fbbbd199feffc46c6f157f1d4 | [
"MIT"
] | null | null | null | src/Tools/TriangulatePolygon/TriangulatePolygon.cpp | Terryhata6/Mengine | dfe36fdc84d7398fbbbd199feffc46c6f157f1d4 | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <shellapi.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <sstream>
#include "ToolUtils/ToolUtils.h"
#define BOOST_NO_IOSTREAM
#pragma warning(push, 0)
#pragma warning(disable:4800)
#include "boost/geometry/geometry.hpp"
#include "boost/geometry/core/tag.hpp"
#include "boost/geometry/geometries/polygon.hpp"
#include "boost/geometry/geometries/box.hpp"
#include "boost/geometry/geometries/point_xy.hpp"
#include "boost/geometry/geometries/segment.hpp"
#include "boost/geometry/strategies/agnostic/point_in_poly_winding.hpp"
#pragma warning(pop)
#include "poly2tri/poly2tri.h"
struct vec2f
{
vec2f()
{
};
vec2f( const vec2f & _v )
: x( _v.x )
, y( _v.y )
{
};
const vec2f & operator = ( const vec2f & _v )
{
x = _v.x;
y = _v.y;
return *this;
}
vec2f( double _x, double _y )
: x( _x )
, y( _y )
{
};
double operator [] ( size_t i ) const
{
return (&x)[i];
}
double & operator [] ( size_t i )
{
return (&x)[i];
}
template <int K>
double get() const
{
return this->operator [] ( K );
}
template <int K>
void set( double _value )
{
this->operator [] ( K ) = _value;
}
double x;
double y;
};
namespace boost
{
namespace geometry
{
namespace traits
{
template <>
struct tag<vec2f>
{
typedef boost::geometry::point_tag type;
};
template<>
struct coordinate_type<vec2f>
{
typedef double type;
};
template<>
struct coordinate_system<vec2f>
{
typedef boost::geometry::cs::cartesian type;
};
template<>
struct dimension<vec2f>
: boost::mpl::int_<2>
{
};
template<size_t Dimension>
struct access<vec2f, Dimension >
{
static inline double get( vec2f const & p )
{
return p.template get<Dimension>();
}
static inline void set( vec2f & p, double const & value )
{
p.template set<Dimension>( value );
}
};
} // namespace traits
}
}
typedef boost::geometry::model::polygon<vec2f, true, true> BoostPolygon;
typedef std::vector<BoostPolygon> TVectorPolygon;
typedef std::vector<vec2f> TVectorPoints;
typedef std::vector<uint32_t> TVectorIndices;
//////////////////////////////////////////////////////////////////////////
static void parse_arg( const std::wstring & _str, TVectorPoints & _value )
{
std::vector<std::wstring> tokens;
std::wstringstream wss( _str );
std::wstring buf;
while( wss >> buf )
{
tokens.push_back( buf );
}
std::vector<std::wstring>::size_type count = tokens.size();
if( count % 2 != 0 )
{
return;
}
for( uint32_t i = 0; i != count; i += 2 )
{
const wchar_t * tocken_0 = tokens[i + 0].c_str();
const wchar_t * tocken_1 = tokens[i + 1].c_str();
double value_x;
swscanf( tocken_0, L"%lf", &value_x );
double value_y;
swscanf( tocken_1, L"%lf", &value_y );
vec2f v( (float)value_x, (float)value_y );
_value.push_back( v );
}
}
//////////////////////////////////////////////////////////////////////////
struct Mesh
{
uint16_t vertexCount;
uint16_t indexCount;
std::vector<vec2f> pos;
std::vector<vec2f> uv;
std::vector<uint16_t> indices;
};
//////////////////////////////////////////////////////////////////////////
static bool polygonize( const vec2f & image_base_size, const vec2f & image_trim_size, const vec2f & image_trim_offset, bool image_bb, bool image_subtract, const TVectorPoints & points, Mesh & mesh )
{
(void)image_base_size;
size_t points_count = points.size();
BoostPolygon polygon_input;
for( size_t points_index = 0; points_index != points_count; ++points_index )
{
const vec2f & v = points[points_index];
boost::geometry::append( polygon_input, v );
}
boost::geometry::correct( polygon_input );
TVectorPolygon output;
if( image_bb == true )
{
vec2f v0( image_trim_offset.x, image_trim_offset.y );
vec2f v1( image_trim_offset.x + image_trim_size.x, image_trim_offset.y );
vec2f v2( image_trim_offset.x + image_trim_size.x, image_trim_offset.y + image_trim_size.y );
vec2f v3( image_trim_offset.x, image_trim_offset.y + image_trim_size.y );
BoostPolygon imagePolygon;
boost::geometry::append( imagePolygon, v0 );
boost::geometry::append( imagePolygon, v1 );
boost::geometry::append( imagePolygon, v2 );
boost::geometry::append( imagePolygon, v3 );
boost::geometry::correct( imagePolygon );
if( image_subtract == false )
{
std::deque<BoostPolygon> result;
try
{
boost::geometry::intersection( polygon_input, imagePolygon, result );
}
catch( const std::exception & )
{
return false;
}
for( std::deque<BoostPolygon>::const_iterator
it = result.begin(),
it_end = result.end();
it != it_end;
++it )
{
const BoostPolygon & polygon = *it;
output.push_back( polygon );
}
}
else
{
std::deque<BoostPolygon> result;
try
{
boost::geometry::difference( imagePolygon, polygon_input, result );
}
catch( const std::exception & )
{
return false;
}
for( std::deque<BoostPolygon>::const_iterator
it = result.begin(),
it_end = result.end();
it != it_end;
++it )
{
const BoostPolygon & polygon = *it;
output.push_back( polygon );
}
}
}
else
{
output.push_back( polygon_input );
}
std::vector<p2t::Point> p2t_points;
std::vector<p2t::Point *> p2t_polygon_trinagles;
size_t max_points = 0;
for( TVectorPolygon::const_iterator
it = output.begin(),
it_end = output.end();
it != it_end;
++it )
{
const BoostPolygon & shape_vertex = *it;
const BoostPolygon::ring_type & shape_vertex_ring = shape_vertex.outer();
size_t outer_count = shape_vertex_ring.size();
max_points += outer_count - 1;
const BoostPolygon::inner_container_type & shape_vertex_inners = shape_vertex.inners();
size_t inners_count = shape_vertex_inners.size();
for( size_t index = 0; index != inners_count; ++index )
{
const BoostPolygon::ring_type & shape_vertex_inners_ring = shape_vertex_inners[index];
size_t inner_count = shape_vertex_inners_ring.size();
max_points += inner_count - 1;
}
}
p2t_points.reserve( max_points );
TVectorIndices shape_indices;
for( TVectorPolygon::const_iterator
it = output.begin(),
it_end = output.end();
it != it_end;
++it )
{
const BoostPolygon & shape_vertex = *it;
std::vector<p2t::Point *> p2t_polygon;
const BoostPolygon::ring_type & shape_vertex_ring = shape_vertex.outer();
size_t outer_count = shape_vertex_ring.size();
for( size_t index = 0; index != outer_count - 1; ++index )
{
const vec2f & v = shape_vertex_ring[index];
p2t_points.push_back( p2t::Point( v.x, v.y ) );
p2t::Point * p = &p2t_points.back();
p2t_polygon.push_back( p );
}
p2t::CDT cdt( p2t_polygon );
const BoostPolygon::inner_container_type & shape_vertex_inners = shape_vertex.inners();
size_t inners_count = shape_vertex_inners.size();
for( size_t index_inners = 0; index_inners != inners_count; ++index_inners )
{
std::vector<p2t::Point *> p2t_hole;
const BoostPolygon::ring_type & shape_vertex_inners_ring = shape_vertex_inners[index_inners];
size_t inner_count = shape_vertex_inners_ring.size();
for( size_t index_inner = 0; index_inner != inner_count - 1; ++index_inner )
{
const vec2f & v = shape_vertex_inners_ring[index_inner];
p2t_points.push_back( p2t::Point( v.x, v.y ) );
p2t::Point * p = &p2t_points.back();
p2t_hole.push_back( p );
}
cdt.AddHole( p2t_hole );
}
cdt.Triangulate();
std::vector<p2t::Triangle *> triangles = cdt.GetTriangles();
for( std::vector<p2t::Triangle *>::iterator
it_triangle = triangles.begin(),
it_triangle_end = triangles.end();
it_triangle != it_triangle_end;
++it_triangle )
{
p2t::Triangle * tr = *it_triangle;
p2t::Point * p0 = tr->GetPoint( 0 );
p2t::Point * p1 = tr->GetPoint( 1 );
p2t::Point * p2 = tr->GetPoint( 2 );
if( std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p0 ) == p2t_polygon_trinagles.end() )
{
p2t_polygon_trinagles.push_back( p0 );
}
if( std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p1 ) == p2t_polygon_trinagles.end() )
{
p2t_polygon_trinagles.push_back( p1 );
}
if( std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p2 ) == p2t_polygon_trinagles.end() )
{
p2t_polygon_trinagles.push_back( p2 );
}
}
for( std::vector<p2t::Triangle *>::iterator
it_triangle = triangles.begin(),
it_triangle_end = triangles.end();
it_triangle != it_triangle_end;
++it_triangle )
{
p2t::Triangle * tr = *it_triangle;
p2t::Point * p0 = tr->GetPoint( 0 );
p2t::Point * p1 = tr->GetPoint( 1 );
p2t::Point * p2 = tr->GetPoint( 2 );
uint32_t i0 = (uint32_t)std::distance( p2t_polygon_trinagles.begin(), std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p0 ) );
uint32_t i1 = (uint32_t)std::distance( p2t_polygon_trinagles.begin(), std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p1 ) );
uint32_t i2 = (uint32_t)std::distance( p2t_polygon_trinagles.begin(), std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p2 ) );
shape_indices.push_back( i0 );
shape_indices.push_back( i1 );
shape_indices.push_back( i2 );
}
}
if( output.empty() == true )
{
mesh.vertexCount = 0U;
mesh.indexCount = 0U;
}
else
{
size_t shapeVertexCount = p2t_polygon_trinagles.size();
size_t shapeIndicesCount = shape_indices.size();
mesh.vertexCount = (uint16_t)shapeVertexCount;
mesh.indexCount = (uint16_t)shapeIndicesCount;
mesh.pos.resize( shapeVertexCount );
mesh.uv.resize( shapeVertexCount );
mesh.indices.resize( shapeIndicesCount );
for( size_t i = 0; i != shapeVertexCount; ++i )
{
const p2t::Point * shape_pos = p2t_polygon_trinagles[i];
mesh.pos[i].x = (float)shape_pos->x;
mesh.pos[i].y = (float)shape_pos->y;
mesh.uv[i].x = ((float)shape_pos->x - image_trim_offset.x) / image_trim_size.x;
mesh.uv[i].y = ((float)shape_pos->y - image_trim_offset.y) / image_trim_size.y;
}
for( size_t i = 0; i != shapeIndicesCount; ++i )
{
mesh.indices[i] = (uint16_t)shape_indices[i];
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////
int APIENTRY wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nShowCmd )
{
(void)hInstance;
(void)hPrevInstance;
(void)nShowCmd;
std::wstring arg_image_bb;
std::wstring arg_image_base_size;
std::wstring arg_image_trim_size;
std::wstring arg_image_trim_offset;
std::wstring arg_polygon_input;
bool image_bb = parse_kwds( lpCmdLine, L"--bb", false );
float base_width = parse_kwds( lpCmdLine, L"--base_width", 0.f );
float base_height = parse_kwds( lpCmdLine, L"--base_height", 0.f );
float trim_width = parse_kwds( lpCmdLine, L"--trim_width", 0.f );
float trim_height = parse_kwds( lpCmdLine, L"--trim_height", 0.f );
float trim_offset_x = parse_kwds( lpCmdLine, L"--trim_offset_x", 0.f );
float trim_offset_y = parse_kwds( lpCmdLine, L"--trim_offset_y", 0.f );
bool image_subtract = parse_kwds( lpCmdLine, L"--subtract", false );
TVectorPoints points = parse_kwds( lpCmdLine, L"--points", TVectorPoints() );
std::wstring result_path = parse_kwds( lpCmdLine, L"--result_path", std::wstring() );
vec2f image_base_size( base_width, base_height );
vec2f image_trim_size( trim_width, trim_height );
vec2f image_trim_offset( trim_offset_x, trim_offset_y );
Mesh mesh;
bool successful = polygonize( image_base_size, image_trim_size, image_trim_offset, image_bb, image_subtract, points, mesh );
WCHAR infoCanonicalizeQuote[MAX_PATH];
ForcePathQuoteSpaces( infoCanonicalizeQuote, result_path.c_str() );
PathUnquoteSpaces( infoCanonicalizeQuote );
FILE * f_result;
errno_t err = _wfopen_s( &f_result, infoCanonicalizeQuote, L"wt" );
if( err != 0 )
{
message_error( "invalid _wfopen %ls err %d\n"
, infoCanonicalizeQuote
, err
);
return 0;
}
if( successful == false )
{
fprintf_s( f_result, "# invalid polygonize\n" );
}
else
{
fprintf_s( f_result, "%u\n", mesh.vertexCount );
fprintf_s( f_result, "%u\n", mesh.indexCount );
fprintf_s( f_result, "" );
for( uint16_t i = 0; i != mesh.vertexCount; ++i )
{
if( i != 0 )
{
fprintf_s( f_result, "," );
}
const vec2f & pos = mesh.pos[i];
fprintf_s( f_result, " %12f, %12f"
, pos.x
, pos.y
);
}
fprintf_s( f_result, "\n" );
fprintf_s( f_result, "" );
for( uint16_t i = 0; i != mesh.vertexCount; ++i )
{
if( i != 0 )
{
fprintf_s( f_result, "," );
}
const vec2f & uv = mesh.uv[i];
fprintf_s( f_result, " %12f, %12f"
, uv.x
, uv.y
);
}
fprintf_s( f_result, "\n" );
fprintf_s( f_result, "" );
for( uint16_t i = 0; i != mesh.indexCount; ++i )
{
if( i != 0 )
{
fprintf_s( f_result, "," );
}
uint16_t index = mesh.indices[i];
fprintf_s( f_result, " %u"
, index
);
}
fprintf_s( f_result, "\n" );
}
fclose( f_result );
return 0;
} | 27.731449 | 198 | 0.544151 | Terryhata6 |
6c498967d740eb97a5685813c5aae8ff8f89b416 | 63,514 | cpp | C++ | OSGExport.cpp | mattjr/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | 14 | 2015-01-11T02:53:04.000Z | 2021-11-25T17:31:22.000Z | OSGExport.cpp | skair39/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | null | null | null | OSGExport.cpp | skair39/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | 14 | 2015-07-21T04:47:52.000Z | 2020-03-12T12:31:25.000Z | //
// structured - Tools for the Generation and Visualization of Large-scale
// Three-dimensional Reconstructions from Image Data. This software includes
// source code from other projects, which is subject to different licensing,
// see COPYING for details. If this project is used for research see COPYING
// for making the appropriate citations.
// Copyright (C) 2013 Matthew Johnson-Roberson <mattkjr@gmail.com>
//
// This file is part of structured.
//
// structured 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.
//
// structured 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 structured. If not, see <http://www.gnu.org/licenses/>.
//
#include "OSGExport.h"
#include <osgUtil/TriStripVisitor>
#include <osgUtil/SmoothingVisitor>
#include <osgUtil/Optimizer>
#include <osg/GraphicsContext>
#include <osg/TexEnvCombine>
#include <osg/PolygonMode>
#include <osg/TextureRectangle>
#include <osgDB/WriteFile>
#include <osg/Point>
#include <osgUtil/Simplifier>
#include <osg/PolygonOffset>
#include <osg/ShapeDrawable>
#include <cv.h>
#include <glib.h>
#include <osg/io_utils>
#include <highgui.h>
#include <boost/thread/thread.hpp>
#include <sys/stat.h>
#include "auv_texture_utils.hpp"
#include "auv_lod.hpp"
#include "auv_gts_utils.hpp"
#include "auv_tex_projection.hpp"
#include "adt_image_norm.hpp"
//#include "colormaps.h"
using namespace libpolyp;
typedef struct _GHashNode GHashNode;
using namespace libsnapper;
using namespace squish;
MyGraphicsContext *mgc=NULL;
std::vector<GtsBBox *> bboxes_all;;
std::vector<GeometryCollection *> gc_ptrs;
boost::mutex bfMutex;
class UnrefTextureAtlas : public osg::NodeVisitor
{
public:
UnrefTextureAtlas():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
{}
virtual void apply(osg::Node& node)
{
if (node.getStateSet()) apply(*node.getStateSet());
traverse(node);
}
virtual void apply(osg::Geode& node)
{
if (node.getStateSet()) apply(*node.getStateSet());
for(unsigned int i=0;i<node.getNumDrawables();++i)
{
osg::Drawable* drawable = node.getDrawable(i);
if (drawable && drawable->getStateSet()) apply(*drawable->getStateSet());
}
traverse(node);
}
virtual void apply(osg::StateSet& stateset)
{
// search for the existence of any texture object attributes
for(unsigned int i=0;i<stateset.getTextureAttributeList().size();++i)
{
osg::Texture* texture = dynamic_cast<osg::Texture*>(stateset.getTextureAttribute(i,osg::StateAttribute::TEXTURE));
if (texture)
{
_textureSet.insert(texture);
}
}
}
void unref_ptrs()
{
for(TextureSet::iterator itr=_textureSet.begin();
itr!=_textureSet.end();
++itr)
{
osg::Texture* texture = const_cast<osg::Texture*>(itr->get());
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(texture);
osg::Texture3D* texture3D = dynamic_cast<osg::Texture3D*>(texture);
// osg::ref_ptr<osg::Image> image = texture2D ? texture2D->getImage() : (texture3D ? texture3D->getImage() : 0);
// printf("texture %d image %d\n",texture->referenceCount(),image->referenceCount());
if(texture2D){
while(texture2D->referenceCount()>0){
texture2D->unref();
}
}else if(texture3D){
while(texture3D->referenceCount()>0){
texture3D->unref();
}
}
//printf("texture %d image %d\n",texture->referenceCount(),image->referenceCount());
}
}
typedef std::set< osg::ref_ptr<osg::Texture> > TextureSet;
TextureSet _textureSet;
};
class SetDynamicStateSetVisitor : public osg::NodeVisitor
{
public:
SetDynamicStateSetVisitor():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_numStateSetChanged(0)
{
osg::notify(osg::INFO)<< "Running DynamicStateSet..."<<std::endl;
}
~SetDynamicStateSetVisitor()
{
osg::notify(osg::INFO)<<" Number of StateState removed "<<_numStateSetChanged<<std::endl;
}
virtual void apply(osg::Node& node)
{
if (node.getStateSet())
{
node.getStateSet()->setDataVariance(osg::Object::DYNAMIC);
++_numStateSetChanged;
}
traverse(node);
}
virtual void apply(osg::Geode& node)
{
if (node.getStateSet())
{
node.getStateSet()->setDataVariance(osg::Object::DYNAMIC);
++_numStateSetChanged;
}
for(unsigned int i=0;i<node.getNumDrawables();++i)
{
osg::Drawable* drawable = node.getDrawable(i);
if (drawable && drawable->getStateSet())
{
drawable->getStateSet()->setDataVariance(osg::Object::DYNAMIC);
++_numStateSetChanged;
}
}
traverse(node);
}
unsigned int _numStateSetChanged;
};
void OSGExporter::compress(osg::Texture2D* texture2D, osg::Texture::InternalFormatMode internalFormatMode){
if(!state)
state = new osg::State;
osg::ref_ptr<osg::Image> image = texture2D->getImage();
if (image.valid() &&
(image->getPixelFormat()==GL_RGB || image->getPixelFormat()==GL_RGBA) ){//&&
// (image->s()>=32 && image->t()>=32)){
//internalFormatMode=osg::Texture::USE_S3TC_DXT1_COMPRESSION;
texture2D->setInternalFormatMode(internalFormatMode);
// need to disable the unref after apply, other the image could go out of scope.
bool unrefImageDataAfterApply = texture2D->getUnRefImageDataAfterApply();
texture2D->setUnRefImageDataAfterApply(false);
// get OpenGL driver to create texture from image.
texture2D->apply(*state);
// restore the original setting
texture2D->setUnRefImageDataAfterApply(unrefImageDataAfterApply);
image->readImageFromCurrentTexture(state->getContextID(),true);
texture2D->setInternalFormatMode(osg::Texture::USE_IMAGE_DATA_FORMAT);
}
}
void bin_face_mat_osg (T_Face * f, gpointer * data){
MaterialToGeometryCollectionMap *mtgcm=(MaterialToGeometryCollectionMap *)data[0];
//uint uiFace = *((guint *) data[1]);
if(mtgcm->count(f->material) <= 0){
GeometryCollection *gc_tmp = new GeometryCollection;
gc_ptrs.push_back(gc_tmp);
(*mtgcm)[f->material]= gc_tmp;
}
GeometryCollection& gc = *(*mtgcm)[f->material];
gc._numPoints += 3;
gc._numPrimitives += 1;
if (f->material >= 0) {
gc._numPrimitivesWithTexCoords += 1;
}
GUINT_TO_POINTER ((*((guint *) data[1]))++);
}
static void add_face_mat_osg (T_Face * f, gpointer * data){
MaterialToGeometryCollectionMap *mtgcm=(MaterialToGeometryCollectionMap *)data[0];
float *zrange = (float *)data[4];
map<int,string> *textures = (map<int,string> *)data[3];
ClippingMap *cm=(ClippingMap *)data[2];
GeometryCollection& gc = *(*mtgcm)[f->material];
osg::BoundingBox &texLimits=(*cm)[osgDB::getSimpleFileName((*textures)[f->material])];
//int planeTexSize=(long int)data[7];
map<int,int> *texnum2arraynum=(map<int,int> *)data[9];
vector<Plane3D> *planes=(vector<Plane3D> *)data[10];
osg::PrimitiveSet::Mode mode;
mode = osg::PrimitiveSet::TRIANGLES;
gc._geom->addPrimitiveSet(new osg::DrawArrays(mode,gc._coordCount,3));
gc._coordCount += 3;
TVertex * v1,* v2,* v3;
gts_triangle_vertices(>S_FACE(f)->triangle,(GtsVertex **)& v1,
(GtsVertex **)&v2, (GtsVertex **)&v3);
/* (*gc._vertices++).set(GTS_VERTEX(v1)->p.y,GTS_VERTEX(v1)->p.x,-GTS_VERTEX(v1)->p.z);
(*gc._vertices++).set(GTS_VERTEX(v2)->p.y,GTS_VERTEX(v2)->p.x,-GTS_VERTEX(v2)->p.z);
(*gc._vertices++).set(GTS_VERTEX(v3)->p.y,GTS_VERTEX(v3)->p.x,-GTS_VERTEX(v3)->p.z);*/
(*gc._vertices++).set(GTS_VERTEX(v1)->p.x,GTS_VERTEX(v1)->p.y,GTS_VERTEX(v1)->p.z);
(*gc._vertices++).set(GTS_VERTEX(v2)->p.x,GTS_VERTEX(v2)->p.y,GTS_VERTEX(v2)->p.z);
(*gc._vertices++).set(GTS_VERTEX(v3)->p.x,GTS_VERTEX(v3)->p.y,GTS_VERTEX(v3)->p.z);
if(gc._planeTexValid && planes){
if(v1->plane >= 0)
(*gc._texcoordsPlane++).set((*planes)[v1->plane].u[0], (*planes)[v1->plane].u[1],(*planes)[v1->plane].u[2],(*planes)[v1->plane].d0);
else
(*gc._texcoordsPlane++).set(-1.0,-1.0,-1.0,-1.0);
if(v2->plane >= 0)
(*gc._texcoordsPlane++).set((*planes)[v2->plane].u[0], (*planes)[v2->plane].u[1],(*planes)[v2->plane].u[2],(*planes)[v2->plane].d0);
else
(*gc._texcoordsPlane++).set(-1.0,-1.0,-1.0,-1.0);
if(v3->plane >= 0)
(*gc._texcoordsPlane++).set((*planes)[v3->plane].u[0], (*planes)[v3->plane].u[1],(*planes)[v3->plane].u[2],(*planes)[v3->plane].d0);
else
(*gc._texcoordsPlane++).set(-1.0,-1.0,-1.0,-1.0);
}
if (gc._texturesActive){// && f->material >= 0){
texLimits.expandBy(v1->u,1-v1->v,0.0);
texLimits.expandBy(v2->u,1-v2->v,0.0);
texLimits.expandBy(v3->u,1-v3->v,0.0);
if(f->material >= 0){
(*gc._texcoords++).set(v1->u,1-v1->v);
(*gc._texcoords++).set(v2->u,1-v2->v);
(*gc._texcoords++).set(v3->u,1-v3->v);
}
if(texnum2arraynum != NULL){
for(int i=0; i< 4; i++){
// if((*texnum2arraynum)[f->materialB[i]] == 0 && f->materialB[i] >= 0)
// printf("Broken %d %d\n",f->materialB[i],f->material);
if(f->materialB[i] == -1 || texnum2arraynum->count(f->materialB[i]) <=0 ){
(*gc._texcoordsTexArray[i]++).set(-1,-1,-1);
(*gc._texcoordsTexArray[i]++).set(-1,-1,-1);
(*gc._texcoordsTexArray[i]++).set(-1,-1,-1);
}else{
(*gc._texcoordsTexArray[i]++).set(v1->uB[i], 1 - v1->vB[i],(*texnum2arraynum)[f->materialB[i]]);
(*gc._texcoordsTexArray[i]++).set(v2->uB[i], 1 - v2->vB[i],(*texnum2arraynum)[f->materialB[i]]);
(*gc._texcoordsTexArray[i]++).set(v3->uB[i], 1 - v3->vB[i],(*texnum2arraynum)[f->materialB[i]]);
}
}
}
}else
gc._texturesActive=false;
if(gc._colorsActive){
// if(!shader_colori){
{
if(!zrange){
(*gc._colors++).set(0.5,0.5,0.5,0.0);
(*gc._colors++).set(0.5,0.5,0.5,0.0);
(*gc._colors++).set(0.5,0.5,0.5,0.0);
}
float range=zrange[1]-zrange[0];
Lut_Vec color;
float val;// r,g,b,val;
Colors::eColorMap map=Colors::eRainbowMap;
val = clamp ( ( GTS_VERTEX(v1)->p.z -zrange[0] )/range , 0.0f, 1.0f);
color=GlobalColors()->Get(map, val);
(*gc._colors++).set(color[0],color[1],color[2],1.0);
// jet_color_map(val,r,g,b);
//(*gc._colors++).set(r,b,g,1.0);
val = clamp ( ( GTS_VERTEX(v2)->p.z -zrange[0] )/range, 0.0f, 1.0f);;
color=GlobalColors()->Get(map, val);
(*gc._colors++).set(color[0],color[1],color[2],1.0);
//jet_color_map(val,r,g,b);
// (*gc._colors++).set(r,b,g,1.0);
val = clamp ( ( GTS_VERTEX(v3)->p.z -zrange[0] )/range, 0.0f, 1.0f);
color=GlobalColors()->Get(map, val);
(*gc._colors++).set(color[0],color[1],color[2],1.0);
//jet_color_map(val,r,g,b);
// (*gc._colors++).set(r,b,g,1.0);
}/*else{
//(*gc._colors++).set(v1->r/255.0,v1->g/255.0,v1->b/255.0,1.0);
// (*gc._colors++).set(v2->r/255.0,v2->g/255.0,v2->b/255.0,1.0);
// (*gc._colors++).set(v3->r/255.0,v3->g/255.0,v3->b/255.0,1.0);
(*gc._colors++).set(v1->r,v1->g,v1->b,1.0);
(*gc._colors++).set(v2->r,v2->g,v2->b,1.0);
(*gc._colors++).set(v3->r,v3->g,v3->b,1.0);
}*/
}
}
osg::ref_ptr<osg::Image>OSGExporter::cacheCompressedImage(IplImage *img,string name,int tex_size){
string ddsname=osgDB::getNameLessExtension(name);
ddsname +=".dds";
IplImage *tex_img=cvCreateImage(cvSize(tex_size,tex_size),
IPL_DEPTH_8U,3);
if(img && tex_img)
cvResize(img,tex_img);
else
printf("Invalid Images\n");
osg::ref_ptr<osg::Image> image= Convert_OpenCV_TO_OSG_IMAGE(tex_img);
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
texture->setImage(image.get());
compress(texture.get());
osgDB::writeImageFile(*image.get(),ddsname);
cvReleaseImage(&tex_img);
return image;
}
osg::ref_ptr<osg::Image>OSGExporter::cacheImage(IplImage *img,string name,int tex_size,bool ret){
IplImage *tex_img=cvCreateImage(cvSize(tex_size,tex_size),
IPL_DEPTH_8U,3);
if(img && tex_img)
cvResize(img,tex_img,CV_INTER_AREA);
else
printf("Invalid Images\n");
if(ret){
osg::ref_ptr<osg::Image> image= Convert_OpenCV_TO_OSG_IMAGE(tex_img);
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
texture->setImage(image.get());
osgDB::writeImageFile(*image.get(),name);
cvReleaseImage(&tex_img);
return image;
}
else {
cvSaveImage(name.c_str(),tex_img);
cvReleaseImage(&tex_img);
}
return NULL;
}
osg::Image *OSGExporter::decompressImage(osg::Image * img_ptr){
osg::Image *image_full= new osg::Image();
unsigned char *newdata = new unsigned char[img_ptr->s()*img_ptr->t()*3*sizeof(unsigned char)];
decompressed_ptrs.push_back(image_full);
DecompressImageRGB(newdata,img_ptr->s(),img_ptr->t(),img_ptr->data(),squish::kDxt1);
image_full->setImage(img_ptr->s(),img_ptr->t(),img_ptr->r(),osg::Texture::USE_IMAGE_DATA_FORMAT,GL_RGB,GL_UNSIGNED_BYTE,newdata,osg::Image::USE_NEW_DELETE);
return image_full;
}
osg::Image *OSGExporter::getCachedCompressedImage(string name,int size){
IplImage *img=NULL;
string basename=osgDB::getSimpleFileName(name);
string ddsname=osgDB::getNameLessExtension(name);
ddsname +=".dds";
bool cachedLoaded=false;
osg::Image *filecached;
if(compressed_img_cache.find(basename) == compressed_img_cache.end() || !compressed_img_cache[basename] ){
if(FileExists(ddsname)){
filecached=osgDB::readImageFile(ddsname);
if(filecached){
cachedLoaded=true;
filecached->ref();
}
}
if(!cachedLoaded){
img = cvLoadImage(name.c_str(),-1);
if(!img){
printf("In Cached Compressed Img Load failed %s.\n",name.c_str());
return NULL;
}
else{
osg::ref_ptr<osg::Image> comp_img=cacheCompressedImage(img,ddsname,size).get();
filecached=comp_img.get();
comp_img->ref();
}
}
filecached->setFileName(basename);
compressed_img_cache[basename]=filecached;
}else{
filecached=compressed_img_cache[basename];
}
if(filecached && filecached->s() == size && filecached->t() == size){
if(!compress_tex || do_atlas){
osg::Image *ret=decompressImage(filecached);
return ret;
}
return filecached;
}
int resize=filecached->s();
unsigned int i=0;
for(i=0; i < filecached->getNumMipmapLevels()-1; i++){
if(resize <= size)
break;
resize >>= 1;
}
if(resize == 0)
resize=1;
osg::Image *retImage=new osg::Image;
downsampled_img_ptrs.push_back(retImage);
int datasize=filecached->getTotalSizeInBytesIncludingMipmaps()-filecached->getMipmapOffset(i);
unsigned char *newdata = new unsigned char[datasize];
resize_data_ptrs.push_back(newdata);
memcpy(newdata,filecached->getMipmapData(i),datasize);
retImage->setImage(resize,resize,filecached->r(),filecached->getInternalTextureFormat() ,filecached->getPixelFormat(),filecached->getDataType(),newdata,osg::Image::USE_NEW_DELETE);
osg::Image::MipmapDataType mipmaps;
mipmaps=filecached->getMipmapLevels();
int newsize= mipmaps[i]-mipmaps[i-1];
int base=mipmaps[i];
std::vector<unsigned int>newmipmap;
for(int k=i; k < (int)mipmaps.size(); k++){
newmipmap.push_back(newsize+(mipmaps[k]-base));
}
retImage->setMipmapLevels(newmipmap);
retImage->setFileName(basename);
if(!compress_tex || do_atlas){
osg::Image *ret=decompressImage(retImage);
return ret;
}
else
return retImage;
}
osg::Image *OSGExporter::getCachedImage(string name,int size){
IplImage *img=NULL;
string basename=osgDB::getSimpleFileName(name);
bool cachedLoaded=false;
IplImage *filecached=NULL;
if(tex_image_cache.find(basename) == tex_image_cache.end() || !tex_image_cache[basename] ){
if(FileExists(name)){
filecached=cvLoadImage(name.c_str(),1);
if(filecached){
cachedLoaded=true;
}
}
if(!cachedLoaded){
img = cvLoadImage((string("img/")+basename).c_str(),1);
if(!img){
printf("In Cached Compressed Img Load failed %s.\n",name.c_str());
return NULL;
}
else{
osg::ref_ptr<osg::Image> comp_img=cacheImage(img,name,size).get();
filecached=img;
}
}
tex_image_cache[basename]=filecached;
}else{
filecached=tex_image_cache[basename];
}
IplImage *tex_img=NULL;
IplImage *small_img=NULL;
if(filecached->width == size && filecached->height == size){
tex_img=filecached;
osg::Image *retImage =Convert_OpenCV_TO_OSG_IMAGE(tex_img,true,false);
return retImage;
}else{
small_img =cvCreateImage(cvSize(size,size),
IPL_DEPTH_8U,3);
if(filecached && small_img)
cvResize(filecached,small_img);
else
printf("Invalid Images\n");
osg::Image *retImage =Convert_OpenCV_TO_OSG_IMAGE(small_img,false,false);
cvReleaseImageHeader(&small_img);
return retImage;
}
}
#define TEXUNIT_ARRAY 0
#define TEXUNIT_HIST 2
#define TEXUNIT_INFO 3
#define TEXUNIT_PLANES 1
void OSGExporter::calcHists( MaterialToGeometryCollectionMap &mtgcm, map<int,string> textures, Hist_Calc &histCalc){
MaterialToGeometryCollectionMap::iterator itr;
for(itr=mtgcm.begin(); itr!=mtgcm.end(); ++itr){
GeometryCollection& gc = *(itr->second);
if(!gc._texturesActive )
continue;
string name=textures[itr->first];
IplImage *scaled=NULL;
scaled=tex_image_cache[osgDB::getSimpleFileName(name)];
if(!scaled){
printf("Image null in getTextureHists %s\n",name.c_str());
continue;
}
// IplImage *tmp=cvCreateImage(cvSize(img->s(),img->t()),
// IPL_DEPTH_8U,3);
IplImage *mask=cvNewGray(scaled);
cvZero(mask);
//DecompressImageRGB((unsigned char *)tmp->imageData,tmp->width,tmp->height,img->data(),squish::kDxt1);
int count = 3;
CvPoint pt[3];
CvPoint* tri=pt;
for(int i=0; i< (int) gc._texcoordArray->size(); i+=3){
for(int j=0; j<3; j++){
osg::Vec2f tc = (*gc._texcoordArray)[i+j];
tc *= scaled->width;
pt[j]=cvPoint((int)tc[1],(int)tc[0]);
}
cvFillPoly(mask, &tri, &count, 1, CV_RGB(255,255,255));
}
histCalc.calc_hist(scaled,mask,1/*BGR*/);
if(gpuNovelty){
osg::Texture *tex=osg_tex_map[itr->first];
if(!tex){
printf("Null Texture in calcHist %s\n",textures[itr->first].c_str());
continue;
}
IplImage *rgba=cvCreateImage(cvSize(scaled->width,scaled->height),
IPL_DEPTH_8U,4);
cvCvtColor(scaled, rgba, CV_RGB2RGBA);
cvSetImageCOI(rgba,4);
cvCopy(histCalc.imageTex,rgba);
cvSetImageCOI(rgba,0);
// cvNamedWindow("ASDAS",-1);
// cvShowImage("ASDAS",rgba);
// cvWaitKey(0);
osg::Image *imageWithG=Convert_OpenCV_TO_OSG_IMAGE(rgba,false);
//osgDB::Registry::instance()->writeImage( *imageWithG,"ass.png",NULL);
// exit(0);
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(tex);
texture2D->setImage(imageWithG);
// compress(texture2D,osg::Texture::USE_S3TC_DXT5_COMPRESSION);
}
// cvReleaseImage(&scaled);
cvReleaseImage(&mask);
}
}
void OSGExporter::addNoveltyTextures( MaterialToGeometryCollectionMap &mtgcm, map<int,string> textures, Hist_Calc &histCalc,CvHistogram *hist){
MaterialToGeometryCollectionMap::iterator itr;
for(itr=mtgcm.begin(); itr!=mtgcm.end(); ++itr){
GeometryCollection& gc = *(itr->second);
if(!gc._texturesActive )
continue;
IplImage *novelty_channel=NULL;
string name=textures[itr->first];
if(novelty_image_cache.count(osgDB::getSimpleFileName(name)) > 0 && novelty_image_cache[osgDB::getSimpleFileName(name)]){
novelty_channel=novelty_image_cache[osgDB::getSimpleFileName(name)];
}
osg::Texture *tex=osg_tex_map[itr->first];
IplImage *tmp=NULL;
tmp=tex_image_cache[osgDB::getSimpleFileName(name)];
if(!tmp || !tex){
printf("Image null in addNovletyTextures %s\n",osgDB::getSimpleFileName(name).c_str());
continue;
}
IplImage *scaled=cvCreateImage(cvSize(histCalc.width,histCalc.height),
IPL_DEPTH_8U,3);
cvResize(tmp,scaled);
if(!novelty_channel){
if(!hist)
continue;
IplImage *med=cvNewGray(scaled);
// DecompressImageRGB((unsigned char *)tmp->imageData,tmp->width,tmp->height,img->data(),squish::kDxt1);
IplImage *novelty_image= histCalc.get_novelty_img(scaled,hist);
mcvNormalize((IplImage*)novelty_image, (IplImage*)novelty_image, 0, 255);
// IplImage *texInfo=cvNewColor(novelty_image);
IplImage *tmpG=cvNewGray(novelty_image);
//cvZero(texInfo);
cvConvertScale(novelty_image,tmpG);
cvSmooth(tmpG,med,CV_MEDIAN,9);
novelty_channel=med;
novelty_image_cache[osgDB::getSimpleFileName(name)]=novelty_channel;
cvReleaseImage(&tmpG);
cvReleaseImage(&novelty_image);
}
IplImage *rgba=cvCreateImage(cvSize(histCalc.width,histCalc.height),
IPL_DEPTH_8U,4);
IplImage *scaled_novelty=cvCreateImage(cvSize(histCalc.width,histCalc.height),IPL_DEPTH_8U,1);
cvResize(novelty_channel,scaled_novelty);
cvCvtColor(scaled, rgba, CV_RGB2RGBA);
cvSetImageCOI(rgba,4);
cvCopy(scaled_novelty,rgba);
cvSetImageCOI(rgba,0);
/* cvNamedWindow("ASDAS",-1);
cvShowImage("ASDAS",scaled_novelty);
cvWaitKey(5);*/
osg::Image *imageWithG=Convert_OpenCV_TO_OSG_IMAGE(rgba,false);
//osgDB::Registry::instance()->writeImage( *imageWithG,"ass.png",NULL);
// exit(0);
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(tex);
texture2D->setImage(imageWithG);
// compress(texture2D,osg::Texture::USE_S3TC_DXT5_COMPRESSION);
/* }else{
cvSetImageCOI(texInfo,1);
cvCopy(med,texInfo);
cvSetImageCOI(texInfo,0);
cvNamedWindow("ASDAS",-1);
cvShowImage("ASDAS",texInfo);
cvWaitKey(0);
osg::Image *texI=Convert_OpenCV_TO_OSG_IMAGE(texInfo,false);
osg::Texture2D* texture2D = new osg::Texture2D(texI);
compress(texture2D,osg::Texture::USE_S3TC_DXT1_COMPRESSION);
gc._geom->getStateSet()->setTextureAttribute(TEXUNIT_INFO,texture2D );
cvReleaseImage(&texInfo);
}*/
}
// cvReleaseImage(&tmp);
}
bool OSGExporter::convertGtsSurfListToGeometry(GtsSurface *s, map<int,string> textures,ClippingMap *cm,int proj_tex_size,int tex_size,osg::ref_ptr<osg::Geode>*group,vector<Plane3D> planes,vector<TriMesh::BBox> bounds,osg::Matrix *rot,VerboseMeshFunc vmcallback,float *zrange,std::map<int,osg::Matrixd> *camMatrices,std::map<string,int> *classes,int num_class_id,osg::Group *toggle_ptr)
{
gpuNovelty=false;
_tex_size=tex_size;
map<int,int> texnum2arraynum;
gpointer data[11];
gint n=0;
data[0]=&mtgcm;
data[1] = &n;
data[2]=cm;
data[3]=&textures;
data[4]=zrange;
data[6]=zrange;
data[7]=(void *)_planeTexSize;
if(_tex_array_blend)
data[9]=&texnum2arraynum;
else
data[9]=NULL;
if(usePlaneDist)
data[10]=&planes;
else
data[10]=NULL;
if(classes && num_class_id != 0)
useClasses=true;
else
useClasses=false;
if(useClasses)
shader_coloring=true;
//data[5]=hists;
//tempFF=getPlaneTex(planes);
int numimgpertex;
if(_tex_array_blend){
const osg::Texture2DArray::Extensions* extensions =osg::Texture2DArray::getExtensions(0,true);
if (!extensions->isTexture2DArraySupported()){
numimgpertex=1;
_tex_array_blend=false;
std::cerr<<"Warning: Texture2DArray::apply(..) failed, 2D texture arrays are not support by OpenGL driver."<<std::endl;
}else{
int maxLayers=extensions->maxLayerCount();
if(verbose)
fprintf(stdout,"Max Layers for Blending %d\n",maxLayers);
numimgpertex=maxLayers;
}
}
else
numimgpertex=1;
//int overlap=max(1,(int)(numimgpertex * 0.1));
gts_surface_foreach_face (s, (GtsFunc) bin_face_mat_osg , data);
MaterialToGeometryCollectionMap::iterator itr;
vector<pair<GeometryCollection *,vector<int> > > gcAndTexIds;
int count=0;
bool first=true;
GeometryCollection *curGC=NULL;
/*
//New broken load
int numGeom=mtgcm.size();
int numSeg=(int)ceil(numGeom/(double)numimgpertex);
printf("Num Geom %d %d\n",numGeom,numSeg);
gcAndTexIds.resize(numSeg);
int c=0;
for(itr=mtgcm.begin(); itr!=mtgcm.end(); ++itr,c++){
if(itr->second == 0){
printf("Invalid %d\n",c);
}
}
itr=mtgcm.begin();
int overlap=1;
for(int i=0; i < gcAndTexIds.size(); i++){
gcAndTexIds[i].first=NULL;
for(int j=0; j < numimgpertex && itr!=mtgcm.end(); j++){
// printf("Seg: %d/%d j: %d/%d\n",i,gcAndTexIds.size(),j,numimgpertex);
if(!gcAndTexIds[i].first){
gcAndTexIds[i].first=itr->second;
if(itr->first >= 0)
gcAndTexIds[i].second.push_back(itr->first);
}else{
GeometryCollection& gc = *(itr->second);
gcAndTexIds[i].first->_numPoints += gc._numPoints;
gcAndTexIds[i].first->_numPrimitives += gc._numPrimitives;
gcAndTexIds[i].first->_numPrimitivesWithTexCoords += gc._numPrimitivesWithTexCoords;
if(itr->first >= 0)
gcAndTexIds[i].second.push_back(itr->first);
///Reset mtgcm to new merged geom
itr->second=gcAndTexIds[i].first;
}
itr++;
}
}*/
for(itr=mtgcm.begin(); itr!=mtgcm.end(); ++itr){
GeometryCollection& gc = *(itr->second);
if(count % numimgpertex == 0 || first){
vector<int> ids;
if(itr->first >= 0)
ids.push_back(itr->first);
gcAndTexIds.push_back(make_pair(itr->second,ids));
curGC=itr->second;
}
else{
gcAndTexIds.back().first->_numPoints += gc._numPoints;
gcAndTexIds.back().first->_numPrimitives += gc._numPrimitives;
gcAndTexIds.back().first->_numPrimitivesWithTexCoords += gc._numPrimitivesWithTexCoords;
if(itr->first >= 0)
gcAndTexIds.back().second.push_back(itr->first);
itr->second=curGC;
}
count++;
first=false;
}
int tex_count=0;
for(int gci=0; gci< (int)gcAndTexIds.size(); gci++){
GeometryCollection& gc = (*gcAndTexIds[gci].first);
if (gc._numPrimitives){
gc._geom = new osg::Geometry;
osg::Vec3Array* vertArray = new osg::Vec3Array(gc._numPoints);
gc._vertices = vertArray->begin();
gc._geom->setVertexArray(vertArray);
gc._planeTexValid=false;
// set up color.
if(!shader_coloring){
osg::Vec4Array* colorsArray = new osg::Vec4Array(gc._numPoints);
gc._colors=colorsArray->begin();
gc._colorsActive=true;
gc._geom->setColorArray(colorsArray);
gc._geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
}else
gc._colorsActive=false;
if(!_tex_array_blend && gcAndTexIds[gci].second.size() > 1){
fprintf(stderr,"Error blending off yet more then one texture per geometry\n");
}
osg::ref_ptr<osg::Texture2DArray> textureArray;
if(_tex_array_blend){
textureArray =new osg::Texture2DArray;
osg::Program* program=NULL;
program = new osg::Program;
program->setName( "microshader" );
osg::Shader *lerpF=new osg::Shader( osg::Shader::FRAGMENT);
osg::Shader *lerpV=new osg::Shader( osg::Shader::VERTEX);
loadShaderSource( lerpF, basedir+"lerp.frag" );
loadShaderSource( lerpV, basedir+"lerp.vert" );
program->addShader( lerpF );
program->addShader( lerpV );
textureArray->setTextureSize(tex_size,tex_size,gcAndTexIds[gci].second.size());
osg::StateSet* stateset = new osg::StateSet;
stateset->setAttributeAndModes( program, osg::StateAttribute::ON );
stateset->addUniform( new osg::Uniform("theTexture", TEXUNIT_ARRAY) );
// stateset->addUniform( new osg::Uniform( "weights", osg::Vec3(0.640f, 0.370f, 0.770f) ));
// stateset->addUniform( new osg::Uniform( "shaderOut", 1));
stateset->setTextureAttribute(TEXUNIT_ARRAY, textureArray.get());
stateset->setDataVariance(osg::Object::STATIC);
osg::Vec2Array* texcoordArray = new osg::Vec2Array(gc._numPoints);
gc._texcoords = texcoordArray->begin();
gc._geom->setTexCoordArray(0,texcoordArray);
gc._texturesActive=true;
for(int i=0; i< NUM_TEX_BLEND_COORDS; i++){
osg::Vec3Array* texcoordBlendArray =new osg::Vec3Array(gc._numPoints);
for(unsigned int j=0; j <texcoordBlendArray->size(); j++)
(*texcoordBlendArray)[i]=osg::Vec3(-1,-1,-1);
gc._texcoordsTexArray[i] = texcoordBlendArray->begin();
gc._geom->setTexCoordArray(i+1,texcoordBlendArray);
}
gc._geom->setStateSet(stateset);
//printf("New GC size %d i = %d \n",gcAndTexIds[gci].second.size(),gci);
for(int g=0; g< (int)gcAndTexIds[gci].second.size(); g++)
// printf("Dude %d\n",gcAndTexIds[gci].second[g]);
;
}
int imgNum=0;
// set up texture if needed.
for(int j=0; j < (int)gcAndTexIds[gci].second.size(); j++){
int tidx=gcAndTexIds[gci].second[j];
if(tidx < 0 || textures.count(tidx) <= 0){
printf("Really should never get here %d!!!!!\n",j);
}
std::string filename=prefixdir+textures[tidx];
osg::notify(osg::INFO) << "ctex " << filename << std::endl;
char fname[255];
sprintf(fname,"mesh/%s",textures[tidx].c_str());
++tex_count;
if(vmcallback)
vmcallback(tex_count,mtgcm.size()-1);
if(verbose)
printf("\rLoading Texture: %03d/%03d",tex_count,(int)mtgcm.size()-1);
if(!ive_out)
if(verbose)printf("\n");
fflush(stdout);
osg::ref_ptr<osg::Image> image;
// if(do_atlas)
image=getCachedImage(filename,tex_size);
// else
// image=getCachedCompressedImage(filename,tex_size);
int baseTexUnit=0;
//LoadResizeSave(filename,fname, (!ive_out),tex_size);
if (image.valid()){
if(_tex_array_blend){
texnum2arraynum[tidx]=j;
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
texture->setImage(image.get());
compress(texture.get());
textureArray->setImage(imgNum,image.get());
textureArray->setUnRefImageDataAfterApply(false);
osg_tex_arr_ptrs.push_back(textureArray);
imgNum++;
}else{
// create state
osg::StateSet* stateset = new osg::StateSet;
// create texture
osg::Texture2D* texture = new osg::Texture2D;
/* if(do_atlas || compress_tex)
texture->setUnRefImageDataAfterApply( true );
else
texture->setUnRefImageDataAfterApply( false );
*/
texture->setImage(image.get());
texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_BORDER);
texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_BORDER);
texture->setBorderColor(osg::Vec4(0.0,1.0,0.0,1.0));
//texture->setBorderWidth(1.0);
//texture->setInternalFormatMode(internalFormatMode);
stateset->setTextureAttributeAndModes(baseTexUnit,texture,
osg::StateAttribute::ON);
if(shader_coloring&& !_tex_array_blend){
if(useClasses && classes){
int class_id=-1;
if(classes->count(osgDB::getNameLessExtension(textures[tidx])))
class_id=(*classes)[osgDB::getNameLessExtension(textures[tidx])];
stateset->addUniform( new osg::Uniform( "classid", class_id/(float)(num_class_id)));
}
stateset->setDataVariance(osg::Object::STATIC);
string shader_base;
if(use_proj_tex)
shader_base="proj";
else
shader_base="hcolor";
//printf("Using proj texture\n");
osg::Program* program=NULL;
program = new osg::Program;
program->setName( "colorshaderasdas" );
program->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT,4);
program->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT,GL_POINTS);
program->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT,GL_POINTS);
// printf("Here\n");
osg::Shader *hcolorf=new osg::Shader( osg::Shader::FRAGMENT);
osg::Shader *hcolorv=new osg::Shader( osg::Shader::VERTEX);
loadShaderSource( hcolorf, basedir+shader_base+".frag" );
loadShaderSource( hcolorv, basedir+shader_base+".vert" );
program->addShader( hcolorf );
program->addShader( hcolorv );
stateset->setAttributeAndModes( program,
osg::StateAttribute::ON );
if(use_proj_tex){
osg::Matrix mat=(*camMatrices)[tidx];
// osg::Matrix texScale(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1);
//texScale(0,0)=1.0/(double)(proj_tex_size);
/// texScale(1,1)=1.0/(double)(proj_tex_size);
// cout << "tex Scale "<<texScale <<endl;
// osg::Vec3 v1(-133.381,74.1,15.0319);
//osg::Matrix mat2=mat;
// mat2.postMult(texScale);
//std::cout <<"BUG " <<v1*mat << " \n
//std::cout <<"RES " << v1*mat2<<endl;
stateset->addUniform( new osg::Uniform( "teMat",mat));
// stateset->setTextureAttributeAndModes(baseTexUnit, texMat, osg::StateAttribute::ON);
// stateset->addUniform( new osg::Uniform( "fc", osg::Vec4(_calib->fcx,_calib->fcy,_calib->ccx,_calib->ccy)));
}
}
gc._texturesActive=true;
stateset->setDataVariance(osg::Object::STATIC);
gc._geom->setStateSet(stateset);
osg::Vec2Array* texcoordArray = new osg::Vec2Array(gc._numPoints);
gc._texcoords = texcoordArray->begin();
gc._texcoordArray = texcoordArray;
gc._geom->setTexCoordArray(0,texcoordArray);
if(computeHists){
osg::Vec4Array* texcoordPlanes = new osg::Vec4Array(gc._numPoints);
gc._texcoordsPlane = texcoordPlanes->begin();
gc._geom->setTexCoordArray(TEXUNIT_PLANES,texcoordPlanes);
gc._planeTexValid=true;
}
osg_tex_ptrs.push_back(texture);
osg_tex_map[tidx]=texture;
}
}
}
}
}
if(verbose)
printf("\n");
gts_surface_foreach_face (s, (GtsFunc) add_face_mat_osg , data);
osg::ref_ptr<osg::Geode> untextured = new osg::Geode;
osg::ref_ptr<osg::Geode> textured = new osg::Geode;
osg::TextureRectangle* histTex=NULL;
osg::ref_ptr<osg::Program> novelty_program= new osg::Program;
novelty_program->setName( "microshader" );
osg::Shader *novelty=new osg::Shader( osg::Shader::FRAGMENT);
osg::Shader *distNovelty=new osg::Shader( osg::Shader::VERTEX);
if(gpuNovelty){
loadShaderSource( novelty, basedir+"novelty-live.frag" );
}else{
loadShaderSource( novelty, basedir+"novelty.frag" );
// loadShaderSource( novelty, "ass.frag" );
}
loadShaderSource( distNovelty, basedir+"novelty.vert" );
//loadShaderSource( distNovelty, "ass.vert" );
novelty_program->addShader( novelty );
novelty_program->addShader( distNovelty );
//osg::TextureRectangle* planeTex=NULL;
if(computeHists){
Hist_Calc histCalc(_tex_size,_tex_size,16,1);
if(!run_higher_res){
calcHists(mtgcm,textures,histCalc);
histCalc.get_hist(finalhist);
// cvSave("hist1.xml",finalhist);
}
if(gpuNovelty)
histTex= getTextureHists(finalhist);
else
addNoveltyTextures(mtgcm,textures,histCalc,finalhist);
// add everthing into the Geode.
// planeTex=getPlaneTex(planes,_planeTexSize);
}
osgUtil::SmoothingVisitor smoother;
for(int i=0; i< (int)gcAndTexIds.size(); i++)
{
GeometryCollection& gc = *(gcAndTexIds[i].first);
if (gc._geom)
{
gc._geom->setUseDisplayList(true);
// gc._geom->setUseVertexBufferObjects(true);
// gc._geom->setUseDisplayList(false);
// tessellator.retessellatePolygons(*gc._geom);
smoother.smooth(*gc._geom);
if(gc._texturesActive ){
textured->addDrawable(gc._geom);
}
else{
osg::StateSet *utstateset = gc._geom->getOrCreateStateSet();
if(shader_coloring){
osg::Program* program=NULL;
program = new osg::Program;
program->setName( "colorshader" );
// printf("Here\n");
osg::Shader *hcolorf=new osg::Shader( osg::Shader::FRAGMENT);
osg::Shader *hcolorv=new osg::Shader( osg::Shader::VERTEX);
loadShaderSource( hcolorf, basedir+"hcolor.frag" );
loadShaderSource( hcolorv, basedir+"hcolor.vert" );
program->addShader( hcolorf );
program->addShader( hcolorv );
utstateset->setAttributeAndModes( program, osg::StateAttribute::ON );
utstateset->addUniform( new osg::Uniform( "zrange", osg::Vec3(zrange[0], zrange[1], 0.0f) ));
// utstateset->addUniform( new osg::Uniform( "shaderOut", 0));
utstateset->addUniform( new osg::Uniform( "untex",true));
utstateset->setDataVariance(osg::Object::STATIC);
}
{
osg::Material* material = new osg::Material;
osg::Vec4 specular( 0.18, 0.18, 0.18, 0.18 );
specular *= 1.5;
float mat_shininess = 64.0f ;
osg::Vec4 ambient (0.92, 0.92, 0.92, 0.95 );
osg::Vec4 diffuse( 0.8, 0.8, 0.8, 0.85 );
material->setAmbient(osg::Material::FRONT_AND_BACK,ambient);
material->setSpecular(osg::Material::FRONT_AND_BACK,specular);
material->setShininess(osg::Material::FRONT_AND_BACK,mat_shininess);
// material->setColorMode( osg::Material::AMBIENT_AND_DIFFUSE);
//if(!applyNonVisMat){
utstateset->setAttribute(material);
// }else {
if(applyNonVisMat){
osg::PolygonOffset* polyoffset = new osg::PolygonOffset;
polyoffset->setFactor(-1.0f);
polyoffset->setUnits(-1.0f);
// osg::PolygonMode* polymode = new osg::PolygonMode;
//polymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
utstateset->setAttributeAndModes(polyoffset,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
//utstateset->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
/*
osg::Material* material = new osg::Material;
utstateset->setAttributeAndModes(material,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
utstateset->setMode(GL_LIGHTING,osg::StateAttribute::OVERRIDE|osg::StateAttribute::OFF);
//fprintf(stderr,"Apply non vis\n");
*/
}
}
untextured->addDrawable(gc._geom);
}
}
}
if(usePlaneDist){
osg::Switch *toggle_plane=new osg::Switch();
osg::Geode *planeGeode=new osg::Geode();
osg::Geode *boxGeode=new osg::Geode();
osg::StateSet* _stateset = new osg::StateSet;
osg::PolygonMode* _polygonmode = new osg::PolygonMode;
_polygonmode->setMode(osg::PolygonMode::FRONT_AND_BACK,
osg::PolygonMode::LINE);
_stateset->setAttribute(_polygonmode);
_stateset->setMode( GL_LIGHTING, osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF );
for(int i=0; i<(int)bounds.size(); i++){
osg::ref_ptr<osg::Box> b=new osg::Box(osg::Vec3(bounds[i].center()[0],
bounds[i].center()[1],
bounds[i].center()[2]),
bounds[i].size()[0],
bounds[i].size()[1],
bounds[i].size()[2]);
// printf("%f %f %f\n",bounds[i].center()[0],bounds[i].center()[1],bounds[i].center()[2]);
// printf("%f %f %f\n",bounds[i].size()[0],bounds[i].size()[1],bounds[i].size()[2]);
osg::ShapeDrawable* _shapedrawable = new osg::ShapeDrawable;
_shapedrawable->setColor(osg::Vec4(1.0,0.0,0.0,0.80));
_shapedrawable->setShape(b.get());
_shapedrawable->setStateSet(_stateset);
boxGeode->addDrawable(_shapedrawable);
osg::Geometry* linesGeom = new osg::Geometry();
Plane3D p=planes[i];
osg::Vec3 center(bounds[i].center()[0],bounds[i].center()[1],bounds[i].center()[2]);
osg::Vec3 rot_center=rot->preMult(center);
// cout << rot_center;
osg::Vec3Array* vertices = displayPlane(p,Point3D(rot_center[0],rot_center[1],rot_center[2]));
// pass the created vertex array to the points geometry object.
linesGeom->setVertexArray(vertices);
// set the colors as before, plus using the above
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(0.0f,1.0f,0.0f,1.0f));
linesGeom->setColorArray(colors);
linesGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
// set the normal in the same way color.
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back(osg::Vec3(0.0f,-1.0f,0.0f));
linesGeom->setNormalArray(normals);
linesGeom->setNormalBinding(osg::Geometry::BIND_OVERALL);
// This time we simply use primitive, and hardwire the number of coords to use
// since we know up front,
linesGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES,0,vertices->size()));
linesGeom->setStateSet(_stateset);
planeGeode->addDrawable(linesGeom);
}
osg::MatrixTransform *rotT =new osg::MatrixTransform(*rot);
rotT->addChild(boxGeode);
toggle_plane->addChild(rotT);
toggle_plane->addChild(planeGeode);
toggle_plane->setAllChildrenOff();
if(toggle_ptr)
toggle_ptr->addChild(toggle_plane);
osg::Point* point = new osg::Point();
point->setSize( 4.0 );
textured->getOrCreateStateSet()->setAttribute( point, osg::StateAttribute::ON );
}
if(computeHists){
/* int max_planes=32;
if(max_planes < planes.size()){
fprintf(stderr,"Max planes to small\n");
exit(-1);
}
osg::Vec4Array* planeArray = new osg::Vec4Array(max_planes);
if(usePlaneDist){
for(int i=0; i <max_planes; i++){
osg::Vec4 plane;
if(i < planes.size()){
plane[0]= planes[i].u[0];
plane[1]=planes[i].u[1];
plane[2]=planes[i].u[2];
plane[3]=planes[i].d0;
}
else{
plane[0]=0;
plane[1]=0;
plane[2]=0;
plane[3]=0;
}
cout << plane<<endl;
planeArray->push_back(plane);
}
textured->getOrCreateStateSet()->addUniform(new osg::Uniform("planeArray",
planeArray) );
}*/
if(gpuNovelty){
textured->getOrCreateStateSet()->addUniform(new osg::Uniform("hist",
TEXUNIT_HIST) );
textured->getOrCreateStateSet()->setTextureAttribute(TEXUNIT_HIST,
histTex);
textured->getOrCreateStateSet()->addUniform( new osg::Uniform("binsize",
16.0f));
}
//textured->getOrCreateStateSet()->addUniform(new osg::Uniform("rtex",0));
// textured->getOrCreateStateSet()->addUniform(new osg::Uniform("infoT",
// TEXUNIT_INFO));
// textured->getOrCreateStateSet()->addUniform(new osg::Uniform("planes",
// TEXUNIT_PLANES) );
// textured->getOrCreateStateSet()->setTextureAttribute(TEXUNIT_PLANES,
// planeTex);
textured->getOrCreateStateSet()->setAttributeAndModes(novelty_program,
osg::StateAttribute::ON );
}else if(shader_coloring){
osg::Program* program=NULL;
program = new osg::Program;
program->setName( "colorshader" );
// printf("Here\n");
osg::Shader *hcolorf=new osg::Shader( osg::Shader::FRAGMENT);
osg::Shader *hcolorv=new osg::Shader( osg::Shader::VERTEX);
loadShaderSource( hcolorf, basedir+"hcolor.frag" );
loadShaderSource( hcolorv, basedir+"hcolor.vert" );
program->addShader( hcolorf );
program->addShader( hcolorv );
textured->getOrCreateStateSet()->setAttributeAndModes( program,
osg::StateAttribute::ON );
textured->getOrCreateStateSet()->addUniform(new osg::Uniform( "zrange",
osg::Vec3(zrange[0],
zrange[1], 0.0f)));
textured->getOrCreateStateSet()->addUniform( new osg::Uniform( "untex",
false));
}else {
if(computeHists){
textured->getOrCreateStateSet()->setMode(GL_BLEND,
osg::StateAttribute::OFF);
textured->getOrCreateStateSet()->setMode(GL_ALPHA_TEST,
osg::StateAttribute::OFF);
}else{
osg::TexEnvCombine *te = new osg::TexEnvCombine;
// Modulate diffuse texture with vertex color.
te->setCombine_RGB(osg::TexEnvCombine::REPLACE);
te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
te->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
te->setSource1_RGB(osg::TexEnvCombine::PREVIOUS);
te->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
// Alpha doesn't matter.
te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
te->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
te->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
textured->getOrCreateStateSet()->setTextureAttribute(0, te);
/* osg::Material* material = new osg::Material;
osg::Vec4 specular( 0.18, 0.18, 0.18, 0.18 );
specular *= 1.5;
float mat_shininess = 64.0f ;
osg::Vec4 ambient (0.92, 0.92, 0.92, 0.95 );
osg::Vec4 diffuse( 0.8, 0.8, 0.8, 0.85 );
material->setAmbient(osg::Material::FRONT_AND_BACK,ambient);
material->setSpecular(osg::Material::FRONT_AND_BACK,specular);
material->setShininess(osg::Material::FRONT_AND_BACK,mat_shininess);
// material->setColorMode( osg::Material::AMBIENT_AND_DIFFUSE);
stateset->setAttribute(material);*/
}
}
if(textured->getNumDrawables())
group[0]=textured.get();
else
group[0]=NULL;
if(untextured->getNumDrawables() )
group[1]=untextured.get();
else
group[1]=NULL;
return true;
}
class CompressTexturesVisitor : public osg::NodeVisitor
{
public:
CompressTexturesVisitor(osg::Texture::InternalFormatMode internalFormatMode):
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_internalFormatMode(internalFormatMode) {}
virtual void apply(osg::Node& node)
{
if (node.getStateSet()) apply(*node.getStateSet());
traverse(node);
}
virtual void apply(osg::Geode& node)
{
if (node.getStateSet()) apply(*node.getStateSet());
for(unsigned int i=0;i<node.getNumDrawables();++i)
{
osg::Drawable* drawable = node.getDrawable(i);
if (drawable && drawable->getStateSet()) apply(*drawable->getStateSet());
}
traverse(node);
}
virtual void apply(osg::StateSet& stateset)
{
// search for the existance of any texture object attributes
for(unsigned int i=0;i<stateset.getTextureAttributeList().size();++i)
{
osg::Texture* texture = dynamic_cast<osg::Texture*>(stateset.getTextureAttribute(i,osg::StateAttribute::TEXTURE));
if (texture)
{
_textureSet.insert(texture);
}
}
}
void compress()
{
osg::notify(osg::INFO)<<"Compress TEXTURE Visitor Compressing"<<std::endl;
if(!mgc){
MyGraphicsContext context;
if (!context.valid()){
osg::notify(osg::INFO)<<"Error: Unable to create graphis context - cannot run compression"<<std::endl;
return;
}
}
osg::ref_ptr<osg::State> state = new osg::State;
for(TextureSet::iterator itr=_textureSet.begin();
itr!=_textureSet.end();
++itr)
{
osg::Texture* texture = const_cast<osg::Texture*>(itr->get());
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(texture);
osg::Texture3D* texture3D = dynamic_cast<osg::Texture3D*>(texture);
osg::ref_ptr<osg::Image> image = texture2D ? texture2D->getImage() : (texture3D ? texture3D->getImage() : 0);
if (image.valid() &&
(image->getPixelFormat()==GL_RGB || image->getPixelFormat()==GL_RGBA) &&
(image->s()>=32 && image->t()>=32))
{
texture->setInternalFormatMode(_internalFormatMode);
// need to disable the unref after apply, other the image could go out of scope.
bool unrefImageDataAfterApply = texture->getUnRefImageDataAfterApply();
texture->setUnRefImageDataAfterApply(false);
// get OpenGL driver to create texture from image.
texture->apply(*state);
// restore the original setting
texture->setUnRefImageDataAfterApply(unrefImageDataAfterApply);
image->readImageFromCurrentTexture(0,true);
texture->setInternalFormatMode(osg::Texture::USE_IMAGE_DATA_FORMAT);
}
}
}
typedef std::set< osg::ref_ptr<osg::Texture> > TextureSet;
TextureSet _textureSet;
osg::Texture::InternalFormatMode _internalFormatMode;
};
bool OSGExporter::outputModelOSG(char *out_name, osg::ref_ptr<osg::Geode> *group,osg::Group *toggle_ptr) {
run_higher_res=true;
osg::Geode *tex=group[0].get();
osg::Geode *untex =group[1].get();
osg::Matrix trans( osg::Matrix::rotate(osg::inDegrees(-90.0f),
1.0f,0.0f,0.0f)*
osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,
1.0f,0.0f));
osg::ref_ptr<osg::MatrixTransform> positioned1 = new osg::MatrixTransform(trans);
osg::ref_ptr<osg::MatrixTransform> positioned2= new osg::MatrixTransform(trans);
if(!_tex_array_blend&& do_atlas && tex){
if(verbose)
printf("Texture Atlas Creation\n");
osgUtil::Optimizer optimizer;
osgUtil::Optimizer::TextureAtlasVisitor ctav(&optimizer);
osgUtil::Optimizer::TextureAtlasBuilder &tb=ctav.getTextureAtlasBuilder();
tb.setMargin(0);
tb.setMaximumAtlasSize(2048,2048);
tex->accept(ctav);
ctav.optimize();
int options=0;
options |= osgUtil::Optimizer::DEFAULT_OPTIMIZATIONS;
options |=osgUtil::Optimizer::TEXTURE_ATLAS_BUILDER;
optimizer.optimize(tex,options);
if(compress_tex){
if(computeHists){
CompressTexturesVisitor ctv(osg::Texture::USE_S3TC_DXT5_COMPRESSION);
tex->accept(ctv);
ctv.compress();
}else{
CompressTexturesVisitor ctv(osg::Texture::USE_S3TC_DXT1_COMPRESSION);
tex->accept(ctv);
ctv.compress();
}
}
SetDynamicStateSetVisitor sdssv;
tex->accept(sdssv);
}
osgDB::ReaderWriter::WriteResult result;
char outtex[255];
string outname_str(out_name);
if(tex && tex->getNumDrawables()){
positioned1->addChild(tex);
if(toggle_ptr)
positioned1->addChild(toggle_ptr);
strcpy(outtex,(outname_str.substr(0,outname_str.length()-4)+string("-t."+string(OSG_EXT))).c_str());
result = osgDB::Registry::instance()->writeNode(*positioned1,outtex,osgDB::Registry::instance()->getOptions());
if (result.success()) {
if(verbose)
osg::notify(osg::NOTICE)<<"Data written to '"<<outtex<<"'."<< std::endl;
}
else if (result.message().empty()){
osg::notify(osg::NOTICE)<<"Warning: file write to '"<<outtex<<"' no supported."<< std::endl;
// root->getChild(0)=NULL;
}else
osg::notify(osg::NOTICE)<<"Writer output: "<< result.message()<<std::endl;
}
if(untex && untex->getNumDrawables()){
positioned2->addChild(untex);
strcpy(outtex,(outname_str.substr(0,outname_str.length()-4)+string("-u."+string(OSG_EXT))).c_str());
result = osgDB::Registry::instance()->writeNode(*positioned2,outtex,osgDB::Registry::instance()->getOptions());
if (result.success()) {
if(verbose)
osg::notify(osg::NOTICE)<<"Data written to '"<<outtex<<"'."<< std::endl;
}
else if (result.message().empty()){
osg::notify(osg::NOTICE)<<"Warning: file write to '"<<outtex<<"' no supported."<< std::endl;
// root->getChild(0)=NULL;
}
}
/*if(do_atlas){
UnrefTextureAtlas uta;
tex->accept(uta);
uta.unref_ptrs();
}*/
/*
{
MaterialToGeometryCollectionMap::iterator itr;
for(itr=mtgcm.begin(); itr!=mtgcm.end(); ++itr){
itr->second->_geom->unref();
// if(itr->second)
//delete itr->second;
}
}*/
mtgcm.clear();
return true;
/* root->removeChild(0,1);
geode=NULL;*/
}
osg::Image *OSGExporter::LoadResizeSave(string filename,string outname,bool save,int tex_size){
IplImage *fullimg=NULL;
bool cached=false;
if(tex_image_cache.find(filename) == tex_image_cache.end() || !tex_image_cache[filename] ){
fullimg=cvLoadImage(filename.c_str(),1);
}
else{
fullimg=tex_image_cache[filename];
if(fullimg && fullimg->width < tex_size){
printf("Warning Upsampling from cached so reloading\n");
fullimg=cvLoadImage(filename.c_str(),-1);
}else{
cached=true;
}
}
IplImage *cvImg=cvCreateImage(cvSize(tex_size,tex_size),
IPL_DEPTH_8U,3);
if(fullimg){
cvResize(fullimg,cvImg);
cvReleaseImage(&fullimg);
tex_image_cache[filename]=cvImg;
}
else {
printf("Failed to load %s\n",filename.c_str());
cvReleaseImage(&cvImg);
return NULL;
}
osg::Image* image=NULL;
if(compress_tex && !_hardware_compress){
image =Convert_OpenCV_TO_OSG_IMAGE(cvImg,!cached,true);
}else
image =Convert_OpenCV_TO_OSG_IMAGE(cvImg,!cached,false);
image->setFileName(osgDB::getSimpleFileName(filename));
if(save){
//printf("Writing %s\n",outname.c_str());
osgDB::writeImageFile(*image,outname);
image->setFileName(outname);
}
return image;
}
static void texcoord_foreach_face (T_Face * f,
texGenData *data)
{
int indexClosest=find_closet_img_trans(>S_FACE(f)->triangle,
data->bboxTree,data->camPosePts,
data->back_trans,data->calib,bboxes_all,data->margin);
//fprintf(ffp,"%d\n",indexClosest);
if(indexClosest == INT_MAX){
/*fprintf(errFP,"Failed traingle\n");
gts_write_triangle(>S_FACE(f)->triangle,NULL,errFP);
fflush(errFP);*/
if(data->verbose)
libpolyp::tex_add_verbose(data->count++,data->total,data->reject++);
return;
}
if(apply_tex_to_tri(f,data->calib,data->back_trans[indexClosest],indexClosest,data->tex_size,data->margin,data->use_dist_coords))
data->validCount++;
else{
//printf("Index closest %d\n",indexClosest);
find_closet_img_trans(>S_FACE(f)->triangle,
data->bboxTree,data->camPosePts,
data->back_trans,data->calib,bboxes_all,data->margin);
}
if(data->verbose)
tex_add_verbose(data->count++,data->total,data->reject);
}
static void findimg_foreach_face (T_Face * f,
texGenData *data)
{
int indexClosest=find_first_bbox(>S_FACE(f)->triangle,
data->bboxTree,bboxes_all,data->back_trans);
//fprintf(ffp,"%d\n",indexClosest);
if(indexClosest == INT_MAX){
// fprintf(stderr,"Failed traingle\n");
//gts_write_triangle(>S_FACE(f)->triangle,NULL,stderr);
// fflush(stderr);
if(data->verbose)
libpolyp::tex_add_verbose(data->count++,data->total,data->reject++);
return;
}
//if(indexClosest != 93)
// return;
if(apply_texid_to_tri(f,indexClosest))
data->validCount++;
if(data->verbose)
tex_add_verbose(data->count++,data->total,data->reject);
}
static void texcoord_blend_foreach_face (T_Face * f,
texGenData *data)
{
int idx[NUM_TEX_BLEND_COORDS];
bool found=find_blend_img_trans(>S_FACE(f)->triangle,
data->bboxTree,data->camPosePts,
data->back_trans,data->calib,idx,bboxes_all,data->margin);
for(int i=0; i <NUM_TEX_BLEND_COORDS; i++)
//fprintf(ffp,"%d ",idx[i]);
// fprintf(ffp,"\n");
if(!found){
/*fprintf(errFP,"Failed traingle\n");
gts_write_triangle(>S_FACE(f)->triangle,NULL,errFP);
fflush(errFP);*/
if(data->verbose)
libpolyp::tex_add_verbose(data->count++,data->total,data->reject++);
return;
}
if(apply_blend_tex_to_tri(f,data->calib,data->back_trans,idx,data->tex_size,data->margin))
data->validCount++;
else{
//printf("Failed\n");
}
if(data->verbose)
tex_add_verbose(data->count++,data->total,data->reject);
}
static void findborder_blend_foreach_face (T_Face * f,
texGenData *data)
{
GtsTriangle * t = >S_FACE(f)->triangle;
TVertex * v1,* v2,* v3;
gts_triangle_vertices(t,(GtsVertex **)& v1,
(GtsVertex **)&v2, (GtsVertex **)&v3);
for(int i=0; i < NUM_TEX_BLEND_COORDS; i++){
if(f->materialB[i] != v1->idB[i] || f->materialB[i] != v2->idB[i] || f->materialB[i] != v3->idB[i]){
boost::mutex::scoped_lock scoped_lock(bfMutex);
data->border_faces->push_back(f);
return;
}
}
}
static void findborder_foreach_face (T_Face * f,
texGenData *data)
{
GtsTriangle * t = >S_FACE(f)->triangle;
TVertex * v1,* v2,* v3;
gts_triangle_vertices(t,(GtsVertex **)& v1,
(GtsVertex **)&v2, (GtsVertex **)&v3);
if(f->material != v1->id || f->material != v2->id || f->material != v3->id){
boost::mutex::scoped_lock scoped_lock(bfMutex);
data->border_faces->push_back(f);
}
}
void gen_mesh_tex_coord(GtsSurface *s ,Camera_Calib *calib, std::map<int,GtsMatrix *> back_trans,GNode * bboxTree,int tex_size, int num_threads,int verbose,int blend,int margin,bool use_dist_coords){
//ffp=fopen("w.txt","w");
//errFP=fopen("err.txt","w");
std::vector<GtsPoint> camPosePts;
GtsPoint transP;
if(verbose)
printf("Size %d\n",(int)back_trans.size());
map<int,GtsMatrix *>::iterator iter;
for( iter=back_trans.begin(); iter != back_trans.end(); iter++){
GtsMatrix *m= gts_matrix_inverse(iter->second);
transP.x=m[0][3];
transP.y=m[1][3];
transP.z=m[2][3];
camPosePts.push_back(transP);
gts_matrix_destroy(m);
}
gts_surface_foreach_vertex(s,(GtsFunc)set_tex_id_unknown,NULL);
std::vector<T_Face *> border_faces;
texGenData tex_data;
tex_data.bboxTree=bboxTree;
tex_data.camPosePts =camPosePts;
tex_data.margin=margin;
tex_data.use_dist_coords=use_dist_coords;
tex_data.back_trans=back_trans;
tex_data.validCount=0;
tex_data.tex_size=tex_size;
tex_data.count=1;
tex_data.reject=0;
tex_data.total=gts_surface_face_number(s);
tex_data.calib=calib;
tex_data.verbose=verbose;
tex_data.border_faces = &border_faces;
if(!blend){
if(num_threads > 1)
threaded_surface_foreach_face (s, (GtsFunc)texcoord_foreach_face ,
&tex_data ,num_threads);
else
gts_surface_foreach_face (s, (GtsFunc)texcoord_foreach_face ,&tex_data);
}else {
if(num_threads > 1)
threaded_surface_foreach_face (s, (GtsFunc)texcoord_blend_foreach_face ,
&tex_data ,num_threads);
else
gts_surface_foreach_face (s, (GtsFunc)texcoord_blend_foreach_face ,&tex_data);
}
//fclose(ffp);
if(verbose)
printf("\nChecking weird border cases...\n");
if(!blend){
if(num_threads > 1)
threaded_surface_foreach_face (s, (GtsFunc)findborder_foreach_face ,
&tex_data ,num_threads);
else
gts_surface_foreach_face (s, (GtsFunc)findborder_foreach_face ,&tex_data );
}else{
if(num_threads > 1)
threaded_surface_foreach_face (s, (GtsFunc)findborder_blend_foreach_face ,
&tex_data ,num_threads);
else
gts_surface_foreach_face (s, (GtsFunc)findborder_blend_foreach_face ,&tex_data );
}
tex_data.count=1;
tex_data.reject=0;
tex_data.total =border_faces.size();
for(int i=0; i < (int) border_faces.size(); i++){
T_Face *f2 = copy_face(border_faces[i],s);
if(!blend){
int idx=find_closet_img_trans(>S_FACE(f2)->triangle,bboxTree,camPosePts,back_trans,calib,bboxes_all,margin);
if(apply_tex_to_tri(f2,calib,back_trans[idx],idx,tex_size,margin,use_dist_coords))
tex_data.validCount++;
}else{
int idx[NUM_TEX_BLEND_COORDS];
if(find_blend_img_trans(>S_FACE(f2)->triangle,bboxTree,camPosePts,back_trans,calib,idx,bboxes_all,margin))
if(apply_blend_tex_to_tri(f2,calib,back_trans,idx,tex_size,margin))
tex_data.validCount++;
}
gts_surface_remove_face(s,GTS_FACE(border_faces[i]));
if(verbose)
tex_add_verbose(tex_data.count++,tex_data.total,tex_data.reject);
}
if(verbose)
printf("\nValid tex %d\n", tex_data.validCount);
}
void gen_mesh_tex_id(GtsSurface *s ,GNode * bboxTree, std::map<int,GtsMatrix *> back_trans,int num_threads,int verbose){
gts_surface_foreach_vertex(s,(GtsFunc)set_tex_id_unknown,NULL);
texGenData tex_data;
tex_data.bboxTree=bboxTree;
tex_data.validCount=0;
tex_data.count=1;
tex_data.reject=0;
tex_data.total=gts_surface_face_number(s);
tex_data.verbose=verbose;
tex_data.back_trans=back_trans;
if(num_threads > 1)
threaded_surface_foreach_face (s, (GtsFunc)findimg_foreach_face ,
&tex_data ,num_threads);
else
gts_surface_foreach_face (s, (GtsFunc)findimg_foreach_face ,&tex_data);
}
OSGExporter::~OSGExporter(){
{
map<string, IplImage *>::const_iterator itr;
for(itr = tex_image_cache.begin(); itr != tex_image_cache.end(); ++itr){
IplImage *tmp=(*itr).second;
cvReleaseImage(&tmp);
}
tex_image_cache.clear();
}
for(unsigned int i=0; i<decompressed_ptrs.size(); i++){
// decompressed_ptrs[i]->unref();
}
for(unsigned int i=0; i<resize_data_ptrs.size(); i++){
if(resize_data_ptrs[i])
delete resize_data_ptrs[i];
}
for(unsigned int i=0; i<downsampled_img_ptrs.size(); i++){
// printf(" %d\n",downsampled_img_ptrs[i]->referenceCount());
do{
downsampled_img_ptrs[i]->unref();
}while(downsampled_img_ptrs[i]->referenceCount()> 0);
}
decompressed_ptrs.clear();
{
std::map<string,osg::Image * >::const_iterator itr;
for(itr = compressed_img_cache.begin(); itr != compressed_img_cache.end(); ++itr){
itr->second->unref();
}
}
for(unsigned int i=0; i< gc_ptrs.size(); i++)
if(gc_ptrs[i])
delete gc_ptrs[i];
// Seg faults ????
gc_ptrs.clear();
}
| 31.614734 | 385 | 0.635025 | mattjr |
6c4afef01d764690e3b9357c24f62044adb16107 | 1,083 | cpp | C++ | Jit/lir/function.cpp | diogommartins/cinder | 79103e9119cbecef3b085ccf2878f00c26e1d175 | [
"CNRI-Python-GPL-Compatible"
] | 1 | 2021-11-04T07:39:43.000Z | 2021-11-04T07:39:43.000Z | Jit/lir/function.cpp | diogommartins/cinder | 79103e9119cbecef3b085ccf2878f00c26e1d175 | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | Jit/lir/function.cpp | diogommartins/cinder | 79103e9119cbecef3b085ccf2878f00c26e1d175 | [
"CNRI-Python-GPL-Compatible"
] | 1 | 2021-05-11T05:20:30.000Z | 2021-05-11T05:20:30.000Z | // Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
#include "Jit/lir/function.h"
#include "Jit/lir/blocksorter.h"
#include "Jit/lir/printer.h"
#include <stack>
#include <unordered_map>
#include <unordered_set>
namespace jit {
namespace lir {
void Function::sortBasicBlocks() {
BasicBlockSorter sorter(basic_blocks_);
basic_blocks_ = sorter.getSortedBlocks();
}
BasicBlock* Function::allocateBasicBlock() {
basic_block_store_.emplace_back(this);
BasicBlock* new_block = &basic_block_store_.back();
basic_blocks_.emplace_back(new_block);
return new_block;
}
BasicBlock* Function::allocateBasicBlockAfter(BasicBlock* block) {
auto iter = std::find_if(
basic_blocks_.begin(),
basic_blocks_.end(),
[block](const BasicBlock* a) -> bool { return block == a; });
++iter;
basic_block_store_.emplace_back(this);
BasicBlock* new_block = &basic_block_store_.back();
basic_blocks_.emplace(iter, new_block);
return new_block;
}
void Function::print() const {
std::cerr << *this;
}
} // namespace lir
} // namespace jit
| 25.186047 | 77 | 0.723915 | diogommartins |
6c4c5fa7415941a928fcb9b0e39cb13be32e80df | 914 | cpp | C++ | boost/libs/preprocessor/test/debug.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | boost/libs/preprocessor/test/debug.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | boost/libs/preprocessor/test/debug.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | # /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# include <boost/preprocessor/debug.hpp>
# include <libs/preprocessor/test/test.h>
BEGIN sizeof(BOOST_PP_ASSERT_MSG(0, "text") "") / sizeof(char) != 1 END
BEGIN sizeof(BOOST_PP_ASSERT_MSG(1, "text") "") / sizeof(char) == 1 END
BOOST_PP_ASSERT(10)
# line BOOST_PP_LINE(100, __FILE__)
BEGIN __LINE__ == 100 END
| 41.545455 | 80 | 0.448578 | randolphwong |
6c54d6f2a98c3073bbe807c2ecf0950ab6be0785 | 3,298 | cpp | C++ | 2048.cpp | eric0410771/Game_Theory_CPP | d739035ef64b4831491ca47126baf6f2216ad498 | [
"MIT"
] | null | null | null | 2048.cpp | eric0410771/Game_Theory_CPP | d739035ef64b4831491ca47126baf6f2216ad498 | [
"MIT"
] | null | null | null | 2048.cpp | eric0410771/Game_Theory_CPP | d739035ef64b4831491ca47126baf6f2216ad498 | [
"MIT"
] | null | null | null | /**
* Basic Environment for Game 2048
* use 'g++ -std=c++11 -O3 -g -o 2048 2048.cpp' to compile the source
*
* Computer Games and Intelligence (CGI) Lab, NCTU, Taiwan
* http://www.aigames.nctu.edu.tw
*/
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include "board.h"
#include "action.h"
#include "agent.h"
#include "episode.h"
#include "statistic.h"
#include <stdio.h>
#include<vector>
int main(int argc, const char* argv[]) {
std::cout << "Thress-Demo: ";
std::copy(argv, argv + argc, std::ostream_iterator<const char*>(std::cout, " "));
std::cout << std::endl << std::endl;
size_t total = 5000, block = 0, limit = 0;
std::string play_args, evil_args;
std::string load, save;
bool summary = false;
for (int i = 1; i < argc; i++) {
std::string para(argv[i]);
if (para.find("--total=") == 0) {
total = std::stoull(para.substr(para.find("=") + 1));
} else if (para.find("--block=") == 0) {
block = std::stoull(para.substr(para.find("=") + 1));
} else if (para.find("--limit=") == 0) {
limit = std::stoull(para.substr(para.find("=") + 1));
} else if (para.find("--play=") == 0) {
play_args = para.substr(para.find("=") + 1);
} else if (para.find("--evil=") == 0) {
evil_args = para.substr(para.find("=") + 1);
} else if (para.find("--load=") == 0) {
load = para.substr(para.find("=") + 1);
} else if (para.find("--save=") == 0) {
save = para.substr(para.find("=") + 1);
} else if (para.find("--summary") == 0) {
summary = true;
}
}
statistic stat(total, block, limit);
if (load.size()) {
std::ifstream in(load, std::ios::in);
in >> stat;
in.close();
summary |= stat.is_finished();
}
weight_agent play(play_args);
rndenv evil(evil_args);
action move;
int last_slide;
action_op player_move;
action_reward action_result;
while (!stat.is_finished()) {
play.open_episode("~:" + evil.name());
evil.open_episode(play.name() + ":~");
std::vector<std::vector<int>> state_index;
std::vector<std::vector<int>> after_state_index;
std::vector<int> rewards;
stat.open_episode(play.name() + ":" + evil.name());
episode& game = stat.back();
last_slide = -1;
std::vector<int> state;
while (true) {
agent& who = game.take_turns(play, evil);
if(who.role().compare("player") == 0){
player_move = who.take_action2(game.state());
last_slide = player_move.op;
move = player_move.s;
}
else{
move = who.take_action(game.state(),last_slide);
}
action_result = game.apply_action(move);
if (who.role().compare("player") == 0){
if(state.size() == 0){
state = game.state().features();
}else{
state_index.push_back(state);
after_state_index.push_back(game.state().features());
rewards.push_back(action_result.reward);
state = game.state().features();
}
}
if (not action_result.legal_action or who.check_for_win(game.state())) break;
}
agent& win = game.last_turns(play, evil);
stat.close_episode(win.name());
play.update_weights(state_index, rewards, after_state_index);
play.close_episode(win.name());
evil.close_episode(win.name());
}
if (summary) {
stat.summary();
}
if (save.size()) {
std::ofstream out(save, std::ios::out | std::ios::trunc);
out << stat;
out.close();
}
return 0;
}
| 27.949153 | 82 | 0.620376 | eric0410771 |
6c5873921021e015f5bb0ad11e98ddf67bccafdc | 1,255 | hh | C++ | src/hidden_layer.hh | WaizungTaam/neural_network | f593f81ffa5ef9ee3377d56cbfd6c679f668da26 | [
"Apache-2.0"
] | null | null | null | src/hidden_layer.hh | WaizungTaam/neural_network | f593f81ffa5ef9ee3377d56cbfd6c679f668da26 | [
"Apache-2.0"
] | null | null | null | src/hidden_layer.hh | WaizungTaam/neural_network | f593f81ffa5ef9ee3377d56cbfd6c679f668da26 | [
"Apache-2.0"
] | null | null | null | #ifndef HIDDEN_LAYER_HH
#define HIDDEN_LAYER_HH
#include <vector>
#include <string>
#include "matrix.hh"
#include "utils.hh"
#include "layer.hh"
class HiddenLayer : public Layer {
public:
HiddenLayer() = default;
HiddenLayer(const HiddenLayer &) = default;
HiddenLayer(HiddenLayer &&) = default;
HiddenLayer & operator=(const HiddenLayer &) = default;
HiddenLayer & operator=(HiddenLayer &&) = default;
~HiddenLayer() = default;
HiddenLayer(int, int, std::string func="logistic");
HiddenLayer(const Matrix &, std::string func="logistic");
HiddenLayer(const Matrix &, const Matrix &, std::string func="logistic");
Matrix output();
Matrix output(const Matrix &);
Matrix forward();
Matrix forward(int);
Matrix forward(int, int);
Matrix forward(const Matrix &, std::string func="logistic");
Matrix backward();
Matrix backward(int);
Matrix backward(int, int);
Matrix backward(const Matrix &);
void update(double);
void update(double, double);
std::vector<std::size_t> shape() const;
private:
Matrix weight;
Matrix w_bias;
Matrix delta_weight;
Matrix delta_w_bias;
// Matrix x_forward;
Matrix local_field;
Matrix local_gradient;
std::string activ_func_name;
};
#endif // hidden_layer.hh | 27.888889 | 75 | 0.708367 | WaizungTaam |
6c598852f77a18abe809573eecdd8da4ae6f3507 | 310 | cpp | C++ | libs/test/doc/src/examples/example26.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/test/doc/src/examples/example26.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/test/doc/src/examples/example26.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | #include <boost/test/prg_exec_monitor.hpp> // this header is optional
//____________________________________________________________________________//
int cpp_main( int, char* [] ) // note the name
{
return 5;
}
//____________________________________________________________________________//
| 28.181818 | 81 | 0.783871 | zyiacas |
6c5c7e3ee59db26f09b2a1e518ce451f09854e1b | 23,913 | cpp | C++ | directfire_github/trunk/gameui/battle.net/headsettingdialog.cpp | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | 1 | 2015-08-12T04:05:33.000Z | 2015-08-12T04:05:33.000Z | directfire_github/trunk/gameui/battle.net/headsettingdialog.cpp | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | null | null | null | directfire_github/trunk/gameui/battle.net/headsettingdialog.cpp | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | null | null | null | #include "headsettingdialog.h"
#include "gamecore/resource/resourcemgr.h"
#include "gamecore/sounds/soundmgr.h"
#include "utils/sysutils.h"
#include "utils/fileutils.h"
#include "ccimagecliper.h"
HeadSettingDialog::HeadSettingDialog(CCNode *parent,const ccColor4B &color)
: BasShowDialog(parent,color)
{
m_serverInf = ServerInterface::getInstance();
m_accountInf = m_serverInf->getLoginAccountInfo();
m_headSprite = CCSprite::create();
m_headPortrait = "portraitdefault";
m_resetImg = "buttonbg";
m_resetButton = 0;
m_loadingDialog = 0;
m_submitPortraitListener = 0;
m_submitPortraitFunc = 0;
PhotoHelper::getInstance()->registerListener(this);
m_serverInf->setHeadSettingCB(this,callfuncND_selector(HeadSettingDialog::onSubmitSuc),callfuncND_selector(HeadSettingDialog::onSubmitFailed));
m_editAble = false;
}
HeadSettingDialog::~HeadSettingDialog()
{
PhotoHelper::getInstance()->unRegisterListener(this);
}
void HeadSettingDialog::takePhotoFinished(const char* imageData, int len, const char* imageDataHq, int lenHq)
{
m_headPortrait.assign(imageDataHq, lenHq);
portraitUpdated(m_headPortrait);
if(m_submitPortraitListener && m_submitPortraitFunc) {
(m_submitPortraitListener->*m_submitPortraitFunc)(this,&m_headPortrait);
}
}
void HeadSettingDialog::takePhotoFinished(const char* imageFile)
{
if(imageFile == 0)
return;
CCNode *root = this->getParent();
while(root->getParent())
root = root->getParent();
CCImageCliper *cliper = new CCImageCliper(imageFile,this,root,ccc4(0,0,0,128));
cliper->setTouchPriority(this->touchPriority() - uilib::SafePriorityGap);
cliper->exec();
}
void HeadSettingDialog::takePhotoFailed()
{
}
void HeadSettingDialog::takePhotoCanceled()
{
}
void HeadSettingDialog::setHeadSprite(CCSprite *headSprite)
{
m_headSprite->initWithTexture(headSprite->getTexture());
}
void HeadSettingDialog::setEditAble(bool editAble)
{
m_editAble = editAble;
}
void HeadSettingDialog::setSubmitPortraitCB(CCNode *listener,SEL_CallFuncND func)
{
m_submitPortraitListener = listener;
m_submitPortraitFunc = func;
}
void HeadSettingDialog::portraitUpdated(const std::string& imgData)
{
float width = 220;
float height = 220;
CCImage *img = new CCImage;
img->initWithImageData((void*)imgData.data(),imgData.size(),
CCImage::kFmtUnKnown);
CCTexture2D *texture = new CCTexture2D;
texture->initWithImage(img);
m_headSprite->initWithTexture(texture);
CCSize csize = m_headSprite->getContentSize();
m_headSprite->setScaleX(width / csize.width);
m_headSprite->setScaleY(height / csize.height);
delete img;
CCFadeIn *fade = CCFadeIn::create(0.5);
m_headSprite->runAction(fade);
}
void HeadSettingDialog::exec()
{
finish();
BasShowDialog::exec();
}
void HeadSettingDialog::finish()
{
// dialog
CCSize size = CCDirector::sharedDirector()->getWinSize();
setHeight(size.height * 0.9);
LangDef *lang = ResourceMgr::getInstance()->getLangDef();
// base area
m_baseArea = new BasWidget;
this->addChild(m_baseArea);
m_baseArea->setFill("parent");
BasWidget *portraitArea = new BasWidget;
m_baseArea->addChild(portraitArea);
portraitArea->setHeight(getHeight() / 4.0);
portraitArea->setWidth(getWidth() - (m_edgeSize * 2));
BasWidget *accountArea = new BasWidget;
m_baseArea->addChild(accountArea);
accountArea->setHeight(getHeight() / 2.0);
accountArea->setWidth(getWidth() - (m_edgeSize * 2));
BasWidget *accountAreaLeft = new BasWidget;
BasWidget *accountAreaRight = new BasWidget;
accountAreaLeft->setTop("parent", uilib::Top);
accountAreaLeft->setBottom("parent", uilib::Bottom);
accountAreaLeft->setLeft("parent", uilib::Left);
accountAreaLeft->setMaxWidthRefSize("parent", 0.3);
accountAreaLeft->setMinWidthRefSize("parent", 0.3);
accountAreaRight->setTop("parent", uilib::Top);
accountAreaRight->setBottom("parent", uilib::Bottom);
accountAreaRight->setLeft(accountAreaLeft->getName(), uilib::Right);
accountAreaRight->setLeftMargin(m_edgeSize);
accountAreaRight->setRight("parent", uilib::Right);
accountAreaRight->setRightMargin(m_edgeSize * 2);
accountArea->addChild(accountAreaLeft);
accountArea->addChild(accountAreaRight);
BasWidget *bottomArea = new BasWidget;
m_baseArea->addChild(bottomArea);
bottomArea->setHeight(getHeight() / 6.0);
bottomArea->setWidth(getWidth() - (m_edgeSize * 2));
// portrait area
portraitArea->setTop("parent",uilib::Top);
portraitArea->setTopMargin(m_edgeSize * 10.0);
portraitArea->setHorizontal("parent",0.5);
BasWidget *portraitLeftArea = new BasWidget;
BasWidget *portraitRightArea = new BasWidget;
portraitLeftArea->setLeft("parent", uilib::Left);
portraitLeftArea->setTop("parent", uilib::Top);
portraitLeftArea->setBottom("parent", uilib::Bottom);
portraitLeftArea->setMaxWidthRefSize("parent", 0.6);
portraitLeftArea->setMinWidthRefSize("parent", 0.6);
portraitRightArea->setLeft(portraitLeftArea->getName(), uilib::Right);
portraitRightArea->setLeftMargin(m_edgeSize);
portraitRightArea->setTop("parent", uilib::Top);
portraitRightArea->setBottom("parent", uilib::Bottom);
portraitRightArea->setRight("parent", uilib::Right);
portraitArea->addChild(portraitLeftArea);
portraitArea->addChild(portraitRightArea);
// portrait sub area
m_headDelegate = new BasNodeDelegateWidget(m_headSprite);
portraitLeftArea->addChild(m_headDelegate);
m_headDelegate->setVertical("parent",0.5);
m_headDelegate->setHorizontal("parent",0.5);
// upload button layout
BasButton* uploadButton = new BasButton;
uploadButton->setWidth(150.0f);
// logout button layout
BasButton* logoutButton = new BasButton;
logoutButton->setWidth(150.0f);
//exit button
BasButton *exitButton = new BasButton;
exitButton->setWidth(150.0f);
VerticalLayout *vlayPortrait = new VerticalLayout;
vlayPortrait->addWidget(exitButton);
vlayPortrait->addWidget(logoutButton);
vlayPortrait->addWidget(uploadButton);
vlayPortrait->setAveraged(true);
vlayPortrait->setChildAlign(0,uilib::Left);
vlayPortrait->setChildAlign(1,uilib::Left);
vlayPortrait->setChildAlign(2,uilib::Left);
portraitRightArea->setLayout(vlayPortrait);
// portrait
UiThemeDef *uiDef = UiThemeMgrProxy::getInstance()->getThemeByName(m_theme);
if(!m_headSprite->getTexture()) {
std::string headimg;
uiDef->getNormalData()->getImg(m_headPortrait,headimg);
m_headSprite->initWithSpriteFrameName(headimg.data());
}
// upload button
uploadButton->setButtonInfo(lang->getStringById(StringEnum::Upload),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE);
uploadButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onUploadClicked));
// logout button
logoutButton->setButtonInfo(lang->getStringById(StringEnum::Logout),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE);
logoutButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onLogOutClicked));
//exit button
exitButton->setButtonInfo(lang->getStringById(StringEnum::QuitGame),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE);
exitButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onExitGameClicked));
// account info area
accountArea->setBottom(bottomArea->getName(),uilib::Top);
accountArea->setBottomMargin(m_edgeSize * 2.0);
accountArea->setHorizontal("parent",0.5);
// id
BasLabel *idLbl = new BasLabel;
idLbl->setLabelInfo(lang->getStringById(StringEnum::ID),"","",CCSizeMake(0,0),getSystemFont(),24);
BasLabel *idLbl2 = new BasLabel;
idLbl2->setLabelInfo(m_accountInf->m_id,"","",CCSizeMake(0,0),getSystemFont(),24);
// account
BasLabel *accountLbl = new BasLabel;
accountLbl->setLabelInfo(lang->getStringById(StringEnum::Mail),"","",CCSizeMake(0,0),getSystemFont(),24);
m_accountInput = new InputBox;
m_accountInput->setMaxLength(24);
m_accountInput->setTheme("default","inputbg");
m_accountInput->setText(m_accountInf->m_mail);
m_accountInput->setHeight(60);
// password
BasLabel *pwdLbl = new BasLabel;
pwdLbl->setLabelInfo(lang->getStringById(StringEnum::Password),"","",CCSizeMake(0,0),getSystemFont(),24);
m_pwdInput = new InputBox;
m_pwdInput->setMaxLength(24);
m_pwdInput->setTheme("default","inputbg");
m_pwdInput->setText(m_accountInf->m_password);
m_pwdInput->setInputFlag(kEditBoxInputFlagPassword);
m_pwdInput->setHeight(60);
// password confirm
BasLabel *pwdConfirmLbl = new BasLabel;
pwdConfirmLbl->setLabelInfo(lang->getStringById(StringEnum::PasswordConfirm),"","",CCSizeMake(0,0),getSystemFont(),24);
m_pwdConfirmInput = new InputBox;
m_pwdConfirmInput->setMaxLength(24);
m_pwdConfirmInput->setTheme("default","inputbg");
m_pwdConfirmInput->setText(m_accountInf->m_password);
m_pwdConfirmInput->setInputFlag(kEditBoxInputFlagPassword);
m_pwdConfirmInput->setHeight(60);
// nick name
BasLabel *nickNameLbl = new BasLabel;
nickNameLbl->setLabelInfo(lang->getStringById(StringEnum::NickName),"","",CCSizeMake(0,0),getSystemFont(),24);
m_nickNameInput = new InputBox;
m_nickNameInput->setMaxLength(14);
m_nickNameInput->setTheme("default","inputbg");
m_nickNameInput->setText(m_accountInf->m_name);
m_nickNameInput->setHeight(60);
if(m_accountInf->m_name.empty()){
//show the nick name no exist warnning
BasLabel *nickNameSet = new BasLabel;
nickNameSet->setLabelInfo(lang->getStringById(StringEnum::SetYourNickName),"","",CCSizeMake(0,0),getSystemFont(),24,ccWHITE);
this->addChild(nickNameSet);
nickNameSet->setHorizontal("parent",0.5);
nickNameSet->setTop("parent",uilib::Top);
nickNameSet->setTopMargin(10);
}
// sex
BasLabel *sexLbl = new BasLabel;
sexLbl->setLabelInfo(lang->getStringById(StringEnum::Sex),"","",CCSizeMake(0,0),getSystemFont(),24);
BasWidget *sexRadioArea = new BasWidget;
sexRadioArea->setWidth(accountAreaRight->getWidth());
// female radio button
m_femaleButton = new CheckBox;
m_maleButton = new CheckBox;
sexRadioArea->addChild(m_maleButton);
sexRadioArea->addChild(m_femaleButton);
m_maleButton->setTop("parent", uilib::Top);
m_maleButton->setBottom("parent", uilib::Bottom);
m_maleButton->setLeft("parent", uilib::Left);
m_maleButton->setMaxWidthRefSize("parent", 0.5);
m_maleButton->setMinWidthRefSize("parent", 0.5);
m_maleButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onMaleClicked));
m_maleButton->setCheckInfo(lang->getStringById(StringEnum::Male).data(),"fonts/uifont24.fnt","default","",CCSizeMake(60,60));
m_femaleButton->setTop("parent", uilib::Top);
m_femaleButton->setBottom("parent", uilib::Bottom);
m_femaleButton->setLeft(m_maleButton->getName(), uilib::Right);
m_femaleButton->setLeftMargin(m_edgeSize);
m_femaleButton->setRight("parent", uilib::Right);
m_femaleButton->setRightMargin(m_edgeSize * 2);
m_femaleButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onFemaleClicked));
m_femaleButton->setCheckInfo(lang->getStringById(StringEnum::Female).data(),"fonts/uifont24.fnt","default","",CCSizeMake(60,60));
if (m_accountInf->m_sex == 0) {
m_femaleButton->setCheck(true);
m_maleButton->setCheck(false);
} else {
m_femaleButton->setCheck(false);
m_maleButton->setCheck(true);
}
// account area layout
VerticalLayout *vlayAccountLeft = new VerticalLayout;
vlayAccountLeft->addWidget(idLbl);
vlayAccountLeft->addWidget(accountLbl);
vlayAccountLeft->addWidget(pwdLbl);
vlayAccountLeft->addWidget(pwdConfirmLbl);
vlayAccountLeft->addWidget(nickNameLbl);
vlayAccountLeft->addWidget(sexLbl);
vlayAccountLeft->setAveraged(true);
vlayAccountLeft->setChildAlign(0,uilib::Left);
vlayAccountLeft->setChildAlign(1,uilib::Left);
vlayAccountLeft->setChildAlign(2,uilib::Left);
vlayAccountLeft->setChildAlign(3,uilib::Left);
vlayAccountLeft->setChildAlign(4,uilib::Left);
vlayAccountLeft->setChildAlign(5,uilib::Left);
vlayAccountLeft->setLeftMargin(40);
accountAreaLeft->setLayout(vlayAccountLeft);
VerticalLayout *vlayAccountRight = new VerticalLayout;
vlayAccountRight->addWidget(idLbl2);
vlayAccountRight->addWidget(m_accountInput);
vlayAccountRight->addWidget(m_pwdInput);
vlayAccountRight->addWidget(m_pwdConfirmInput);
vlayAccountRight->addWidget(m_nickNameInput);
vlayAccountRight->addWidget(sexRadioArea);
vlayAccountRight->setAveraged(true);
vlayAccountRight->setChildAlign(0,uilib::Left);
vlayAccountRight->setChildAlign(1,uilib::Left);
vlayAccountRight->setChildAlign(2,uilib::Left);
vlayAccountRight->setChildAlign(3,uilib::Left);
vlayAccountRight->setChildAlign(4,uilib::Left);
vlayAccountRight->setChildAlign(5,uilib::Left);
vlayAccountRight->setChildAlign(1,uilib::Right);
vlayAccountRight->setChildAlign(2,uilib::Right);
vlayAccountRight->setChildAlign(3,uilib::Right);
vlayAccountRight->setChildAlign(4,uilib::Right);
vlayAccountRight->setChildAlign(5,uilib::Right);
accountAreaRight->setLayout(vlayAccountRight);
// button area
bottomArea->setBottom("parent",uilib::Bottom);
bottomArea->setBottomMargin(m_edgeSize * 2.0);
bottomArea->setHorizontal("parent",0.5);
// reset button
m_resetButton = new BasButton;
m_resetButton->setButtonInfo(lang->getStringById(StringEnum::Reset),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE);
bottomArea->addChild(m_resetButton);
m_resetButton->setVertical("parent",0.5);
m_resetButton->setHorizontal("parent",0.5);
m_resetButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onResetClicked));
// submit button
m_submitButton = new BasButton;
m_submitButton->setButtonInfo(lang->getStringById(StringEnum::Submit),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE);
bottomArea->addChild(m_submitButton);
m_submitButton->setVertical("parent",0.5);
m_submitButton->setHorizontal("parent",0.5);
m_submitButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onSubmitClicked));
editEnabled(m_editAble);
}
void HeadSettingDialog::setResetImg(const std::string &normal,const std::string &pressed)
{
m_resetImg = normal;
m_resetPressedImg = pressed;
}
void HeadSettingDialog::onUploadClicked(CCNode *sender,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY){
std::string text;
text.append("Upload portrait no supported in bb10 now!");
new SplashMessageWidget(this,text);
return;
}else if(CC_TARGET_PLATFORM == CC_PLATFORM_LINUX){
takePhotoFinished("/home/water/work/cocos2d-2.1beta3-x-2.1.0/directfire/trunk/Resources/ss0.jpg");
return;
}
LangDef *lang = ResourceMgr::getInstance()->getLangDef();
PhotoHelper::getInstance()->setLangCancel(lang->getStringById(StringEnum::Cancel));
PhotoHelper::getInstance()->setLangChooseImage(lang->getStringById(StringEnum::ChooseImage));
PhotoHelper::getInstance()->setLangTakePhoto(lang->getStringById(StringEnum::TakePhoto));
PhotoHelper::getInstance()->takePhoto();
}
void HeadSettingDialog::onLogOutClicked(CCNode *sender,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
m_serverInf->disconnectGameServer();
}
void HeadSettingDialog::onExitGameClicked(CCNode *sender,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
m_serverInf->disconnectGameServer();
ResourceMgr::getInstance()->getUserDataMgr()->getInstance()->flush();
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
void HeadSettingDialog::onResetClicked(CCNode *sender,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
editEnabled(true);
}
void HeadSettingDialog::editEnabled(bool enable)
{
if (enable) {
m_resetButton->setVisible(false);
m_submitButton->setVisible(true);
showEditAbleInputBox();
m_femaleButton->setEnabled(true);
m_maleButton->setEnabled(true);
} else {
m_resetButton->setVisible(true);
m_submitButton->setVisible(false);
showDisableInputBox();
m_femaleButton->setEnabled(false);
m_maleButton->setEnabled(false);
}
}
void HeadSettingDialog::onSubmitClicked(CCNode *sender,void *data)
{
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
if(!sendFormData())
return;
}
bool HeadSettingDialog::sendFormData()
{
m_resetButton->setVisible(true);
m_submitButton->setVisible(false);
// hidden the inputbox prevent on top of loading dialog
hiddenInputBox();
m_femaleButton->setEnabled(false);
m_maleButton->setEnabled(false);
LangDef *lang = ResourceMgr::getInstance()->getLangDef();
string mail = m_accountInput->getText();
string password = m_pwdInput->getText();
string passwordConfirm = m_pwdConfirmInput->getText();
string nickName = m_nickNameInput->getText();
short sex = 0;
if(m_femaleButton->isCheck())
sex = 0;
else
sex = 1;
// nothing changed
if ((mail.compare(m_accountInf->m_mail) == 0 && !mail.empty())
&& (password.compare(m_accountInf->m_password) == 0 && !password.empty())
&& (passwordConfirm.compare(m_accountInf->m_password) == 0 && !passwordConfirm.empty())
&& (nickName.compare(m_accountInf->m_name) == 0 && !nickName.empty())
&& (sex == m_accountInf->m_sex)) {
showDisableInputBox();
return true;
}
// verify account
if (mail.empty()) {
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::AccountEmptyError));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
return false;
}
if (!isMailAddress(mail)) {
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::AccountNotMailError));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
return false;
}
// verify password
if (password.empty() || passwordConfirm.empty()) {
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::PasswordEmptyError));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
return false;
}
if (password.size() < 4) {
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::PasswordLenError));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
return false;
}
if (password.compare(passwordConfirm) != 0) {
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::PasswordConfirmError));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
return false;
}
if (nickName.empty()) {
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::NickNameEmptyError));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
return false;
}
if (hasSpecialChar(mail) || hasSpecialChar(password) || hasSpecialChar(nickName)) {
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::SpecialCharactersError));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
return false;
}
if(m_loadingDialog == 0){
m_loadingDialog = new BusyDialog();
m_loadingDialog->setTouchPriority(this->touchPriority() - uilib::SafePriorityGap);
CCNode *root = this->getParent();
while (root->getParent()) {
root = root->getParent();
}
root->addChild(m_loadingDialog, 11000);
m_loadingDialog->setBusyText(lang->getStringById(StringEnum::Loading));
m_loadingDialog->setAnimationName("uiloadinga");
}
m_loadingDialog->setLoadFinishedCB(this,callfuncN_selector(HeadSettingDialog::onSubmitStart));
m_loadingDialog->exec();
return true;
}
void HeadSettingDialog::onSubmitStart()
{
string mail = m_accountInput->getText();
string password = m_pwdInput->getText();
string passwordConfirm = m_pwdConfirmInput->getText();
string nickName = m_nickNameInput->getText();
short sex = 0;
if(m_femaleButton->isCheck())
sex = 0;
else
sex = 1;
// send change
m_serverInf->resetUserInfo(mail, password, nickName, sex);
}
void HeadSettingDialog::onSubmitSuc(CCNode *sender,void *data)
{
if(m_loadingDialog != 0){
m_loadingDialog->destory();
m_loadingDialog = 0;
}
showDisableInputBox();
}
void HeadSettingDialog::onSubmitFailed(CCNode *sender,void *data)
{
int no = *(int*)data;
if(m_loadingDialog != 0){
m_loadingDialog->destory();
m_loadingDialog = 0;
}
LangDef *lang = ResourceMgr::getInstance()->getNetLangDef();
SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(no));
splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished));
}
void HeadSettingDialog::onFailedSplashFinished(CCNode *sender)
{
m_resetButton->setVisible(false);
m_submitButton->setVisible(true);
showEditAbleInputBox();
m_femaleButton->setEnabled((true));
m_maleButton->setEnabled((true));
}
void HeadSettingDialog::onFemaleClicked(CCNode *sender,void *data)
{
if(!m_femaleButton->isEnabled())
return;
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
m_femaleButton->setCheck(true);
m_maleButton->setCheck(false);
}
void HeadSettingDialog::onMaleClicked(CCNode *sender,void *data)
{
if(!m_maleButton->isEnabled())
return;
SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL);
m_femaleButton->setCheck(false);
m_maleButton->setCheck(true);
}
void HeadSettingDialog::hiddenInputBox()
{
m_accountInput->setVisible(false);
m_pwdInput->setVisible(false);
m_pwdConfirmInput->setVisible(false);
m_nickNameInput->setVisible(false);
}
void HeadSettingDialog::showEditAbleInputBox()
{
// show inputbox and enable edit
m_accountInput->setVisible(true);
m_pwdInput->setVisible(true);
m_pwdConfirmInput->setVisible(true);
m_nickNameInput->setVisible(true);
if (m_accountInf->m_mail.empty()) {
m_accountInput->setEnabled(true);
} else {
m_accountInput->setEnabled(false);
}
m_pwdInput->setEnabled(true);
m_pwdConfirmInput->setEnabled(true);
m_nickNameInput->setEnabled(true);
}
void HeadSettingDialog::showDisableInputBox()
{
// show inputbox and disable edit
m_accountInput->setVisible(true);
m_pwdInput->setVisible(true);
m_pwdConfirmInput->setVisible(true);
m_nickNameInput->setVisible(true);
m_accountInput->setEnabled(false);
m_pwdInput->setEnabled(false);
m_pwdConfirmInput->setEnabled(false);
m_nickNameInput->setEnabled(false);
}
| 41.371972 | 155 | 0.720027 | zhwsh00 |