hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c74278df6f0e3a7bcc7c673ba0fa1ac763f0efdd | 3,780 | cpp | C++ | KClient/release/moc_mainwindow.cpp | adricatena/TD3-Ethernet | f2113676614ae71e10b5073d1623a9c7941ba111 | [
"MIT"
] | null | null | null | KClient/release/moc_mainwindow.cpp | adricatena/TD3-Ethernet | f2113676614ae71e10b5073d1623a9c7941ba111 | [
"MIT"
] | null | null | null | KClient/release/moc_mainwindow.cpp | adricatena/TD3-Ethernet | f2113676614ae71e10b5073d1623a9c7941ba111 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created: Thu 29. Sep 11:25:29 2016
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../mainwindow.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_MainWindow[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
8, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
12, 11, 11, 11, 0x08,
36, 11, 11, 11, 0x08,
63, 11, 11, 11, 0x08,
84, 80, 11, 11, 0x08,
126, 11, 11, 11, 0x08,
140, 11, 11, 11, 0x08,
163, 11, 11, 11, 0x08,
189, 11, 11, 11, 0x08,
0 // eod
};
static const char qt_meta_stringdata_MainWindow[] = {
"MainWindow\0\0on_sendButton_clicked()\0"
"on_connectButton_clicked()\0connectionInit()\0"
"err\0handleError(QAbstractSocket::SocketError)\0"
"dataArrived()\0on_btnEnviar_clicked()\0"
"on_btn_grfc_Sen_clicked()\0"
"on_btn_grfc_Luz_clicked()\0"
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
MainWindow *_t = static_cast<MainWindow *>(_o);
switch (_id) {
case 0: _t->on_sendButton_clicked(); break;
case 1: _t->on_connectButton_clicked(); break;
case 2: _t->connectionInit(); break;
case 3: _t->handleError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
case 4: _t->dataArrived(); break;
case 5: _t->on_btnEnviar_clicked(); break;
case 6: _t->on_btn_grfc_Sen_clicked(); break;
case 7: _t->on_btn_grfc_Luz_clicked(); break;
default: ;
}
}
}
const QMetaObjectExtraData MainWindow::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow,
qt_meta_data_MainWindow, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &MainWindow::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 8)
qt_static_metacall(this, _c, _id, _a);
_id -= 8;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 33.451327 | 102 | 0.593915 | [
"object"
] |
c743ac88ef7ee199bb0187f5a05898d16ce476f8 | 851 | hpp | C++ | src/RendererSectionData.hpp | uis246/AltCraft | 2659824ef8d48b3dd371d74a7792792002b367a5 | [
"Apache-2.0"
] | 4 | 2021-06-22T19:44:24.000Z | 2022-01-19T07:01:37.000Z | src/RendererSectionData.hpp | uis246/AltCraft | 2659824ef8d48b3dd371d74a7792792002b367a5 | [
"Apache-2.0"
] | 4 | 2020-08-08T23:22:59.000Z | 2021-07-06T17:23:39.000Z | src/RendererSectionData.hpp | uis246/AltCraft | 2659824ef8d48b3dd371d74a7792792002b367a5 | [
"Apache-2.0"
] | 1 | 2021-09-22T07:31:25.000Z | 2021-09-22T07:31:25.000Z | #pragma once
#include <vector>
#include <glm/mat4x4.hpp>
#include "Vector.hpp"
#include "Section.hpp"
#include "AssetManager.hpp"
class World;
struct BlockLightness {
unsigned char face[FaceDirection::none] = { 0,0,0,0,0,0 };
};
struct SectionsData {
Section *section = nullptr;
Section *west = nullptr;
Section *east = nullptr;
Section *top = nullptr;
Section *bottom = nullptr;
Section *north = nullptr;
Section *south = nullptr;
BlockId GetBlockId(const Vector &pos, bool locked = false) const;
BlockLightness GetLight(const Vector &pos) const;
BlockLightness GetSkyLight(const Vector &pos) const;
};
struct RendererSectionData {
std::vector<glm::vec3> verts;
std::vector<uint32_t> quadInfo;
size_t hash = ~0;
Vector sectionPos;
bool forced = false;
};
RendererSectionData ParseSection(const SectionsData §ions);
| 20.261905 | 66 | 0.72973 | [
"vector"
] |
c7470ded46a7581ba7c53d926fe8e93566c6e0d3 | 3,806 | cpp | C++ | roundssqlmodel.cpp | jonkjenn/ChessTour | 0df7366250de02811708a6d24dab9209f703097c | [
"CC-BY-3.0"
] | null | null | null | roundssqlmodel.cpp | jonkjenn/ChessTour | 0df7366250de02811708a6d24dab9209f703097c | [
"CC-BY-3.0"
] | null | null | null | roundssqlmodel.cpp | jonkjenn/ChessTour | 0df7366250de02811708a6d24dab9209f703097c | [
"CC-BY-3.0"
] | null | null | null | #include "roundssqlmodel.h"
#include <QtSql/QSqlRecord>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <QDebug>
RoundsSqlModel::RoundsSqlModel(QObject *parent, QSqlDatabase database):
QSqlTableModel(parent), database(database)
{
}
QVariant RoundsSqlModel::data(int row, QString columnName)const
{
return data(index(row,0),fieldIndex(columnName) + Qt::UserRole + 1);
}
QVariant RoundsSqlModel::data(const QModelIndex &index, int role) const
{
QVariant value;
if (index.isValid()) {
if (role < Qt::UserRole) {
value = QSqlQueryModel::data(index, role);
} else {
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
}
return value;
}
QHash<int, QByteArray> RoundsSqlModel::roleNames() const
{
QHash<int, QByteArray> roles;
// record() returns an empty QSqlRecord
for (int i = 0; i < this->record().count(); i ++) {
roles.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8().toLower());
}
return roles;
}
bool RoundsSqlModel::select()
{
if(!QSqlTableModel::select()){return false;}
//Create index PrimaryKey -> row (the row number used internally in model not in database)
rowFromPrimary.clear();
for(int i=0;i<rowCount();++i){
rowFromPrimary.insert(primaryValues(i).value(0).toInt(),i);
}
emit roundDataChanged();
return true;
}
int RoundsSqlModel::getRow(int primaryKey)
{
if(primaryKey<0){return -1;}
return rowFromPrimary.value(primaryKey);
}
int RoundsSqlModel::getPk(int row)
{
return primaryValues(row).value(0).toInt();
}
void RoundsSqlModel::setCurrentIndex(int row)
{
saveCurrentShownRound(getPk(row));
m_currentRoundIndex = row;
InternalMessages::RoundChangedData d(getPk(row),data(row,"GamesPerMatch").toInt());
emit roundChanged(d);
}
int RoundsSqlModel::currentRoundIndex()
{
return m_currentRoundIndex;
}
void RoundsSqlModel::onTournamentLoaded(InternalMessages::TournamentChangedData d)
{
setFilter("TournamentId = " + QString::number(d.pk));
setSort(0,Qt::SortOrder::AscendingOrder);
select();
m_currentRoundIndex = d.currentRoundIndex - 1;
m_currentTournamentPk = d.pk;
saveCurrentShownRound(getPk(m_currentRoundIndex));
InternalMessages::RoundChangedData rd(getPk(m_currentRoundIndex),data(m_currentRoundIndex,"GamesPerMatch").toInt());
emit roundChanged(rd,d);
}
/*int RoundsSqlModel::currentShownRound()
{
QModelIndex i = index(0,fieldIndex("TournamentId"));
int tournamentId = data(i,Qt::DisplayRole).toInt();
QSqlQuery sql(database);
sql.prepare("SELECT CurrentShownRound FROM Tournament WHERE Id = :tournamentId");
sql.bindValue(":tournamentId",tournamentId);
sql.exec();
if(!sql.next()){qDebug() << "Could nto retrieve current round";}
int currRound = getRow(sql.value(0).toInt());
if(currRound<0){
currRound = 0;
}
return currRound;
}*/
void RoundsSqlModel::saveCurrentShownRound(int roundPk)
{
/*QModelIndex i = index(currentShownRound,fieldIndex("TournamentId"));
int tournamentId = data(i,Qt::DisplayRole).toInt();*/
//int roundPk = getPk(currentShownRound);
QSqlQuery sql(database);
sql.prepare("UPDATE Tournament SET CurrentShownRound = :currentShownRound WHERE Id = :tournamentId");
sql.bindValue(":currentShownRound",roundPk);
sql.bindValue(":tournamentId",m_currentTournamentPk);
sql.exec();
if(sql.lastError().isValid()){ qDebug() << sql.lastError();}
//qDebug() << sql.lastQuery();
}
int RoundsSqlModel::currentTournamentPk() const
{
return m_currentTournamentPk;
}
| 28.192593 | 120 | 0.682606 | [
"model"
] |
c750ebb9058b2f78325971f45eafb520eb769903 | 2,666 | cpp | C++ | src/common/protocol/types/ArrayOf.cpp | smartdu/kafkaclient-cpp | 03d108808a50a13d7a26e63461a1ac27c5bc141c | [
"Apache-2.0"
] | 5 | 2019-04-29T11:09:55.000Z | 2019-11-28T02:53:59.000Z | src/common/protocol/types/ArrayOf.cpp | smartdu/kafkaclient-cpp | 03d108808a50a13d7a26e63461a1ac27c5bc141c | [
"Apache-2.0"
] | 2 | 2019-05-10T09:37:49.000Z | 2019-05-14T02:40:16.000Z | src/common/protocol/types/ArrayOf.cpp | smartdu/kafkaclient-cpp | 03d108808a50a13d7a26e63461a1ac27c5bc141c | [
"Apache-2.0"
] | 1 | 2019-05-10T10:07:50.000Z | 2019-05-10T10:07:50.000Z | #include "ArrayOf.h"
#include "ByteBuffer.h"
#include "ObjectArray.h"
#include "SchemaException.h"
#include "Object.h"
#include "Type.h"
const char* ArrayOf::ARRAY_TYPE_NAME = "ARRAY";
ArrayOf::ArrayOf(Type *type)
{
this->type_ = type;
this->nullable_ = false;
}
ArrayOf::ArrayOf(Type *type, bool nullable)
{
this->type_ = type;
this->nullable_ = nullable;
}
ArrayOf::~ArrayOf()
{
Type::destroy(type_);
}
ArrayOf* ArrayOf::nullable(Type *type)
{
return new ArrayOf(type, true);
}
bool ArrayOf::isNullable()
{
return nullable_;
}
void ArrayOf::write(ByteBuffer *buffer, Object *o)
{
if (o == NULL)
{
buffer->putInt(-1);
return;
}
ObjectArray *objs = (ObjectArray*) o;
int size = *objs;
buffer->putInt(size);
for (int i = 0; i < size; i++)
{
type_->write(buffer, (*objs)[i]);
}
}
Object* ArrayOf::read(ByteBuffer *buffer)
{
int size = buffer->getInt();
if (size < 0 && isNullable())
return NULL;
else if (size < 0)
{
throw SchemaException("Array size " + std::to_string(size) + " cannot be negative");
}
if (size > buffer->remaining())
throw SchemaException("Error reading array of size " + std::to_string(size) + ", only " + std::to_string(buffer->remaining()) + " bytes available");
ObjectArray *objs = new ObjectArray(size);
for (int i = 0; i < size; i++)
(*objs)[i] = type_->read(buffer);
return objs;
}
int ArrayOf::sizeOf(Object *o)
{
int size = 4;
if (o == NULL)
return size;
ObjectArray *objs = (ObjectArray*) o;
for (int i = 0; i < *objs; i++)
size += type_->sizeOf((*objs)[i]);
return size;
}
Type* ArrayOf::type()
{
return this->type_;
}
std::string ArrayOf::toString()
{
std::string str = ARRAY_TYPE_NAME;
return str + "(" + type_->toString() + ")";
}
Object* ArrayOf::validate(Object *item)
{
if (isNullable() && item == NULL)
{
return NULL;
}
ObjectArray *array = (ObjectArray*)item;
for (int i = 0; i < *array; i++)
type_->validate((*array)[i]);
return array;
}
std::string ArrayOf::typeName()
{
return ARRAY_TYPE_NAME;
}
std::string ArrayOf::documentation()
{
std::string str = "Represents a sequence of objects of a given type T. ";
str += "Type T can be either a primitive type (e.g. ";
str += Type::STRING()->toString();
str += ") or a structure. ";
str += "First, the length N is given as an ";
str += Type::INT32()->toString();
str += ". Then N instances of type T follow. ";
str += "A null array is represented with a length of -1. "
"In protocol documentation an array of T instances is referred to as [T].";
return str;
} | 20.992126 | 151 | 0.610278 | [
"object"
] |
c75446378360d435f8f26f09e65ed989c2f4e6aa | 2,630 | hpp | C++ | src/ct_icp/evaluate_slam.hpp | xiang-1208/ct_icp | 42928e584c24595c49e147e2ea120f8cc31ec716 | [
"MIT"
] | 123 | 2021-10-08T01:51:45.000Z | 2022-03-31T08:55:15.000Z | src/ct_icp/evaluate_slam.hpp | ZuoJiaxing/ct_icp | 1c371331aad833faec157c015fb8f72143019caa | [
"MIT"
] | 9 | 2021-10-19T07:25:46.000Z | 2022-03-31T03:20:19.000Z | src/ct_icp/evaluate_slam.hpp | ZuoJiaxing/ct_icp | 1c371331aad833faec157c015fb8f72143019caa | [
"MIT"
] | 23 | 2021-10-08T01:49:01.000Z | 2022-03-24T15:35:07.000Z |
#ifndef EVALUATE_HPP_
#define EVALUATE_HPP_
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
#include <map>
#include <exception>
#include <Eigen/Dense>
#include "yaml-cpp/yaml.h"
#include "io.hpp"
#include "types.hpp"
namespace ct_icp {
struct errors {
double t_err;
double r_err;
errors(double t_err, double r_err) :
t_err(t_err), r_err(r_err) {}
};
struct seq_errors {
std::vector<errors> tab_errors;
double mean_rpe;
double mean_ape;
double max_ape;
double mean_local_err;
double max_local_err;
double average_elapsed_ms = -1.0;
int index_max_local_err;
double mean_num_attempts;
};
inline double translationError(const Eigen::Matrix4d &pose_error) {
return pose_error.block<3, 1>(0, 3).norm();
}
inline double rotationError(Eigen::Matrix4d &pose_error) {
double a = pose_error(0, 0);
double b = pose_error(1, 1);
double c = pose_error(2, 2);
double d = 0.5 * (a + b + c - 1.0);
return acos(std::max(std::min(d, 1.0), -1.0));
}
inline std::vector<double> trajectoryDistances(const ArrayPoses &poses) {
std::vector<double> dist(1, 0.0);
for (size_t i = 1; i < poses.size(); i++)
dist.push_back(dist[i - 1] + translationError(poses[i - 1] - poses[i]));
return dist;
}
inline int lastFrameFromSegmentLength(const std::vector<double> &dist, int first_frame, double len) {
for (int i = first_frame; i < dist.size(); i++)
if (dist[i] > dist[first_frame] + len)
return i;
return -1;
}
double computeMeanRPE(const ArrayPoses &poses_gt, const ArrayPoses &poses_result,
seq_errors &seq_err);
seq_errors eval(const ArrayPoses &poses_gt, const ArrayPoses &poses_estimated);
inline void eval(const std::string &filename_poses_gt, const std::string &filename_poses_result,
std::list<seq_errors> &all_seq_errors) {
ArrayPoses poses_gt = LoadPoses(filename_poses_gt);
ArrayPoses poses_result = LoadPoses(filename_poses_result);
auto seq_err = eval(poses_gt, poses_result);
// Add to errors of all sequences
all_seq_errors.push_back(seq_err);
}
// Saves Metrics to File
void SaveMetrics(const std::map<std::string, seq_errors> &metrics,
const std::string &destination, bool success = true);
}
#endif
| 27.395833 | 105 | 0.620532 | [
"vector"
] |
c763d8358809a97a2e57f457665e541b6da83290 | 1,403 | hpp | C++ | graph/strongly_connected_components_tarjan.hpp | cormoran/LibAlgorithm | 9eec05a36343c891be5fee475678a283081c68d3 | [
"MIT"
] | 1 | 2020-03-28T23:46:14.000Z | 2020-03-28T23:46:14.000Z | graph/strongly_connected_components_tarjan.hpp | cormoran/LibAlgorithm | 9eec05a36343c891be5fee475678a283081c68d3 | [
"MIT"
] | null | null | null | graph/strongly_connected_components_tarjan.hpp | cormoran/LibAlgorithm | 9eec05a36343c891be5fee475678a283081c68d3 | [
"MIT"
] | null | null | null | #pragma once
#include "common/simple_header.hpp"
using EdgeList = vector<vector<int>>;
// 非連結を含む,グラフ E を強連結成分に分解(Tarjan's algorithm)
// O(N + M) N: 頂点数, M: 辺数
// -> 強連結成分ごとのグループ
// グループはトポロジカル順序の逆順(のはず)http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_A&lang=jp
// でチェック
vector<vector<int>> strongly_connected_components_tarjan(const EdgeList &E) {
int N = E.size();
vector<int> ord(N, -1), low(N);
int cnt = 0;
stack<int> stk;
vector<bool> on_stack(N);
vector<vector<int>> scc;
function<void(int, int)> dfs = [&](int now, int pre) {
stk.push(now);
on_stack[now] = true;
ord[now] = cnt++;
low[now] = ord[now];
for (int nxt : E[now]) {
if (ord[nxt] < 0) {
// not visited
dfs(nxt, now);
low[now] = min(low[now], low[nxt]);
} else if (on_stack[nxt]) {
// visited
low[now] = min(low[now], ord[nxt]);
}
}
if (ord[now] == low[now]) {
scc.push_back({});
while (true) {
int v = stk.top();
stk.pop();
scc.back().push_back(v);
on_stack[v] = false;
if (v == now) break;
}
}
};
// 連結グラフならdfs(0)だけでOK
rep(i, N) if (ord[i] < 0) dfs(i, -1);
return scc;
} | 30.5 | 96 | 0.480399 | [
"vector"
] |
c76525e2c64bf158542b9a42494efc23ab081783 | 5,611 | cc | C++ | tensorflow/lite/micro/kernels/xtensa/reduce_vision.cc | trinitylundgren/tflite-micro | 262a902bff6a2845027391429c8cf71d86adc990 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/micro/kernels/xtensa/reduce_vision.cc | trinitylundgren/tflite-micro | 262a902bff6a2845027391429c8cf71d86adc990 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/micro/kernels/xtensa/reduce_vision.cc | trinitylundgren/tflite-micro | 262a902bff6a2845027391429c8cf71d86adc990 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if defined(VISION_P6)
#include <cstdint>
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/reference/reduce.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/xtensa/xtensa.h"
#include "tensorflow/lite/micro/kernels/xtensa/xtensa_reduce.h"
#include "tensorflow/lite/micro/micro_utils.h"
namespace tflite {
inline void OperandDims4D(uint32_t* dims, TfLiteTensor* opnd) {
for (int i = NumDimensions(opnd) - 1, j = 0; i >= 0; i--, j++) {
dims[j] = SizeOfDimension(opnd, i);
}
return;
}
// This function is duplicated from reference/reduce.h
// This method parses the input 'axis' to remove duplicates and handle negative
// values, and returns a valid 'out_axis'
inline bool ResolveAxis(const int num_dims, const int* axis,
const int64_t num_axis, int* out_axis,
int* out_num_axis) {
*out_num_axis = 0; // Just in case.
// Short-circuit axis resolution for scalars; the axis will go unused.
if (num_dims == 0) {
return true;
}
// o(n^2) is fine since out_num_axis should be really small, mostly <= 4
for (int64_t idx = 0; idx < num_axis; ++idx) {
// Handle negative index. A positive index 'p_idx' can be represented as a
// negative index 'n_idx' as: n_idx = p_idx-num_dims
// eg: For num_dims=3, [0, 1, 2] is the same as [-3, -2, -1] */
int current = axis[idx] < 0 ? (axis[idx] + num_dims) : axis[idx];
TFLITE_DCHECK(current >= 0 && current < num_dims);
if (current < 0 || current >= num_dims) {
return false;
}
bool is_dup = false;
for (int j = 0; j < *out_num_axis; ++j) {
if (out_axis[j] == current) {
is_dup = true;
break;
}
}
if (!is_dup) {
out_axis[*out_num_axis] = current;
*out_num_axis += 1;
}
}
return true;
}
TfLiteStatus ReducePrepareVision(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
TFLITE_DCHECK(node->builtin_data != nullptr);
XtensaReduceOpData* data =
reinterpret_cast<XtensaReduceOpData*>(node->user_data);
MicroContext* micro_context = GetMicroContext(context);
TfLiteTensor* input = micro_context->AllocateTempInputTensor(node, 0);
TfLiteTensor* output = micro_context->AllocateTempOutputTensor(node, 0);
TfLiteTensor* axis = micro_context->AllocateTempInputTensor(node, 1);
uint32_t inputDims[4] = {1, 1, 1, 1};
uint32_t outputDims[4] = {1, 1, 1, 1};
uint32_t shouldReduceR[4] = {0, 0, 0, 0};
int32_t resolved_axis[4] = {0, 0, 0, 0};
OperandDims4D(inputDims, input);
OperandDims4D(outputDims, output);
uint32_t inputRank = NumDimensions(input);
// Interpret an axis tensor with null dimensions as a scalar
int num_axis = static_cast<int>(ElementCount(*axis->dims));
// Resolve axis.
int num_resolved_axis = 0;
if (!ResolveAxis(input->dims->size, axis->data.i32, num_axis, resolved_axis,
&num_resolved_axis)) {
return kTfLiteError;
}
std::vector<bool> shouldReduce(inputRank);
for (int32_t i = 0; i < num_axis; ++i) {
int32_t axisD = resolved_axis[i];
shouldReduce[axisD] = true;
}
// reverse axes and align it to dimension 0 as OperandDims4D
for (uint32_t axisI = 0; axisI < inputRank; ++axisI) {
shouldReduceR[inputRank - 1 - axisI] = (uint32_t)shouldReduce[axisI];
}
uint32_t context_size = 0;
uint32_t status = xiReduceGetMemReqd_Context(&context_size);
if (!status && context_size) {
void* context_data =
context->AllocatePersistentBuffer(context, context_size);
if (context_data == nullptr) {
return kTfLiteError;
}
data->p_context = reinterpret_cast<uint8_t*>(context_data);
data->context_size = context_size;
}
status = xiReduceSetContext(data->p_context, data->context_size, inputDims,
outputDims, shouldReduceR);
if (status) {
return kTfLiteError;
}
micro_context->DeallocateTempTfLiteTensor(input);
micro_context->DeallocateTempTfLiteTensor(output);
micro_context->DeallocateTempTfLiteTensor(axis);
return kTfLiteOk;
}
TfLiteStatus ReduceEvalVision(const XtensaReduceOpData& data,
const TfLiteEvalTensor* input,
TfLiteEvalTensor* output) {
const uint32_t input_size = NumElements(input->dims);
const uint32_t output_size = NumElements(output->dims);
xiReduce(data.p_context, data.context_size,
const_cast<int8_t*>(tflite::micro::GetTensorData<int8_t>(input)),
input_size, tflite::micro::GetTensorData<int8_t>(output),
output_size);
return kTfLiteOk;
}
} // namespace tflite
#endif // defined(VISION_P6)
| 36.673203 | 80 | 0.681875 | [
"vector"
] |
c76e007d3b1becf0b30541b06ccb899e02d96382 | 2,260 | hpp | C++ | baidu/sample/dc/BDSSDKMessage.hpp | wangjinyu124419/long_audio_asr | d8dabf6cb10b282e3bd4981207c4a0f478977c9b | [
"MIT"
] | 6 | 2019-06-10T12:57:32.000Z | 2020-11-27T10:56:13.000Z | baidu/sample/dc/BDSSDKMessage.hpp | wangjinyu124419/long_audio_asr | d8dabf6cb10b282e3bd4981207c4a0f478977c9b | [
"MIT"
] | 1 | 2021-02-19T02:39:47.000Z | 2021-02-19T02:39:47.000Z | include/BDSSDKMessage.hpp | formattor/asr-linux-cpp-change | 630c54daf78f4f0f68e51f7aa996298ee517f2b1 | [
"MIT"
] | 1 | 2019-11-15T10:29:52.000Z | 2019-11-15T10:29:52.000Z | /***************************************************************************
*
* Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved
*
**************************************************************************/
/**
* @file BDSSDKMessage.hpp
* @author Vaino(lappivaeinoe@baidu.com)
* @date 2016/10/26 17:51:32
* @brief Message container to pass commands to SDK and receive events/callbacks from the SDK
*
**/
#ifndef _BDS_SDK_MESSAGE_HPP_
#define _BDS_SDK_MESSAGE_HPP_
#include <map>
#include <vector>
#include <string>
namespace bds {
extern const std::string DATA_CHUNK;
class BDSSDKMessageImpl;
class BDSSDKMessage{
public:
BDSSDKMessage(const std::string &p_name);
BDSSDKMessage();
BDSSDKMessage(const BDSSDKMessage &m);
virtual BDSSDKMessage& operator=(const BDSSDKMessage &m);
std::string name;
/*
char* data;
unsigned int length;
*/
virtual ~BDSSDKMessage();
/* Set parameters to message */
void set_parameter(const std::string &key, const std::string &value);
void set_parameter(const std::string &key, int value);
void set_parameter(const std::string &key, float value);
void set_parameter(const std::string &key, const char* value, int valueLen);
void set_parameter(const std::string &key, const std::vector<std::string> &value);
/* Get keys for parameters set to message */
std::vector<std::string> string_param_keys();
std::vector<std::string> int_param_keys();
std::vector<std::string> float_param_keys();
std::vector<std::string> char_param_keys();
std::vector<std::string> vector_param_keys();
/* Get parameters from message */
bool get_parameter(const std::string &key, std::string &outValue);
bool get_parameter(const std::string &key, int &outValue);
bool get_parameter(const std::string &key, float &outValue);
bool get_parameter(const std::string &key, const char* &outValue, int &outValueLen);
bool get_parameter(const std::string &key, std::vector<std::string> &outValue);
private:
BDSSDKMessageImpl* _impl;
friend class BDSSDKMessageImpl;
};
}
#endif
| 33.731343 | 93 | 0.612389 | [
"vector"
] |
c7830e60960953eca683e9287e197b677351c5bb | 8,385 | cc | C++ | CommBasicObjects/smartsoft/src-gen/CommBasicObjects/CommBasePoseCore.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | null | null | null | CommBasicObjects/smartsoft/src-gen/CommBasicObjects/CommBasePoseCore.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 2 | 2020-08-20T14:49:47.000Z | 2020-10-07T16:10:07.000Z | CommBasicObjects/smartsoft/src-gen/CommBasicObjects/CommBasePoseCore.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 8 | 2018-06-25T08:41:28.000Z | 2020-08-13T10:39:30.000Z | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "CommBasicObjects/CommBasePoseCore.hh"
// serialization/deserialization operators
//#include "CommBasicObjects/CommBasePoseACE.hh"
// include the hash.idl containing the hash constant
#include "hash.hh"
#include <assert.h>
#include <cstring>
#include <iostream>
// SmartUtils used in from_xml method
#include "smartKnuthMorrisPratt.hh"
#ifdef ENABLE_HASH
#include <boost/functional/hash.hpp>
#endif
namespace CommBasicObjects
{
const char* CommBasePoseCore::getCompiledHash()
{
return CommBasicObjectsIDL::REPO_HASH;
}
void CommBasePoseCore::getAllHashValues(std::list<std::string> &hashes)
{
// get own hash value
hashes.push_back(getCompiledHash());
// get hash value(s) for CommBasicObjects::CommPose3d(idl_CommBasePose.pose3D)
CommBasicObjects::CommPose3d::getAllHashValues(hashes);
// get hash value(s) for CommBasicObjects::CommTimeStamp(idl_CommBasePose.timeStamp)
CommBasicObjects::CommTimeStamp::getAllHashValues(hashes);
}
void CommBasePoseCore::checkAllHashValues(std::list<std::string> &hashes)
{
// check own hash value
if (strcmp(getCompiledHash(), hashes.front().c_str()) != 0)
{
std::cerr << "###################################################" << std::endl;
std::cerr << "WARNING: HASHES OF COMMUNICATION OBJECTS MISSMATCH!" << std::endl;
std::cerr << "CommBasePoseCore hash" << std::endl;
std::cerr << "Expected: " << getCompiledHash() << std::endl;
std::cerr << "Received: " << hashes.front() << std::endl;
std::cerr << "###################################################" << std::endl;
}
assert(strcmp(getCompiledHash(), hashes.front().c_str()) == 0);
hashes.pop_front();
// check hash value(s) for CommBasicObjects::CommPose3d(idl_CommBasePose.pose3D)
CommBasicObjects::CommPose3d::checkAllHashValues(hashes);
// check hash value(s) for CommBasicObjects::CommTimeStamp(idl_CommBasePose.timeStamp)
CommBasicObjects::CommTimeStamp::checkAllHashValues(hashes);
}
#ifdef ENABLE_HASH
size_t CommBasePoseCore::generateDataHash(const DATATYPE &data)
{
size_t seed = 0;
boost::hash_combine(seed, data.covInvalid);
std::vector<ACE_CDR::Double>::const_iterator data_covMatrixIt;
for(data_covMatrixIt=data.covMatrix.begin(); data_covMatrixIt!=data.covMatrix.end(); data_covMatrixIt++) {
boost::hash_combine(seed, *data_covMatrixIt);
}
boost::hash_combine(seed, data.updateCount);
seed += CommBasicObjects::CommPose3d::generateDataHash(data.pose3D);
seed += CommBasicObjects::CommTimeStamp::generateDataHash(data.timeStamp);
return seed;
}
#endif
// default constructor
CommBasePoseCore::CommBasePoseCore()
: idl_CommBasePose()
{
setCovInvalid(false);
setCovMatrix(std::vector<double>(9, 0.0));
setUpdateCount(0);
setPose3D(CommBasicObjects::CommPose3d());
setTimeStamp(CommBasicObjects::CommTimeStamp());
}
CommBasePoseCore::CommBasePoseCore(const DATATYPE &data)
: idl_CommBasePose(data)
{ }
CommBasePoseCore::~CommBasePoseCore()
{ }
void CommBasePoseCore::to_ostream(std::ostream &os) const
{
os << "CommBasePose(";
os << getCovInvalid() << " ";
std::vector<double>::const_iterator covMatrixIt;
std::vector<double> covMatrixList = getCovMatrixCopy();
for(covMatrixIt=covMatrixList.begin(); covMatrixIt!=covMatrixList.end(); covMatrixIt++) {
os << *covMatrixIt << " ";
}
os << getUpdateCount() << " ";
getPose3D().to_ostream(os);
getTimeStamp().to_ostream(os);
os << ") ";
}
// convert to xml stream
void CommBasePoseCore::to_xml(std::ostream &os, const std::string &indent) const {
size_t counter = 0;
os << indent << "<covInvalid>" << getCovInvalid() << "</covInvalid>";
std::vector<double>::const_iterator covMatrixIt;
std::vector<double> covMatrixList = getCovMatrixCopy();
counter = 0;
os << indent << "<covMatrixList n=\"" << covMatrixList.size() << "\">";
for(covMatrixIt=covMatrixList.begin(); covMatrixIt!=covMatrixList.end(); covMatrixIt++) {
os << indent << "<covMatrix i=\"" << counter++ << "\">" << *covMatrixIt << "</covMatrix>";
}
os << indent << "</covMatrixList>";
os << indent << "<updateCount>" << getUpdateCount() << "</updateCount>";
os << indent << "<pose3D>";
getPose3D().to_xml(os, indent);
os << indent << "</pose3D>";
os << indent << "<timeStamp>";
getTimeStamp().to_xml(os, indent);
os << indent << "</timeStamp>";
}
// restore from xml stream
void CommBasePoseCore::from_xml(std::istream &is) {
size_t counter = 0;
static const Smart::KnuthMorrisPratt kmp_covInvalid("<covInvalid>");
static const Smart::KnuthMorrisPratt kmp_covMatrixList("<covMatrixList n=\"");
static const Smart::KnuthMorrisPratt kmp_covMatrix("\">");
static const Smart::KnuthMorrisPratt kmp_updateCount("<updateCount>");
static const Smart::KnuthMorrisPratt kmp_pose3D("<pose3D>");
static const Smart::KnuthMorrisPratt kmp_timeStamp("<timeStamp>");
if(kmp_covInvalid.search(is)) {
bool covInvalidItem;
is >> covInvalidItem;
setCovInvalid(covInvalidItem);
}
if(kmp_covMatrixList.search(is)) {
size_t numberElements;
is >> numberElements;
double covMatrixItem;
std::vector<double> covMatrixList;
kmp_covMatrix.search(is);
for(counter=0; counter<numberElements; counter++) {
if(kmp_covMatrix.search(is)) {
is >> covMatrixItem;
covMatrixList.push_back(covMatrixItem);
}
}
setCovMatrix(covMatrixList);
}
if(kmp_updateCount.search(is)) {
unsigned int updateCountItem;
is >> updateCountItem;
setUpdateCount(updateCountItem);
}
if(kmp_pose3D.search(is)) {
CommBasicObjects::CommPose3d pose3DItem;
pose3DItem.from_xml(is);
setPose3D(pose3DItem);
}
if(kmp_timeStamp.search(is)) {
CommBasicObjects::CommTimeStamp timeStampItem;
timeStampItem.from_xml(is);
setTimeStamp(timeStampItem);
}
}
/*
void CommBasePoseCore::get(ACE_Message_Block *&msg) const
{
// start with a default internal buffer size(will automatically grow if needed)
ACE_OutputCDR cdr(ACE_DEFAULT_CDR_BUFSIZE);
CommBasicObjectsIDL::HashList hashes;
getAllHashValues(hashes);
cdr << static_cast<ACE_CDR::Long>(hashes.size());
for(CommBasicObjectsIDL::HashList::const_iterator it=hashes.begin(); it!=hashes.end(); it++)
{
cdr << ACE_CString(it->c_str());
}
// Here the actual serialization takes place using the OutputCDR serialization operator<<
// (see CommBasePoseACE.hh)
cdr << idl_CommBasePose;
#ifdef ENABLE_HASH
ACE_CDR::ULong data_hash = generateDataHash(idl_CommBasePose);
cdr << data_hash;
// std::cout << "CommBasePoseCore: current data hash: " << data_hash << std::endl;
#endif
// return a shallow copy of the serialized message
// (no data is actually copied, only the internal reference counter is incremented)
// in order to prevent memory leaks the caller of this get(msg) method must
// manually free the memory by calling the release() method of the message block msg
msg = cdr.begin()->duplicate();
}
void CommBasePoseCore::set(const ACE_Message_Block *msg)
{
ACE_InputCDR cdr(msg);
CommBasicObjectsIDL::HashList hashes;
ACE_CDR::Long hashes_size;
cdr >> hashes_size;
for(int i=0; i<hashes_size; ++i)
{
ACE_CString hash;
cdr >> hash;
hashes.push_back(hash.c_str());
}
checkAllHashValues(hashes);
// Here the actual de-serialization takes place using the InputCDR serialization operator>>
// (see CommBasePoseACE.hh)
cdr >> idl_CommBasePose;
#ifdef ENABLE_HASH
ACE_CDR::Long data_hash;
cdr >> data_hash;
ACE_CDR::Long own_hash = generateDataHash(idl_CommBasePose);
assert(data_hash == own_hash);
// std::cout << "CommBasePoseCore: own data hash: " << own_hash << "; received data hash: " << data_hash << std::endl;
#endif
}
*/
} /* namespace CommBasicObjects */
| 33.27381 | 120 | 0.687537 | [
"vector"
] |
c7863d35fd27600a945fe617a2e29b86d8ae2a8c | 2,586 | cpp | C++ | motor_control/basic_xy/UDP_FullDuplexS9/UDP_FullDuplexS9.cpp | csteinmetz1/ah-clark | f421e214d6085ea3346ddba3d717516ed226278f | [
"Apache-2.0"
] | null | null | null | motor_control/basic_xy/UDP_FullDuplexS9/UDP_FullDuplexS9.cpp | csteinmetz1/ah-clark | f421e214d6085ea3346ddba3d717516ed226278f | [
"Apache-2.0"
] | null | null | null | motor_control/basic_xy/UDP_FullDuplexS9/UDP_FullDuplexS9.cpp | csteinmetz1/ah-clark | f421e214d6085ea3346ddba3d717516ed226278f | [
"Apache-2.0"
] | null | null | null | // UDP_FullDuplexS9.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
// Two neccessary header files you need to include.
// Place the include for winsock2.h at the beginning of your include statements to avoid a conflict with an older library
#include <winsock2.h>
#include "xPCUDPSock.h"
#include <stdio.h>
#include <string>
#include "Tiva.h"
#pragma pack(push,1) // Important! Tell the compiler to pack things up tightly
//buffer structure definition
struct PACKIN
{
float flt1;
float flt2;
};
struct PACKOUT
{
float flt1;
float flt2;
};
#pragma pack(pop) // Fall back to previous setting
int _tmain(int argc, TCHAR* argv[])
{
int nRetCode = 0;
int userInput = 0;
// Initialize the UDP lib. If failed, quit running.
if (!InitUDPLib())
{
nRetCode = 2;
}
else
{
// Create receiver, with packet size equal to that of PACKIN and port at 12403 or the output port for the Tiva in virtual port 3
CUDPReceiver receiver(sizeof(PACKIN), 12403);
// Create sender, with packet size equal to that of PACKOUT and port at port is 12302 or input port for the Tiva in virtual port 2,
// and remote address 127.0.0.1(localhost)
CUDPSender sender(sizeof(PACKOUT), 12302, "127.0.0.1");
// Define buffers for input and output
PACKIN pkin;
PACKOUT pkout;
float x, y;
char string[256];
char* pEnd;
TivaController Tiva = TivaController(1.0, 46.75, 24.25, 36.0, -22.6);
Vec_double setPoint;
Vec_double home;
home.x = 0;
home.y = 0;
Tiva.moveArm(home, false);
std::vector<Vec_double> path;
receiver.GetData(&pkin);
Tiva.moveArm(home, false);
// repack the data
pkout.flt1 = float(Tiva.getMotor1AngleDegrees());
pkout.flt2 = float(Tiva.getMotor2AngleDegrees());
// send the repacked data through sender
sender.SendData(&pkout);
// Routing data endlessly
while (1)
{
printf("Enter x: ");
fgets(string, 100, stdin);
x = strtof(string, &pEnd);
printf("Enter y: ");
fgets(string, 100, stdin);
y = strtof(string, &pEnd);
setPoint.x = x;
setPoint.y = y;
path = Tiva.computeLinearPath(Tiva.getArm2Location(), setPoint, 300);
// prevent from running to fast
for (auto point : path)
{
Sleep(1);
// get latest data from receiver
receiver.GetData(&pkin);
Tiva.moveArm(point, false);
// repack the data
pkout.flt1 = float(Tiva.getMotor1AngleDegrees());
pkout.flt2 = float(Tiva.getMotor2AngleDegrees());
// send the repacked data through sender
sender.SendData(&pkout);
}
}
}
return nRetCode;
}
| 22.486957 | 134 | 0.683681 | [
"vector"
] |
c7986808fb202e725219486ec4427d2a95e28c78 | 9,940 | cc | C++ | 18 Spring/4611 Programming Interative Graphics and Games/Assignments/a5-artrender/artrender_app.cc | oway13/Schoolwork | 294f407c288ef532f8f187a6ee0bd9fd0e7559ab | [
"MIT"
] | null | null | null | 18 Spring/4611 Programming Interative Graphics and Games/Assignments/a5-artrender/artrender_app.cc | oway13/Schoolwork | 294f407c288ef532f8f187a6ee0bd9fd0e7559ab | [
"MIT"
] | null | null | null | 18 Spring/4611 Programming Interative Graphics and Games/Assignments/a5-artrender/artrender_app.cc | oway13/Schoolwork | 294f407c288ef532f8f187a6ee0bd9fd0e7559ab | [
"MIT"
] | null | null | null | /** CSci-4611 Assignment 5: Art Render
*/
#include "artrender_app.h"
#include "config.h"
#include <iostream>
#include <sstream>
using namespace std;
ArtRenderApp::ArtRenderApp() : GraphicsApp(1024,768, "Art Render"),
shader_style_(0), current_model_(0), light_pos_(3,3,3),
diffuse_ramp_(GL_CLAMP_TO_EDGE), specular_ramp_(GL_CLAMP_TO_EDGE)
{
// Define a search path for finding data files (images and shaders)
search_path_.push_back(".");
search_path_.push_back("./data");
search_path_.push_back("./shaders");
search_path_.push_back(DATA_DIR_INSTALL);
search_path_.push_back(DATA_DIR_BUILD);
search_path_.push_back(SHADERS_DIR_INSTALL);
search_path_.push_back(SHADERS_DIR_BUILD);
model_files_.push_back("bunny.obj");
model_files_.push_back("chamferedCube.obj");
model_files_.push_back("cow.obj");
model_files_.push_back("hippo.obj");
model_files_.push_back("maxplanck.obj");
model_files_.push_back("sphere.obj");
model_files_.push_back("teapot.obj");
}
ArtRenderApp::~ArtRenderApp() {
}
void ArtRenderApp::InitNanoGUI() {
// Setup the GUI window
nanogui::Window *window = new nanogui::Window(screen(), "Shading Style");
window->setPosition(Eigen::Vector2i(10, 10));
window->setSize(Eigen::Vector2i(200,100));
window->setLayout(new nanogui::GroupLayout());
new nanogui::Label(window, "Rendering Style", "sans-bold");
nanogui::Button* btn1 = new nanogui::Button(window, "Phong Shading");
btn1->setCallback(std::bind(&ArtRenderApp::OnPhongBtnPressed, this));
nanogui::Button* btn2 = new nanogui::Button(window, "Artsy Shading");
btn2->setCallback(std::bind(&ArtRenderApp::OnArtsyBtnPressed, this));
nanogui::Button* btn3 = new nanogui::Button(window, "Gouraud Shading");
btn3->setCallback(std::bind(&ArtRenderApp::OnGourBtnPressed, this));
new nanogui::Label(window, "Model", "sans-bold");
for (int i=0; i<model_files_.size(); i++) {
nanogui::Button* btn = new nanogui::Button(window, model_files_[i]);
btn->setCallback( [this,i]{ this->current_model_ = i; } );
Mesh m;
m.LoadFromOBJ(Platform::FindFile(model_files_[i], search_path_));
meshes_.push_back(m);
EdgeMesh em;
em.CreateFromMesh(m);
edge_meshes_.push_back(em);
}
screen()->performLayout();
}
void ArtRenderApp::OnLeftMouseDown(const Point2 &pos) {
Point2 normalizedMousePos = PixelsToNormalizedDeviceCoords(pos);
float mouseZ = ReadZValueAtPixel(pos);
uni_cam_.OnButtonDown(normalizedMousePos, mouseZ);
}
void ArtRenderApp::OnLeftMouseDrag(const Point2 &pos, const Vector2 &delta) {
Point2 normalizedMousePos = PixelsToNormalizedDeviceCoords(pos);
uni_cam_.OnDrag(normalizedMousePos);
}
void ArtRenderApp::OnLeftMouseUp(const Point2 &pos) {
Point2 normalizedMousePos = PixelsToNormalizedDeviceCoords(pos);
uni_cam_.OnButtonUp(normalizedMousePos);
}
void ArtRenderApp::UpdateSimulation(double dt) {
uni_cam_.AdvanceAnimation(dt);
}
void ArtRenderApp::OnPhongBtnPressed() {
shader_style_ = 0;
}
void ArtRenderApp::OnGourBtnPressed() {
shader_style_ = 2;
}
void ArtRenderApp::OnArtsyBtnPressed() {
shader_style_ = 1;
}
void ArtRenderApp::InitOpenGL() {
// Set up the camera in a good position to see the entire field
proj_matrix_ = Matrix4::Perspective(30, aspect_ratio(), 1, 20);
uni_cam_.set_view_matrix(Matrix4::LookAt(Point3(0,0,3), Point3(0,0,0), Vector3(0,1,0)));
glClearColor(0.7, 0.7, 0.7, 1);
phong_shaderprog_.AddVertexShaderFromFile(Platform::FindFile("phong.vert", search_path_));
phong_shaderprog_.AddFragmentShaderFromFile(Platform::FindFile("phong.frag", search_path_));
phong_shaderprog_.LinkProgram();
gour_shaderprog_.AddVertexShaderFromFile(Platform::FindFile("gouraud.vert", search_path_));
gour_shaderprog_.AddFragmentShaderFromFile(Platform::FindFile("gouraud.frag", search_path_));
gour_shaderprog_.LinkProgram();
artsy_shaderprog_.AddVertexShaderFromFile(Platform::FindFile("artsy.vert", search_path_));
artsy_shaderprog_.AddFragmentShaderFromFile(Platform::FindFile("artsy.frag", search_path_));
artsy_shaderprog_.LinkProgram();
outline_shaderprog_.AddVertexShaderFromFile(Platform::FindFile("outline.vert", search_path_));
outline_shaderprog_.AddFragmentShaderFromFile(Platform::FindFile("outline.frag", search_path_));
outline_shaderprog_.LinkProgram();
diffuse_ramp_.InitFromFile(Platform::FindFile("toonDiffuse.png", search_path_));
specular_ramp_.InitFromFile(Platform::FindFile("toonSpecular.png", search_path_));
stand_diff_ramp_.InitFromFile(Platform::FindFile("standardDiffuse.png", search_path_));
stand_spec_ramp_.InitFromFile(Platform::FindFile("standardSpecular.png", search_path_));
}
void ArtRenderApp::DrawUsingOpenGL() {
// Just the identity matrix
Matrix4 model_matrix;
// Lighting parameters
static const Color Ia(0.3, 0.3, 0.3, 1);
static const Color Id(0.7, 0.7, 0.7, 1);
static const Color Is(1.0, 1.0, 1.0, 1);
// Material parameters
static const Color ka(1.0, 0.4, 0.4, 1);
static const Color kd(1.0, 0.4, 0.4, 1);
static const Color ks(0.6, 0.6, 0.6, 1);
static const float s = 50;
// Precompute items needed in the shader
// Light positions are usually defined in world space. For lighting calculations
// we need the position of the light in view space (a.k.a. eye space).
Point3 light_in_view_space = uni_cam_.view_matrix() * light_pos_;
// The shader also needs these matrices
Matrix4 model_view_matrix = uni_cam_.view_matrix()*model_matrix;
Matrix4 normal_matrix = model_view_matrix.Inverse().Transpose();
// Make sure the default option to only draw front facing triangles is set
glEnable(GL_CULL_FACE);
if (shader_style_ == 0) {
// Render the current model's mesh using the Phong shader program
phong_shaderprog_.UseProgram();
phong_shaderprog_.SetUniform("modelViewMatrix", model_view_matrix);
phong_shaderprog_.SetUniform("normalMatrix", normal_matrix);
phong_shaderprog_.SetUniform("projectionMatrix", proj_matrix_);
phong_shaderprog_.SetUniform("ka", ka);
phong_shaderprog_.SetUniform("kd", kd);
phong_shaderprog_.SetUniform("ks", ks);
phong_shaderprog_.SetUniform("s", s);
phong_shaderprog_.SetUniform("lightPosition", light_in_view_space);
phong_shaderprog_.SetUniform("Ia", Ia);
phong_shaderprog_.SetUniform("Id", Id);
phong_shaderprog_.SetUniform("Is", Is);
phong_shaderprog_.BindTexture("standdiffuseRamp", stand_diff_ramp_);
phong_shaderprog_.BindTexture("standspecularRamp", stand_spec_ramp_);
meshes_[current_model_].Draw();
phong_shaderprog_.StopProgram();
}
else if (shader_style_ == 1) {
// Rendering using the Artsy shader programs
// Step 1: Use the toon shader to draw the object's mesh
artsy_shaderprog_.UseProgram();
artsy_shaderprog_.SetUniform("modelViewMatrix", model_view_matrix);
artsy_shaderprog_.SetUniform("normalMatrix", normal_matrix);
artsy_shaderprog_.SetUniform("projectionMatrix", proj_matrix_);
artsy_shaderprog_.SetUniform("ka", ka);
artsy_shaderprog_.SetUniform("kd", kd);
artsy_shaderprog_.SetUniform("ks", ks);
artsy_shaderprog_.SetUniform("s", s);
artsy_shaderprog_.SetUniform("lightPosition", light_in_view_space);
artsy_shaderprog_.SetUniform("Ia", Ia);
artsy_shaderprog_.SetUniform("Id", Id);
artsy_shaderprog_.SetUniform("Is", Is);
artsy_shaderprog_.BindTexture("diffuseRamp", diffuse_ramp_);
artsy_shaderprog_.BindTexture("specularRamp", specular_ramp_);
meshes_[current_model_].Draw();
artsy_shaderprog_.StopProgram();
// Step 2: Draw the silhouette edge using the edge mesh and outline shader
// Disable back face culling so OpenGL will draw both front and back facing triangles
glDisable(GL_CULL_FACE);
// Set the OpenGL polygon offset so it will draw triangles even if they
// exactly on top of another triangle
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1,1);
static const float thickness = 0.01;
// Draw edge mesh
outline_shaderprog_.UseProgram();
outline_shaderprog_.SetUniform("modelViewMatrix", model_view_matrix);
outline_shaderprog_.SetUniform("normalMatrix", normal_matrix);
outline_shaderprog_.SetUniform("projectionMatrix", proj_matrix_);
outline_shaderprog_.SetUniform("thickness", thickness);
edge_meshes_[current_model_].Draw();
outline_shaderprog_.StopProgram();
} else if (shader_style_ == 2) {
// Render the current model's mesh using the Gouraud shader program
gour_shaderprog_.UseProgram();
gour_shaderprog_.SetUniform("modelViewMatrix", model_view_matrix);
gour_shaderprog_.SetUniform("normalMatrix", normal_matrix);
gour_shaderprog_.SetUniform("projectionMatrix", proj_matrix_);
gour_shaderprog_.SetUniform("ka", ka);
gour_shaderprog_.SetUniform("kd", kd);
gour_shaderprog_.SetUniform("ks", ks);
gour_shaderprog_.SetUniform("s", s);
gour_shaderprog_.SetUniform("lightPosition", light_in_view_space);
gour_shaderprog_.SetUniform("Ia", Ia);
gour_shaderprog_.SetUniform("Id", Id);
gour_shaderprog_.SetUniform("Is", Is);
meshes_[current_model_].Draw();
gour_shaderprog_.StopProgram();
}
// Draw the UniCam widget when in rotation mode
uni_cam_.Draw(proj_matrix_);
}
| 37.938931 | 100 | 0.697485 | [
"mesh",
"render",
"object",
"model"
] |
c79dfef951126f86371b000437c67301c8738c75 | 2,975 | hpp | C++ | tracking/include/pcl/tracking/impl/kld_adaptive_particle_filter.hpp | zhangxaochen/CuFusion | e8bab7a366b1f2c85a80b95093d195d9f0774c11 | [
"MIT"
] | 52 | 2017-09-05T13:31:44.000Z | 2022-03-14T08:48:29.000Z | tracking/include/pcl/tracking/impl/kld_adaptive_particle_filter.hpp | GucciPrada/CuFusion | 522920bcf316d1ddf9732fc71fa457174168d2fb | [
"MIT"
] | 4 | 2018-05-17T22:45:35.000Z | 2020-02-01T21:46:42.000Z | tracking/include/pcl/tracking/impl/kld_adaptive_particle_filter.hpp | GucciPrada/CuFusion | 522920bcf316d1ddf9732fc71fa457174168d2fb | [
"MIT"
] | 21 | 2015-07-27T13:00:36.000Z | 2022-01-17T08:18:41.000Z | #ifndef PCL_TRACKING_IMPL_KLD_ADAPTIVE_PARTICLE_FILTER_H_
#define PCL_TRACKING_IMPL_KLD_ADAPTIVE_PARTICLE_FILTER_H_
template <typename PointInT, typename StateT> bool
pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::initCompute ()
{
if (!Tracker<PointInT, StateT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
return (false);
}
if (transed_reference_vector_.empty ())
{
// only one time allocation
transed_reference_vector_.resize (maximum_particle_number_);
for (unsigned int i = 0; i < maximum_particle_number_; i++)
{
transed_reference_vector_[i] = PointCloudInPtr (new PointCloudIn ());
}
}
coherence_->setTargetCloud (input_);
if (!change_detector_)
change_detector_ = boost::shared_ptr<pcl::octree::OctreePointCloudChangeDetector<PointInT> >(new pcl::octree::OctreePointCloudChangeDetector<PointInT> (change_detector_resolution_));
if (!particles_ || particles_->points.empty ())
initParticles (true);
return (true);
}
template <typename PointInT, typename StateT> bool
pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::insertIntoBins
(std::vector<int> bin, std::vector<std::vector<int> > &B)
{
for (size_t i = 0; i < B.size (); i++)
{
if (equalBin (bin, B[i]))
return false;
}
B.push_back (bin);
return true;
}
template <typename PointInT, typename StateT> void
pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::resample ()
{
unsigned int k = 0;
unsigned int n = 0;
PointCloudStatePtr S (new PointCloudState);
std::vector<std::vector<int> > B; // bins
// initializing for sampling without replacement
std::vector<int> a (particles_->points.size ());
std::vector<double> q (particles_->points.size ());
this->genAliasTable (a, q, particles_);
const std::vector<double> zero_mean (StateT::stateDimension (), 0.0);
// select the particles with KLD sampling
do
{
int j_n = sampleWithReplacement (a, q);
StateT x_t = particles_->points[j_n];
x_t.sample (zero_mean, step_noise_covariance_);
// motion
if (rand () / double (RAND_MAX) < motion_ratio_)
x_t = x_t + motion_;
S->points.push_back (x_t);
// calc bin
std::vector<int> bin (StateT::stateDimension ());
for (int i = 0; i < StateT::stateDimension (); i++)
bin[i] = static_cast<int> (x_t[i] / bin_size_[i]);
// calc bin index... how?
if (insertIntoBins (bin, B))
++k;
++n;
}
while (k < 2 || (n < maximum_particle_number_ && n < calcKLBound (k)));
particles_ = S; // swap
particle_num_ = static_cast<int> (particles_->points.size ());
}
#define PCL_INSTANTIATE_KLDAdaptiveParticleFilterTracker(T,ST) template class PCL_EXPORTS pcl::tracking::KLDAdaptiveParticleFilterTracker<T,ST>;
#endif
| 31.989247 | 187 | 0.662857 | [
"vector"
] |
c7a08cbf9df2355e6b9fbf13903f27022fed763a | 1,117 | cpp | C++ | 1021.cpp | Insensatez/URI | b1f0a431ec935b5b86af4b383d0103352c3a4dea | [
"Unlicense"
] | null | null | null | 1021.cpp | Insensatez/URI | b1f0a431ec935b5b86af4b383d0103352c3a4dea | [
"Unlicense"
] | null | null | null | 1021.cpp | Insensatez/URI | b1f0a431ec935b5b86af4b383d0103352c3a4dea | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main(){
double valor;
vector<int> notas;
notas.push_back(100);
notas.push_back(50);
notas.push_back(20);
notas.push_back(10);
notas.push_back(5);
notas.push_back(2);
vector<double> moedas;
moedas.push_back(1.00);
moedas.push_back(0.50);
moedas.push_back(0.25);
moedas.push_back(0.10);
moedas.push_back(0.05);
moedas.push_back(0.01);
cin >> valor;
valor += 0.001; // ajuste de precisão
cout.precision(2);
cout << fixed;
cout << "NOTAS:" << endl;
for(unsigned int i = 0; i < notas.size(); i++){
cout << ((int)(valor / notas[i])) << " nota(s) de R$ "<< notas[i] << ".00" << endl;
valor -= ((int)(valor / notas[i])) * notas[i];
}
cout << "MOEDAS:" << endl;
for(unsigned int i = 0; i < moedas.size(); i++){
cout << ((int)(valor / moedas[i])) << " moeda(s) de R$ "<< moedas[i]<< endl;
valor -= ((int)(valor / moedas[i])) * moedas[i];
}
return 0;
} | 25.386364 | 93 | 0.512086 | [
"vector"
] |
c7a15f23575a403260b1db708b74e47eee8266fa | 1,573 | cpp | C++ | Codeforces/Round-294-Div2/E.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-01-30T13:21:30.000Z | 2018-01-30T13:21:30.000Z | Codeforces/Round-294-Div2/E.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | null | null | null | Codeforces/Round-294-Div2/E.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-08-29T13:26:50.000Z | 2018-08-29T13:26:50.000Z | // Binary Lifting
// 5
// 07-10-2019
#include <bits/stdc++.h>
using namespace std;
const int MAX_V = 1e5 + 10, LG = 17;
int V, H[MAX_V], up[LG][MAX_V], sz[MAX_V];
vector <int> G[MAX_V];
int dfs (int u, int p = -1) {
sz[u] = 1;
for (int bit = 1; bit < LG; bit++) {
int v = up[bit - 1][u];
if (v == -1) break;
up[bit][u] = up[bit - 1][v];
}
for (int v: G[u]) {
if (v == p) continue;
H[v] = H[u] + 1;
up[0][v] = u;
sz[u] += dfs(v, u);
}
return sz[u];
}
int walk (int u, int k) {
for (int bit = LG - 1; bit >= 0; bit--)
if ((k >> bit) bitand 1) u = up[bit][u];
return u;
}
int getLCA (int u, int v) {
u = walk(u, H[u] - H[v]);
if (u == v) return u;
for (int bit = LG - 1; bit >= 0; bit--)
if (up[bit][u] != up[bit][v])
u = up[bit][u], v = up[bit][v];
return up[0][u];
}
int main () {
memset(up, -1, sizeof up);
scanf("%d", &V);
for (int i = 1; i < V; i++) {
int u, v;
scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1);
int q;
scanf("%d", &q);
while (q--) {
int u, v;
scanf("%d %d", &u, &v);
if (H[u] < H[v]) swap(u, v);
int lca = getLCA(u, v);
int path = (H[u] - H[lca]) + (H[v] - H[lca]);
if (path bitand 1) {
puts("0");
continue;
}
if (u == v) {
printf("%d\n", V);
continue;
}
int m = walk(u, path / 2);
if (m == lca) printf("%d\n", sz[1] - sz[walk(u, path / 2 - 1)] - sz[walk(v, path / 2 - 1)]);
else printf("%d\n", sz[m] - sz[walk(u, H[u] - H[m] - 1)]);
}
return (0);
}
| 20.428571 | 96 | 0.438652 | [
"vector"
] |
c7a5a95baf13bec342f5e73ea0590c7baeb4a04b | 1,041 | cpp | C++ | tests/map/accounting_map.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | 17 | 2018-08-22T06:48:20.000Z | 2022-02-22T21:20:09.000Z | tests/map/accounting_map.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | tests/map/accounting_map.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | // Copyright 2018 Oleksandr Bacherikov.
//
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include <actl/map/accounting_map.hpp>
#include <actl/std/map.hpp>
#include "test.hpp"
template <bool Invertible>
void test_accounting_map()
{
accounting_map<std::map<std::string, int>, Invertible> map;
CHECK(0 == get(map, "a"));
CHECK(1 == get(map, "s"));
CHECK(0 == get(map, "a"));
CHECK(2 == get(map, "p"));
CHECK(1 == get(map, "s"));
using C = std::vector<std::pair<std::string, int>>;
C expected{{"a", 0}, {"s", 1}, {"p", 2}};
auto r = map_range(map);
CHECK_EQUAL_SETS(expected, {r.begin(), r.end()});
if constexpr (Invertible)
{
for (int i = 0; i < 3; ++i)
{
CHECK(expected[(unsigned)i].first == invert(map, i));
}
}
}
TEST_CASE("non-invertible")
{
test_accounting_map<false>();
}
TEST_CASE("invertible")
{
test_accounting_map<true>();
}
| 24.785714 | 65 | 0.598463 | [
"vector"
] |
c7aafd8c00cb4af65b1128eab4e217f1401793a4 | 12,652 | cpp | C++ | tests/Unit/Evolution/Systems/NewtonianEuler/Subcell/Test_TimeDerivative.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | tests/Unit/Evolution/Systems/NewtonianEuler/Subcell/Test_TimeDerivative.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | tests/Unit/Evolution/Systems/NewtonianEuler/Subcell/Test_TimeDerivative.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <array>
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/EagerMath/Determinant.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Domain/Block.hpp"
#include "Domain/CoordinateMaps/Affine.hpp"
#include "Domain/CoordinateMaps/CoordinateMap.hpp"
#include "Domain/CoordinateMaps/CoordinateMap.tpp"
#include "Domain/CoordinateMaps/ProductMaps.hpp"
#include "Domain/CoordinateMaps/ProductMaps.tpp"
#include "Domain/CreateInitialElement.hpp"
#include "Domain/LogicalCoordinates.hpp"
#include "Domain/Structure/Element.hpp"
#include "Domain/Tags.hpp"
#include "Evolution/BoundaryCorrectionTags.hpp"
#include "Evolution/DgSubcell/Mesh.hpp"
#include "Evolution/DgSubcell/SliceData.hpp"
#include "Evolution/DgSubcell/Tags/Coordinates.hpp"
#include "Evolution/DgSubcell/Tags/Mesh.hpp"
#include "Evolution/DgSubcell/Tags/NeighborData.hpp"
#include "Evolution/DiscontinuousGalerkin/MortarTags.hpp"
#include "Evolution/Systems/NewtonianEuler/BoundaryCorrections/BoundaryCorrection.hpp"
#include "Evolution/Systems/NewtonianEuler/BoundaryCorrections/Factory.hpp"
#include "Evolution/Systems/NewtonianEuler/ConservativeFromPrimitive.hpp"
#include "Evolution/Systems/NewtonianEuler/FiniteDifference/AoWeno.hpp"
#include "Evolution/Systems/NewtonianEuler/FiniteDifference/MonotisedCentral.hpp"
#include "Evolution/Systems/NewtonianEuler/FiniteDifference/Tag.hpp"
#include "Evolution/Systems/NewtonianEuler/Subcell/TimeDerivative.hpp"
#include "Evolution/Systems/NewtonianEuler/System.hpp"
#include "Evolution/Systems/NewtonianEuler/Tags.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "PointwiseFunctions/AnalyticSolutions/NewtonianEuler/LaneEmdenStar.hpp"
#include "PointwiseFunctions/AnalyticSolutions/NewtonianEuler/SmoothFlow.hpp"
#include "PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp"
#include "PointwiseFunctions/Hydro/EquationsOfState/PolytropicFluid.hpp"
#include "PointwiseFunctions/Hydro/Tags.hpp"
namespace NewtonianEuler {
namespace {
using Affine = domain::CoordinateMaps::Affine;
using Affine2D = domain::CoordinateMaps::ProductOf2Maps<Affine, Affine>;
using Affine3D = domain::CoordinateMaps::ProductOf3Maps<Affine, Affine, Affine>;
template <size_t Dim>
auto make_coord_map();
template <>
auto make_coord_map<1>() {
Affine affine_map{-1.0, 1.0, 2.0, 3.0};
return domain::make_coordinate_map<Frame::ElementLogical, Frame::Inertial>(
affine_map);
}
template <>
auto make_coord_map<2>() {
Affine affine_map{-1.0, 1.0, 2.0, 3.0};
Affine2D product_map{affine_map, affine_map};
return domain::make_coordinate_map<Frame::ElementLogical, Frame::Inertial>(
product_map);
}
template <>
auto make_coord_map<3>() {
Affine affine_map{-1.0, 1.0, 2.0, 3.0};
Affine3D product_map{affine_map, affine_map, affine_map};
return domain::make_coordinate_map<Frame::ElementLogical, Frame::Inertial>(
product_map);
}
template <size_t Dim>
auto make_element();
template <>
auto make_element<1>() {
Affine affine_map{-1.0, 1.0, 2.0, 3.0};
return domain::Initialization::create_initial_element(
ElementId<1>{0, {SegmentId{3, 4}}},
Block<1>{domain::make_coordinate_map_base<Frame::BlockLogical,
Frame::Inertial>(affine_map),
0,
{},
{}},
std::vector<std::array<size_t, 1>>{std::array<size_t, 1>{{3}}});
}
template <>
auto make_element<2>() {
Affine affine_map{-1.0, 1.0, 2.0, 3.0};
return domain::Initialization::create_initial_element(
ElementId<2>{0, {SegmentId{3, 4}, SegmentId{3, 4}}},
Block<2>{domain::make_coordinate_map_base<Frame::BlockLogical,
Frame::Inertial>(
Affine2D{affine_map, affine_map}),
0,
{},
{}},
std::vector<std::array<size_t, 2>>{std::array<size_t, 2>{{3, 3}}});
}
template <>
auto make_element<3>() {
Affine affine_map{-1.0, 1.0, 2.0, 3.0};
return domain::Initialization::create_initial_element(
ElementId<3>{0, {SegmentId{3, 4}, SegmentId{3, 4}, SegmentId{3, 4}}},
Block<3>{domain::make_coordinate_map_base<Frame::BlockLogical,
Frame::Inertial>(
Affine3D{affine_map, affine_map, affine_map}),
0,
{},
{}},
std::vector<std::array<size_t, 3>>{std::array<size_t, 3>{{3, 3, 3}}});
}
template <size_t Dim>
struct SmoothFlowMetaVars {
static constexpr size_t volume_dim = Dim;
using initial_data = NewtonianEuler::Solutions::SmoothFlow<Dim>;
using source_term_type = typename initial_data::source_term_type;
using system = NewtonianEuler::System<Dim, initial_data>;
using source_term_tag = NewtonianEuler::Tags::SourceTerm<initial_data>;
static constexpr bool has_source_terms =
not std::is_same_v<source_term_type, NewtonianEuler::Sources::NoSource>;
static auto solution() {
return initial_data{make_array<Dim>(0.0), make_array<Dim>(-0.2), 0.5, 1.5,
0.01};
}
};
struct LaneEmdenStarMetaVars {
static constexpr size_t volume_dim = 3;
using initial_data = NewtonianEuler::Solutions::LaneEmdenStar;
using source_term_type = typename initial_data::source_term_type;
using system = NewtonianEuler::System<3, initial_data>;
using source_term_tag = NewtonianEuler::Tags::SourceTerm<initial_data>;
static constexpr bool has_source_terms = true;
static auto solution() { return initial_data{0.7, 250.0}; }
};
template <typename Metavariables>
std::array<double, 3> test(const size_t num_dg_pts) {
using metavariables = Metavariables;
static constexpr size_t dim = metavariables::volume_dim;
using solution = typename metavariables::initial_data;
using eos = typename solution::equation_of_state_type;
using system = typename metavariables::system;
const auto coordinate_map = make_coord_map<dim>();
const auto element = make_element<dim>();
const solution soln = metavariables::solution();
const double time = 0.0;
const Mesh<dim> dg_mesh{num_dg_pts, Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto};
const Mesh<dim> subcell_mesh = evolution::dg::subcell::fd::mesh(dg_mesh);
const auto cell_centered_coords =
coordinate_map(logical_coordinates(subcell_mesh));
using prim_tags = typename system::primitive_variables_tag::tags_list;
Variables<prim_tags> cell_centered_prim_vars{
subcell_mesh.number_of_grid_points()};
cell_centered_prim_vars.assign_subset(
soln.variables(cell_centered_coords, time, prim_tags{}));
using variables_tag = typename system::variables_tag;
using dt_variables_tag = db::add_tag_prefix<::Tags::dt, variables_tag>;
// Neighbor data for reconstruction.
//
// 0. neighbors coords (our logical coords +2)
// 1. compute prims from solution
// 2. compute prims needed for reconstruction
// 3. set neighbor data
typename evolution::dg::subcell::Tags::NeighborDataForReconstruction<
dim>::type neighbor_data{};
using prims_to_reconstruct_tags =
tmpl::list<NewtonianEuler::Tags::MassDensity<DataVector>,
NewtonianEuler::Tags::Velocity<DataVector, dim>,
NewtonianEuler::Tags::Pressure<DataVector>>;
for (const Direction<dim>& direction : Direction<dim>::all_directions()) {
auto neighbor_logical_coords = logical_coordinates(subcell_mesh);
neighbor_logical_coords.get(direction.dimension()) +=
2.0 * direction.sign();
auto neighbor_coords = coordinate_map(neighbor_logical_coords);
const auto neighbor_prims =
soln.variables(neighbor_coords, time, prim_tags{});
Variables<prims_to_reconstruct_tags> prims_to_reconstruct{
subcell_mesh.number_of_grid_points()};
tmpl::for_each<prims_to_reconstruct_tags>(
[&prims_to_reconstruct, &neighbor_prims](auto tag_v) {
using tag = tmpl::type_from<decltype(tag_v)>;
get<tag>(prims_to_reconstruct) = get<tag>(neighbor_prims);
});
// Slice data so we can add it to the element's neighbor data
DirectionMap<dim, bool> directions_to_slice{};
directions_to_slice[direction.opposite()] = true;
std::vector<double> neighbor_data_in_direction =
evolution::dg::subcell::slice_data(
prims_to_reconstruct, subcell_mesh.extents(),
NewtonianEuler::fd::MonotisedCentralPrim<dim>{}.ghost_zone_size(),
directions_to_slice)
.at(direction.opposite());
neighbor_data[std::pair{direction,
*element.neighbors().at(direction).begin()}] =
neighbor_data_in_direction;
}
auto box = db::create<
db::AddSimpleTags<
Parallel::Tags::MetavariablesImpl<metavariables>,
typename metavariables::source_term_tag,
::Tags::AnalyticSolution<solution>,
evolution::dg::subcell::Tags::Coordinates<dim, Frame::Inertial>,
domain::Tags::Element<dim>, evolution::dg::subcell::Tags::Mesh<dim>,
fd::Tags::Reconstructor<dim>,
evolution::Tags::BoundaryCorrection<system>,
hydro::Tags::EquationOfState<eos>,
typename system::primitive_variables_tag, dt_variables_tag,
variables_tag,
evolution::dg::subcell::Tags::NeighborDataForReconstruction<dim>,
evolution::dg::Tags::MortarData<dim>>,
db::AddComputeTags<
evolution::dg::subcell::Tags::LogicalCoordinatesCompute<dim>>>(
metavariables{}, typename metavariables::source_term_tag::type{}, soln,
cell_centered_coords, element, subcell_mesh,
std::unique_ptr<NewtonianEuler::fd::Reconstructor<dim>>{
std::make_unique<NewtonianEuler::fd::MonotisedCentralPrim<dim>>()},
std::unique_ptr<
NewtonianEuler::BoundaryCorrections::BoundaryCorrection<dim>>{
std::make_unique<NewtonianEuler::BoundaryCorrections::Hll<dim>>()},
soln.equation_of_state(), cell_centered_prim_vars,
Variables<typename dt_variables_tag::tags_list>{
subcell_mesh.number_of_grid_points()},
typename variables_tag::type{}, neighbor_data,
typename evolution::dg::Tags::MortarData<dim>::type{});
db::mutate_apply<ConservativeFromPrimitive<dim>>(make_not_null(&box));
InverseJacobian<DataVector, dim, Frame::ElementLogical, Frame::Grid>
cell_centered_logical_to_grid_inv_jacobian{};
const auto cell_centered_logical_to_inertial_inv_jacobian =
coordinate_map.inv_jacobian(logical_coordinates(subcell_mesh));
for (size_t i = 0; i < cell_centered_logical_to_grid_inv_jacobian.size();
++i) {
cell_centered_logical_to_grid_inv_jacobian[i] =
cell_centered_logical_to_inertial_inv_jacobian[i];
}
subcell::TimeDerivative::apply(
make_not_null(&box), cell_centered_logical_to_grid_inv_jacobian,
determinant(cell_centered_logical_to_grid_inv_jacobian));
const auto& dt_vars = db::get<dt_variables_tag>(box);
return {{max(abs(get(get<::Tags::dt<Tags::MassDensityCons>>(dt_vars)))),
max(abs(get(get<::Tags::dt<Tags::EnergyDensity>>(dt_vars)))),
max(get(magnitude(
get<::Tags::dt<Tags::MomentumDensity<dim>>>(dt_vars))))}};
}
template <typename Metavariables>
void test_convergence() {
// This tests sets up a stationary SmoothFlow problem or LaneEmdenStar and
// verifies that the time derivative vanishes. Or, more specifically, that the
// time derivative decreases with increasing resolution.
// For the SmoothFlow problem, the time derivatives of the momentum and energy
// densities are roundoff.
const auto four_pts_data = test<Metavariables>(4);
const auto eight_pts_data = test<Metavariables>(8);
for (size_t i = 0; i < four_pts_data.size(); ++i) {
const bool converging =
gsl::at(eight_pts_data, i) < gsl::at(four_pts_data, i);
const bool roundoff = gsl::at(eight_pts_data, i) < 1.e-14 and
gsl::at(four_pts_data, i) < 1.e-14;
CHECK((converging or roundoff));
}
}
SPECTRE_TEST_CASE(
"Unit.Evolution.Systems.NewtonianEuler.Subcell.TimeDerivative",
"[Unit][Evolution]") {
test_convergence<SmoothFlowMetaVars<1>>();
test_convergence<SmoothFlowMetaVars<2>>();
test_convergence<SmoothFlowMetaVars<3>>();
test_convergence<LaneEmdenStarMetaVars>();
}
} // namespace
} // namespace NewtonianEuler
| 42.599327 | 86 | 0.71301 | [
"mesh",
"vector"
] |
c7ab52f9422182e68aa58ec79172dbbc2b2b2ed1 | 13,510 | cc | C++ | chrome/browser/gtk/options/passwords_page_gtk.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/browser/gtk/options/passwords_page_gtk.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/gtk/options/passwords_page_gtk.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 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 "chrome/browser/gtk/options/passwords_page_gtk.h"
#include "app/gfx/gtk_util.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/common/gtk_tree.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/url_constants.h"
#include "grit/app_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
namespace {
// Initial width of the first column.
const int kSiteColumnInitialSize = 265;
// Column ids for |password_list_store_|.
enum {
COL_SITE,
COL_USERNAME,
COL_COUNT,
};
} // anonymous namespace
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageGtk, public:
PasswordsPageGtk::PasswordsPageGtk(Profile* profile)
: populater(this), password_showing_(false), profile_(profile) {
remove_button_ = gtk_button_new_with_label(
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON).c_str());
gtk_widget_set_sensitive(remove_button_, FALSE);
g_signal_connect(G_OBJECT(remove_button_), "clicked",
G_CALLBACK(OnRemoveButtonClicked), this);
remove_all_button_ = gtk_button_new_with_label(l10n_util::GetStringUTF8(
IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON).c_str());
gtk_widget_set_sensitive(remove_all_button_, FALSE);
g_signal_connect(G_OBJECT(remove_all_button_), "clicked",
G_CALLBACK(OnRemoveAllButtonClicked), this);
show_password_button_ = gtk_button_new_with_label(
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON).c_str());
GtkRequisition hide_size, show_size;
// Get the size request of the button with the "hide password" text.
gtk_widget_size_request(show_password_button_, &hide_size);
gtk_button_set_label(GTK_BUTTON(show_password_button_),
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON).c_str());
// Get the size request of the button with the "show password" text.
gtk_widget_size_request(show_password_button_, &show_size);
// Determine the maximum width and height.
if (hide_size.width > show_size.width)
show_size.width = hide_size.width;
if (hide_size.height > show_size.height)
show_size.height = hide_size.height;
// Force the button to be large enough for both labels.
gtk_widget_set_size_request(show_password_button_, show_size.width,
show_size.height);
gtk_widget_set_sensitive(show_password_button_, FALSE);
g_signal_connect(G_OBJECT(show_password_button_), "clicked",
G_CALLBACK(OnShowPasswordButtonClicked), this);
password_ = gtk_label_new("");
GtkWidget* buttons = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(buttons), remove_button_, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(buttons), remove_all_button_, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(buttons), show_password_button_, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(buttons), password_, FALSE, FALSE, 0);
GtkWidget* scroll_window = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_window),
GTK_SHADOW_ETCHED_IN);
// Sets password_tree_ among other things.
InitPasswordTree();
gtk_container_add(GTK_CONTAINER(scroll_window), password_tree_);
page_ = gtk_hbox_new(FALSE, gtk_util::kControlSpacing);
gtk_container_set_border_width(GTK_CONTAINER(page_),
gtk_util::kContentAreaBorder);
gtk_box_pack_end(GTK_BOX(page_), buttons, FALSE, FALSE, 0);
gtk_box_pack_end(GTK_BOX(page_), scroll_window, TRUE, TRUE, 0);
}
PasswordsPageGtk::~PasswordsPageGtk() {
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageGtk, private:
void PasswordsPageGtk::InitPasswordTree() {
password_list_store_ = gtk_list_store_new(COL_COUNT,
G_TYPE_STRING,
G_TYPE_STRING);
password_list_sort_ = gtk_tree_model_sort_new_with_model(
GTK_TREE_MODEL(password_list_store_));
gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(password_list_sort_),
COL_SITE, CompareSite, this, NULL);
gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(password_list_sort_),
COL_USERNAME, CompareUsername, this, NULL);
password_tree_ = gtk_tree_view_new_with_model(password_list_sort_);
g_object_unref(password_list_store_);
g_object_unref(password_list_sort_);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(password_tree_), TRUE);
password_selection_ = gtk_tree_view_get_selection(
GTK_TREE_VIEW(password_tree_));
gtk_tree_selection_set_mode(password_selection_,
GTK_SELECTION_SINGLE);
g_signal_connect(G_OBJECT(password_selection_), "changed",
G_CALLBACK(OnPasswordSelectionChanged), this);
GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes(
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN).c_str(),
gtk_cell_renderer_text_new(),
"text", COL_SITE,
NULL);
gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_FIXED);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_column_set_fixed_width(column, kSiteColumnInitialSize);
gtk_tree_view_column_set_sort_column_id(column, COL_SITE);
gtk_tree_view_append_column(GTK_TREE_VIEW(password_tree_), column);
column = gtk_tree_view_column_new_with_attributes(
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN).c_str(),
gtk_cell_renderer_text_new(),
"text", COL_USERNAME,
NULL);
gtk_tree_view_column_set_sort_column_id(column, COL_USERNAME);
gtk_tree_view_append_column(GTK_TREE_VIEW(password_tree_), column);
populater.populate();
}
PasswordStore* PasswordsPageGtk::GetPasswordStore() {
return profile_->GetPasswordStore(Profile::EXPLICIT_ACCESS);
}
void PasswordsPageGtk::SetPasswordList(
const std::vector<webkit_glue::PasswordForm*>& result) {
std::wstring languages =
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
gtk_list_store_clear(password_list_store_);
password_list_.resize(result.size());
for (size_t i = 0; i < result.size(); ++i) {
password_list_[i] = *result[i];
std::wstring formatted = net::FormatUrl(result[i]->origin, languages,
false, UnescapeRule::NONE, NULL, NULL, NULL);
std::string site = WideToUTF8(formatted);
std::string user = UTF16ToUTF8(result[i]->username_value);
GtkTreeIter iter;
gtk_list_store_insert_with_values(password_list_store_, &iter, (gint) i,
COL_SITE, site.c_str(),
COL_USERNAME, user.c_str(), -1);
}
gtk_widget_set_sensitive(remove_all_button_, result.size() > 0);
}
// static
void PasswordsPageGtk::OnRemoveButtonClicked(GtkButton* widget,
PasswordsPageGtk* page) {
GtkTreeIter iter;
if (!gtk_tree_selection_get_selected(page->password_selection_,
NULL, &iter)) {
NOTREACHED();
return;
}
GtkTreePath* path = gtk_tree_model_get_path(
GTK_TREE_MODEL(page->password_list_sort_), &iter);
gint index = gtk_tree::GetTreeSortChildRowNumForPath(
page->password_list_sort_, path);
gtk_tree_path_free(path);
GtkTreeIter child_iter;
gtk_tree_model_sort_convert_iter_to_child_iter(
GTK_TREE_MODEL_SORT(page->password_list_sort_), &child_iter, &iter);
// Remove from GTK list, DB, and vector.
gtk_list_store_remove(page->password_list_store_, &child_iter);
page->GetPasswordStore()->RemoveLogin(page->password_list_[index]);
page->password_list_.erase(page->password_list_.begin() + index);
gtk_widget_set_sensitive(page->remove_all_button_,
page->password_list_.size() > 0);
}
// static
void PasswordsPageGtk::OnRemoveAllButtonClicked(GtkButton* widget,
PasswordsPageGtk* page) {
GtkWindow* window = GTK_WINDOW(gtk_widget_get_toplevel(page->page_));
GtkWidget* confirm = gtk_message_dialog_new(
window,
static_cast<GtkDialogFlags>(
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT),
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
"%s",
l10n_util::GetStringUTF8(
IDS_PASSWORDS_PAGE_VIEW_TEXT_DELETE_ALL_PASSWORDS).c_str());
gtk_util::ApplyMessageDialogQuirks(confirm);
gtk_window_set_title(GTK_WINDOW(confirm), l10n_util::GetStringUTF8(
IDS_PASSWORDS_PAGE_VIEW_CAPTION_DELETE_ALL_PASSWORDS).c_str());
g_signal_connect(confirm, "response", G_CALLBACK(OnRemoveAllConfirmResponse),
page);
gtk_widget_show_all(confirm);
}
// static
void PasswordsPageGtk::OnRemoveAllConfirmResponse(GtkDialog* confirm,
gint response,
PasswordsPageGtk* page) {
bool confirmed = false;
switch (response) {
case GTK_RESPONSE_YES:
confirmed = true;
break;
default:
break;
}
gtk_widget_destroy(GTK_WIDGET(confirm));
if (!confirmed)
return;
// Remove from GTK list, DB, and vector.
PasswordStore* store = page->GetPasswordStore();
gtk_list_store_clear(page->password_list_store_);
for (size_t i = 0; i < page->password_list_.size(); ++i) {
store->RemoveLogin(page->password_list_[i]);
}
page->password_list_.clear();
gtk_widget_set_sensitive(page->remove_all_button_, FALSE);
}
// static
void PasswordsPageGtk::OnShowPasswordButtonClicked(GtkButton* widget,
PasswordsPageGtk* page) {
page->password_showing_ = !page->password_showing_;
if (!page->password_showing_) {
// Hide the password.
gtk_label_set_text(GTK_LABEL(page->password_), "");
gtk_button_set_label(GTK_BUTTON(page->show_password_button_),
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON).c_str());
return;
}
// Show the password.
GtkTreeIter iter;
if (!gtk_tree_selection_get_selected(page->password_selection_,
NULL, &iter)) {
NOTREACHED();
return;
}
GtkTreePath* path = gtk_tree_model_get_path(
GTK_TREE_MODEL(page->password_list_sort_), &iter);
gint index = gtk_tree::GetTreeSortChildRowNumForPath(
page->password_list_sort_, path);
gtk_tree_path_free(path);
std::string pass = UTF16ToUTF8(page->password_list_[index].password_value);
gtk_label_set_text(GTK_LABEL(page->password_), pass.c_str());
gtk_button_set_label(GTK_BUTTON(page->show_password_button_),
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON).c_str());
}
// static
void PasswordsPageGtk::OnPasswordSelectionChanged(GtkTreeSelection* selection,
PasswordsPageGtk* page) {
// No matter how the selection changed, we want to hide the old password.
gtk_label_set_text(GTK_LABEL(page->password_), "");
gtk_button_set_label(GTK_BUTTON(page->show_password_button_),
l10n_util::GetStringUTF8(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON).c_str());
page->password_showing_ = false;
GtkTreeIter iter;
if (!gtk_tree_selection_get_selected(selection, NULL, &iter)) {
gtk_widget_set_sensitive(page->show_password_button_, FALSE);
gtk_widget_set_sensitive(page->remove_button_, FALSE);
return;
}
gtk_widget_set_sensitive(page->show_password_button_, TRUE);
gtk_widget_set_sensitive(page->remove_button_, TRUE);
}
// static
gint PasswordsPageGtk::CompareSite(GtkTreeModel* model,
GtkTreeIter* a, GtkTreeIter* b,
gpointer window) {
int row1 = gtk_tree::GetRowNumForIter(model, a);
int row2 = gtk_tree::GetRowNumForIter(model, b);
PasswordsPageGtk* page = reinterpret_cast<PasswordsPageGtk*>(window);
return page->password_list_[row1].origin.spec().compare(
page->password_list_[row2].origin.spec());
}
// static
gint PasswordsPageGtk::CompareUsername(GtkTreeModel* model,
GtkTreeIter* a, GtkTreeIter* b,
gpointer window) {
int row1 = gtk_tree::GetRowNumForIter(model, a);
int row2 = gtk_tree::GetRowNumForIter(model, b);
PasswordsPageGtk* page = reinterpret_cast<PasswordsPageGtk*>(window);
return page->password_list_[row1].username_value.compare(
page->password_list_[row2].username_value);
}
void PasswordsPageGtk::PasswordListPopulater::populate() {
DCHECK(!pending_login_query_);
PasswordStore* store = page_->GetPasswordStore();
pending_login_query_ = store->GetAutofillableLogins(this);
}
void PasswordsPageGtk::PasswordListPopulater::OnPasswordStoreRequestDone(
int handle, const std::vector<webkit_glue::PasswordForm*>& result) {
DCHECK_EQ(pending_login_query_, handle);
pending_login_query_ = 0;
page_->SetPasswordList(result);
}
| 41.189024 | 80 | 0.70792 | [
"vector",
"model"
] |
c7ae05cb24e3503aa4bb7abcb3902ce533236998 | 3,054 | hpp | C++ | Std/Forward.hpp | asynts/picoos | 5197f86ce1902fc6572cecd10f97ca68109f2f86 | [
"MIT"
] | 1 | 2021-08-24T05:59:32.000Z | 2021-08-24T05:59:32.000Z | Std/Forward.hpp | asynts/picoos | 5197f86ce1902fc6572cecd10f97ca68109f2f86 | [
"MIT"
] | 3 | 2021-03-31T15:36:01.000Z | 2021-04-19T14:17:44.000Z | Std/Forward.hpp | asynts/picoos | 5197f86ce1902fc6572cecd10f97ca68109f2f86 | [
"MIT"
] | null | null | null | #pragma once
#include <Std/Types.hpp>
constexpr usize KiB = 1024;
constexpr usize MiB = KiB * KiB;
#ifndef TEST
constexpr void* operator new(usize count, void* ptr)
{
return ptr;
}
constexpr void* operator new[](usize count, void* ptr)
{
return ptr;
}
void* operator new(usize);
void* operator new[](usize);
void operator delete(void*);
void operator delete[](void*);
#endif
template<typename T>
struct RemoveReference {
using Type = T;
};
template<typename T>
struct RemoveReference<T&> {
using Type = T;
};
template<typename T>
constexpr typename RemoveReference<T>::Type&& move(T&& value)
{
return static_cast<typename RemoveReference<T>::Type&&>(value);
}
template<typename T>
constexpr T&& forward(typename RemoveReference<T>::Type& value)
{
return static_cast<T&&>(value);
}
template<typename T>
constexpr T&& forward(typename RemoveReference<T>::Type&& value)
{
return static_cast<T&&>(value);
}
template<typename T, typename U = T>
constexpr T exchange(T& obj, U&& new_value)
{
T old_value = move(obj);
obj = forward<U>(new_value);
return move(old_value);
}
template<typename T>
constexpr void swap(T& lhs, T& rhs)
{
T value = move(lhs);
lhs = move(rhs);
rhs = move(value);
}
extern "C"
inline void strlcpy(char *destination, const char *source, usize size) noexcept
{
if (size >= 1) {
__builtin_strncpy(destination, source, size - 1);
destination[size - 1] = 0;
}
}
extern "C"
void* memcpy(void *destination, const void *source, usize count) noexcept;
template<typename T>
constexpr T max(T a, T b)
{
return a >= b ? a : b;
}
template<typename T>
constexpr T min(T a, T b)
{
return a <= b ? a : b;
}
inline usize round_to_power_of_two(usize value)
{
return 1 << (32 - __builtin_clz(value));
}
constexpr usize power_of_two(usize value)
{
return __builtin_ctzl(value);
}
template<typename T, void (T::*Method)()>
static void type_erased_member_function_wrapper(void *object)
{
(reinterpret_cast<T*>(object)->*Method)();
}
namespace Std {
enum class IterationDecision {
Continue,
Break,
};
class Path;
template<typename... Parameters>
void dbgln(const char *fmtstr, const Parameters&...);
[[noreturn]]
void crash(const char *format, const char *condition, const char *file, usize line);
}
#define ASSERT(condition) ((condition) ? (void)0 : ::Std::crash("ASSERT(%condition)\n%file:%line\n", #condition, __FILE__, __LINE__))
#define VERIFY(condition) ((condition) ? (void)0 : ::Std::crash("VERIFY(%condition)\n%file:%line\n", #condition, __FILE__, __LINE__))
#define ASSERT_NOT_REACHED() ::Std::crash("ASSERT_NOT_REACHED():\n%file:%line\n", "", __FILE__, __LINE__)
#define VERIFY_NOT_REACHED() ::Std::crash("VERIFY_NOT_REACHED():\n%file:%line\n", "", __FILE__, __LINE__)
#define FIXME() ::Std::crash("FIXME()\n%file:%line\n", "", __FILE__, __LINE__)
#define FIXME_ASSERT(condition) ((condition) ? (void)0 : ::Std::crash("FIXME(%condition)\n%file:%line\n", #condition, __FILE__, __LINE__))
| 24.047244 | 138 | 0.67649 | [
"object"
] |
c7cf82017dbf14d05d3edf5d989790530059eba6 | 2,979 | cpp | C++ | Classes/MoonScene.cpp | elimu-ai/egma-nyas-space-quest-qd | f92f1d2a893ac52909a986f3ec9fc7c9d409c738 | [
"MIT"
] | null | null | null | Classes/MoonScene.cpp | elimu-ai/egma-nyas-space-quest-qd | f92f1d2a893ac52909a986f3ec9fc7c9d409c738 | [
"MIT"
] | 7 | 2017-06-09T10:50:50.000Z | 2017-06-29T12:15:49.000Z | Classes/MoonScene.cpp | elimu-ai/egma-nyas-space-quest-qd | f92f1d2a893ac52909a986f3ec9fc7c9d409c738 | [
"MIT"
] | 2 | 2017-05-28T22:04:45.000Z | 2017-06-28T14:44:14.000Z | //
// MoonScene.cpp
// akua
//
// Created by German Torres on 8/3/15.
// Moon Map class
//
#include "MoonScene.h"
using namespace CocosDenshion;
Scene* Moon::createScene()
{
auto scene = Scene::create();
auto layer = Moon::create();
layer->loadMap();
scene->addChild(layer);
return scene;
}
bool Moon::init()
{
if (!GameMap::init())
return false;
auto cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("moon.plist");
return true;
}
void Moon::loadMap()
{
setupAudio();
setupBackGround();
setupParallaxImages();
setupTilemap("moonLevel.tmx");
setupMeteorites();
GameMap::loadMap();
}
void Moon::setupAudio()
{
auto audio = SimpleAudioEngine::getInstance();
audio->stopBackgroundMusic();
audio->playBackgroundMusic("sfx/moonMusic.mp3", true);
}
void Moon::setupBackGround()
{
auto bG = Sprite::createWithSpriteFrameName("bg.png");
bG->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(bG, -10);
auto earthBG = Sprite::createWithSpriteFrameName("earth.png");
earthBG->setPosition(Vec2(visibleSize.width/2, visibleSize.height - 450));
this->addChild(earthBG, -9);
auto starsFX = Sprite::createWithSpriteFrameName("stars.jpg");
starsFX->setAnchorPoint(Vec2::ZERO);
starsFX->setBlendFunc(BlendFunc::ADDITIVE);
addChild(starsFX, -10);
auto lander = Sprite::createWithSpriteFrameName("lunarLander.png");
lander->setAnchorPoint(Vec2(0.5, 0));
lander->setScale(0.8f);
lander->setPosition(2500, 10);
lander->setTag(66);
parallaxNodeBack->addChild(lander,1);
}
void Moon::setupParallaxImages()
{
for (int i = 1; i <= 3; ++i)
{
std::string name = "p" + std::to_string(i) + ".png";
auto sprite = Sprite::createWithSpriteFrameName(name);
sprite->setAnchorPoint(Vec2::ZERO);
sprite->setPositionX((i - 1)*sprite->getContentSize().width);
parallaxNodeBack->addChild(sprite);
}
for (int i = 3; i <= 4; ++i)
{
std::string name = "montana" + std::to_string(i) + ".png";
auto mountainSprite = Sprite::createWithSpriteFrameName(name);
mountainSprite->setAnchorPoint(Vec2(0, 0));
mountainSprite->setPositionX(RandomHelper::random_int(-50, (int)visibleSize.width));
if (i >= 3)//lol
{
parallaxNodeFront->addChild(mountainSprite);
}
else
{
//parallaxNodeBack->addChild(mountainSprite);
}
}
}
void Moon::setupMeteorites()
{
auto meteors = tiledMap->getObjectGroup("meteors")->getObjects();
for (auto meteor : meteors)
{
auto meteorMap = meteor.asValueMap();
int x = meteorMap["x"].asInt();
int y = meteorMap["y"].asInt();
auto object = Meteor::create(Vec2(x, y));
meteorVector.pushBack(object);
gameplayNode->addChild(object);
}
}
void Moon::update(float dt)
{
//meteor
for (Meteor * meteor : meteorVector)
{
meteor->update(player->getPosition(), dt);
if (player->checkIntersect(meteor))
{
//meteor->regen(player->getPositionX());
this->hurtPlayer();
}
}
GameMap::update(dt);
}
| 23.456693 | 86 | 0.681772 | [
"object"
] |
c7d7ca4cfa35321e0ce58a2fa313df952ee6b580 | 13,094 | cpp | C++ | darkness-engine/include/shaders/core/outline/Outline.ps.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 6 | 2019-10-17T11:31:55.000Z | 2022-02-11T08:51:20.000Z | darkness-engine/include/shaders/core/outline/Outline.ps.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-08-11T09:01:29.000Z | 2020-08-11T09:01:29.000Z | darkness-engine/include/shaders/core/outline/Outline.ps.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-06-02T15:48:20.000Z | 2020-06-02T15:48:20.000Z | #include "Outline.ps.h"
#include "engine/graphics/ShaderStorage.h"
#include "engine/graphics/Sampler.h"
#include "tools/ByteRange.h"
#include "tools/Debug.h"
#include <memory>
namespace engine
{
namespace shaders
{
#pragma warning( push )
#pragma warning( disable : 4702 )
std::shared_ptr<const ShaderBinary> OutlinePS::load(const Device& device, ShaderStorage& storage) const
{
return storage.loadShader(device, "C:/work/darkness/darkness-engine/data/shaders/vulkan/core/outline/Outline.ps.spv", "C:/work/darkness/darkness-engine/data/shaders/vulkan/core/outline/Outline.ps.support", -1, {});
ASSERT(false, "Could not load the permutation necessary. This is a bug.");
return {};
}
#pragma warning( pop )
OutlinePS::OutlinePS()
: m_constantRange{
ConstantRange{
tools::ByteRange(
reinterpret_cast<const uint8_t*>(static_cast<const ConstData*>(this)),
reinterpret_cast<const uint8_t*>(static_cast<const ConstData*>(this)) + sizeof(ConstData)),
nullptr,
"ConstData"
}
}
, m_inputParameters
{
ShaderInputParameter{"position", "SV_Position0", "float4"}
,
ShaderInputParameter{"colora", "COLOR0", "float4"}
,
ShaderInputParameter{"edgeFlag", "PSIZE", "float"}
}
{}
#pragma warning( push )
#pragma warning( disable : 4100 )
OutlinePS::OutlinePS(const OutlinePS& cl)
: m_constantRange{
ConstantRange{
tools::ByteRange(
reinterpret_cast<const uint8_t*>(static_cast<const ConstData*>(this)),
reinterpret_cast<const uint8_t*>(static_cast<const ConstData*>(this)) + sizeof(ConstData)),
nullptr,
"ConstData"
}
}
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = cl.m_constantRange[i].buffer;
}
depth = cl.depth;
depth_sampler = cl.depth_sampler;
}
#pragma warning( pop )
#pragma warning( push )
#pragma warning( disable : 4100 )
OutlinePS::OutlinePS(OutlinePS&& cl)
: m_constantRange{
ConstantRange{
tools::ByteRange(
reinterpret_cast<const uint8_t*>(static_cast<const ConstData*>(this)),
reinterpret_cast<const uint8_t*>(static_cast<const ConstData*>(this)) + sizeof(ConstData)),
nullptr,
"ConstData"
}
}
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = std::move(cl.m_constantRange[i].buffer);
}
depth = std::move(cl.depth);
depth_sampler = std::move(cl.depth_sampler);
}
#pragma warning( pop )
#pragma warning( push )
#pragma warning( disable : 4100 )
OutlinePS& OutlinePS::operator=(const OutlinePS& cl)
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = cl.m_constantRange[i].buffer;
}
depth = cl.depth;
depth_sampler = cl.depth_sampler;
return *this;
}
#pragma warning( pop )
#pragma warning( push )
#pragma warning( disable : 4100 )
OutlinePS& OutlinePS::operator=(OutlinePS&& cl)
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = std::move(cl.m_constantRange[i].buffer);
}
depth = std::move(cl.depth);
depth_sampler = std::move(cl.depth_sampler);
return *this;
}
#pragma warning( pop )
std::vector<std::string> OutlinePS::textureSrvNames() const
{
return {
"depth"
};
}
std::vector<std::string> OutlinePS::textureUavNames() const
{
return {
};
}
std::vector<std::string> OutlinePS::bufferSrvNames() const
{
return {
};
}
std::vector<std::string> OutlinePS::bufferUavNames() const
{
return {
};
}
std::vector<std::string> OutlinePS::samplerNames() const
{
return {
"depth_sampler"
};
}
std::vector<std::string> OutlinePS::srvNames() const
{
return {
"depth"
};
}
std::vector<std::string> OutlinePS::uavNames() const
{
return {
};
}
#pragma warning( push )
#pragma warning( disable : 4100 )
engine::ResourceDimension OutlinePS::textureDimension(const std::string& name) const
{
if("depth" == name) return engine::ResourceDimension::Texture2D;
return engine::ResourceDimension::Unknown;
}
#pragma warning( pop )
std::vector<TextureSRV> OutlinePS::texture_srvs() const
{
std::vector<TextureSRV> result;
result.emplace_back(depth);
return result;
}
std::vector<TextureUAV> OutlinePS::texture_uavs() const
{
std::vector<TextureUAV> result;
return result;
}
std::vector<BufferSRV> OutlinePS::buffer_srvs() const
{
std::vector<BufferSRV> result;
return result;
}
std::vector<BufferUAV> OutlinePS::buffer_uavs() const
{
std::vector<BufferUAV> result;
return result;
}
std::vector<TextureBindlessSRV> OutlinePS::bindless_texture_srvs() const
{
std::vector<TextureBindlessSRV> result;
return result;
}
std::vector<TextureBindlessUAV> OutlinePS::bindless_texture_uavs() const
{
std::vector<TextureBindlessUAV> result;
return result;
}
std::vector<BufferBindlessSRV> OutlinePS::bindless_buffer_srvs() const
{
std::vector<BufferBindlessSRV> result;
return result;
}
std::vector<BufferBindlessUAV> OutlinePS::bindless_buffer_uavs() const
{
std::vector<BufferBindlessUAV> result;
return result;
}
std::vector<Shader::ConstantRange>& OutlinePS::constants()
{
return m_constantRange;
}
std::vector<Sampler> OutlinePS::samplers() const
{
std::vector<Sampler> result;
result.emplace_back(depth_sampler);
return result;
}
const std::vector<ShaderInputParameter>& OutlinePS::inputParameters() const
{
return m_inputParameters;
}
// warning C4172: returning address of local variable or temporary
// this will never happen as the name will always match the correct resource
#pragma warning( push )
#pragma warning( disable : 4172 )
#pragma warning( disable : 4100 )
bool OutlinePS::hasTextureSrv(const std::string& name) const
{
if(name == std::string("depth")) return true;
return false;
}
bool OutlinePS::hasTextureUav(const std::string& name) const
{
return false;
}
bool OutlinePS::hasBufferSrv(const std::string& name) const
{
return false;
}
bool OutlinePS::hasBufferUav(const std::string& name) const
{
return false;
}
bool OutlinePS::hasBindlessTextureSrv(const std::string& name) const
{
return false;
}
bool OutlinePS::hasBindlessTextureUav(const std::string& name) const
{
return false;
}
bool OutlinePS::hasBindlessBufferSrv(const std::string& name) const
{
return false;
}
bool OutlinePS::hasBindlessBufferUav(const std::string& name) const
{
return false;
}
const TextureSRV& OutlinePS::textureSrv(const std::string& name) const
{
if(name == std::string("depth")) return depth;
ASSERT(false, "Tried to look for non-existing resource");
return TextureSRV();
}
const TextureUAV& OutlinePS::textureUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return TextureUAV();
}
const BufferSRV& OutlinePS::bufferSrv(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferSRV();
}
const BufferUAV& OutlinePS::bufferUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferUAV();
}
void OutlinePS::textureSrv(const std::string& name, TextureSRV& texture)
{
if(name == std::string("depth")) { depth = texture; return; }
ASSERT(false, "Tried to set non-existing resource");
}
void OutlinePS::textureUav(const std::string& name, TextureUAV& texture)
{
ASSERT(false, "Tried to set non-existing resource");
}
void OutlinePS::bufferSrv(const std::string& name, BufferSRV& buffer)
{
ASSERT(false, "Tried to set non-existing resource");
}
void OutlinePS::bufferUav(const std::string& name, BufferUAV& buffer)
{
ASSERT(false, "Tried to set non-existing resource");
}
const Sampler& OutlinePS::sampler(const std::string& name) const
{
if(name == std::string("depth_sampler")) return depth_sampler;
ASSERT(false, "Tried to look for non-existing resource");
return Sampler();
}
const TextureBindlessSRV& OutlinePS::bindlessTextureSrv(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return TextureBindlessSRV();
}
const TextureBindlessUAV& OutlinePS::bindlessTextureUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return TextureBindlessUAV();
}
const BufferBindlessSRV& OutlinePS::bindlessBufferSrv(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferBindlessSRV();
}
const BufferBindlessUAV& OutlinePS::bindlessBufferUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferBindlessUAV();
}
#pragma warning( pop )
uint32_t OutlinePS::descriptorCount() const
{
return 2;
}
}
} | 24.158672 | 226 | 0.470903 | [
"vector"
] |
93a0858d10abb0bd856961778fc0cb84965c0f60 | 8,961 | cc | C++ | src/test/unit-test/test_limitdir.cc | yutannihilation/mdbm | 2899ae42fddfb0cb6d12a046700d304ef6e6dd01 | [
"BSD-3-Clause"
] | 286 | 2015-01-02T01:21:44.000Z | 2022-03-28T09:59:33.000Z | src/test/unit-test/test_limitdir.cc | yutannihilation/mdbm | 2899ae42fddfb0cb6d12a046700d304ef6e6dd01 | [
"BSD-3-Clause"
] | 55 | 2015-01-16T20:27:04.000Z | 2021-02-16T20:03:29.000Z | src/test/unit-test/test_limitdir.cc | yutannihilation/mdbm | 2899ae42fddfb0cb6d12a046700d304ef6e6dd01 | [
"BSD-3-Clause"
] | 69 | 2015-01-06T10:47:28.000Z | 2022-03-10T10:58:46.000Z | /* Copyright 2013 Yahoo! Inc. */
/* See LICENSE in the root of the distribution for licensing details. */
// Unit Tests for mdbm_limit_dir_size
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cppunit/TestAssert.h>
#include <cppunit/TestCase.h>
#include <cppunit/TestFixture.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include "mdbm.h"
#include "TestBase.hh"
class LimitDirSizeTestBase : public CppUnit::TestFixture, public TestBase
{
public:
LimitDirSizeTestBase(int vFlag, const string& vString) : versionFlag(vFlag), versionString(vString) { SetSuiteName("Limit Directory Size Test Suite: "); }
void setUp();
void tearDown();
// unit tests in this suite
//
void ValidDirSizes(); // TC J-2
void InvalidDirSizes(); // TC J-3
void LimPagesSetDirSmaller(); // TC J-4
void LimPagesSetDirBigger(); // TC J-5
void LimPagesSetDirSame(); // TC J-6
protected:
void limitDirSize(int numPages, int expectedRetCode, const char * tcprefix);
void limPagesSetDirSize(int limPages, int dirPages, int expectedRetCode, const char * tcprefix);
void verifyMaxDirWidth(MDBM *dbh, int dirPages, const string &prefix);
int versionFlag;
string versionString;
static int _setupCnt; // CPPUNIT creates instance per CPPUNIT_TEST
static int _MaxDirShift;
};
int LimitDirSizeTestBase::_setupCnt = 0;
// MDBM_DIRSHIFT_MAX is defined internally so cant use the macro here
int LimitDirSizeTestBase::_MaxDirShift = 24;
void LimitDirSizeTestBase::setUp()
{
if (_setupCnt++ == 0) {
cout << endl << "Limit Directory Size Test Suite Beginning..." << endl << flush;
}
}
void LimitDirSizeTestBase::tearDown() { }
void LimitDirSizeTestBase::verifyMaxDirWidth(MDBM *dbh, int dirPages, const string &prefix)
{
// get db info
mdbm_db_info_t dbinfo;
int ret = mdbm_get_db_info(dbh, &dbinfo);
if (ret == 0) {
//int calcMaxDirPages = (int)pow(2, dbinfo.db_max_dir_shift);
int calcMaxDirPages = 1 << dbinfo.db_max_dir_shift;
GetLogStream() << endl << prefix << "Database Info: Number pages=" << dbinfo.db_num_pages
<< " Maximum pages=" << dbinfo.db_max_pages
<< " Number Directory pages=" << dbinfo.db_num_dir_pages
<< " Directory width=" << dbinfo.db_dir_width
<< " Maximum Directory width=" << dbinfo.db_max_dir_shift
<< " Calculated Number of Directory pages=" << calcMaxDirPages << endl << endl << flush;
// dirPages <= 2 ^ dbinfo.db_max_dir_shift
stringstream dbmsg;
dbmsg << prefix
<< "Expected Number directory pages=" << dirPages
<< " to be >= 2 ^ MAX(" << dirPages
<< ") directory width. Actual MAX directory width 2 ^ " << dbinfo.db_max_dir_shift
<< " which=" << calcMaxDirPages << endl;
CPPUNIT_ASSERT_MESSAGE(dbmsg.str(), (dirPages >= calcMaxDirPages));
}
}
void LimitDirSizeTestBase::limitDirSize(int numPages, int expectedRetCode, const char * tcprefix)
{
stringstream premsg;
premsg << tcprefix << " page-count-limit=" << numPages << ": ";
string prefix = premsg.str();
TRACE_TEST_CASE(tcprefix);
prefix = SUITE_PREFIX() + prefix;
// Call mdbm_open; Create new DB using page size = p
MdbmHolder dbh = EnsureTmpMdbm(prefix, MDBM_O_RDWR | MDBM_O_CREAT | MDBM_O_TRUNC | versionFlag);
int ret = mdbm_limit_dir_size(dbh, numPages);
stringstream ssmsg;
ssmsg << prefix << "Expected return code=" << expectedRetCode
<< " but received=" << ret << endl;
CPPUNIT_ASSERT_MESSAGE(ssmsg.str(), (ret == expectedRetCode));
if ((expectedRetCode != -1) && (versionFlag & MDBM_CREATE_V3)) {
verifyMaxDirWidth(dbh, numPages, prefix);
}
}
// There is an internal maximum for directory size of MDBM_DIRSHIFT_MAX = 24.
// So a set of invalid numbers can be : n in 1, 7, MDBM_DIRSHIFT_MAX
// 1. Call mdbm_open; create new v3 DB using defaults
// 2. Call mdbm_limit_dir_size: n
// 3. Expected result: success
void LimitDirSizeTestBase::ValidDirSizes() // TC J-2
{
limitDirSize(1, 0, "TC J-2: ValidDirSizes: mdbm_limit_dir_size: ");
limitDirSize(3, 0, "TC J-2: ValidDirSizes: mdbm_limit_dir_size: ");
limitDirSize(4, 0, "TC J-2: ValidDirSizes: mdbm_limit_dir_size: ");
limitDirSize(7, 0, "TC J-2: ValidDirSizes: mdbm_limit_dir_size: ");
limitDirSize(16, 0, "TC J-2: ValidDirSizes: mdbm_limit_dir_size: ");
// MDBM_DIRSHIFT_MAX is defined internally so cant use the macro here
limitDirSize(_MaxDirShift, 0, "TC J-2: ValidDirSizes: mdbm_limit_dir_size: ");
}
// As an int, dir size could be negative. Also there is an internal maximum
// for directory size of MDBM_DIRSHIFT_MAX = 24. So a set of invalid numbers
// can be : n in -1, 0, 25
// 1. Call mdbm_open; create new v3 DB using defaults
// 2. Call mdbm_limit_dir_size: n
// 3. Expected result: FAIL and sets errno
void LimitDirSizeTestBase::InvalidDirSizes() // TC J-3
{
// BZ ticket 5285592
limitDirSize(-1, -1, "TC J-3: InvalidDirSizes: mdbm_limit_dir_size: ");
// MDBM_DIRSHIFT_MAX is defined internally so cant use the macro here
limitDirSize(1<<(_MaxDirShift + 1), -1, "TC J-3: InvalidDirSizes: mdbm_limit_dir_size: ");
limitDirSize(0, -1, "TC J-3: InvalidDirSizes: mdbm_limit_dir_size: ");
}
void LimitDirSizeTestBase::limPagesSetDirSize(int limPages, int dirPages, int expectedRetCode, const char * tcprefix)
{
stringstream premsg;
premsg << GetSuiteName() << tcprefix
<< " Number pages to limit directory size=" << dirPages
<< ": Number pages to limit database size=" << limPages << ": ";
string prefix = premsg.str();
TRACE_TEST_CASE(prefix);
prefix = SUITE_PREFIX() + prefix;
// Call mdbm_open; Create new DB using page size = p
MdbmHolder dbh = EnsureTmpMdbm(prefix, MDBM_O_RDWR | MDBM_O_CREAT | MDBM_O_TRUNC | versionFlag);
int ret = mdbm_limit_size_v3(dbh, limPages, 0, 0);
stringstream lsmsg;
lsmsg << prefix
<< "Expected mdbm_limit_size to succeed setting pages=" << limPages << endl;
CPPUNIT_ASSERT_MESSAGE(lsmsg.str(), (ret == 0));
ret = mdbm_limit_dir_size(dbh, dirPages);
stringstream dsmsg;
dsmsg << prefix
<< "Expected return code=" << expectedRetCode
<< " but received=" << ret << endl;
CPPUNIT_ASSERT_MESSAGE(dsmsg.str(), (ret == expectedRetCode));
// get db info
if (versionFlag & MDBM_CREATE_V3)
verifyMaxDirWidth(dbh, dirPages, prefix);
}
// Limit the DB size(number of pages) then set directory size to support less pages than the limit.
// 1. Call mdbm_open; create v3 DB using defaults
// 2. Call mdbm_limit_size; number of pages p = 16
// 3. Call mdbm_limit_dir_size; pages p = 8
// 4. Call get_db_info; get structure(mdbm_db_info_t) of internal data fields
// 5. Expected result: mdbm_db_info_t.db_max_dir_shift == 2
void LimitDirSizeTestBase::LimPagesSetDirSmaller() // TC J-4
{
limPagesSetDirSize(16, 8, 0, "TC J-4: LimPagesSetDirSmaller: mdbm_limit_dir_size: ");
}
// Limit the DB size(number of pages) then set directory size to support more pages than the limit.
// 1. Call mdbm_open; create v3 DB using defaults
// 2. Call mdbm_limit_size; number of pages p = 1
// 3. Call mdbm_limit_dir_size; dir size d = 24
// 4. Expected result: FAIL and errno set
void LimitDirSizeTestBase::LimPagesSetDirBigger() // TC J-5
{
limPagesSetDirSize(1, 24, 0, "TC J-5: LimPagesSetDirBigger: mdbm_limit_dir_size: ");
}
// Limit the DB size(number of pages) then set directory size to support same pages as the limit.
// 1. Call mdbm_open; create v3 DB using defaults
// 2. Call mdbm_limit_size; number of pages p = 8
// 3. Call mdbm_limit_dir_size; pages p = 8
// 4. Call get_db_info; get structure(mdbm_db_info_t) of internal data fields
// 5. Expected result: mdbm_db_info_t.db_max_dir_shift == 2
void LimitDirSizeTestBase::LimPagesSetDirSame() // TC J-6
{
limPagesSetDirSize(8, 8, 0, "TC J-6: LimPagesSetDirSame: mdbm_limit_dir_size: ");
}
class LimitDirSizeTestSuiteV3 : public LimitDirSizeTestBase
{
CPPUNIT_TEST_SUITE(LimitDirSizeTestSuiteV3);
CPPUNIT_TEST(ValidDirSizes);
CPPUNIT_TEST(InvalidDirSizes);
CPPUNIT_TEST(LimPagesSetDirSmaller);
CPPUNIT_TEST(LimPagesSetDirBigger);
CPPUNIT_TEST(LimPagesSetDirSame);
CPPUNIT_TEST_SUITE_END();
public:
LimitDirSizeTestSuiteV3() : LimitDirSizeTestBase(MDBM_CREATE_V3, "v3") {}
};
CPPUNIT_TEST_SUITE_REGISTRATION(LimitDirSizeTestSuiteV3);
| 37.182573 | 158 | 0.689544 | [
"vector"
] |
93a15cf82a34259f98de39474f09697103e2f74c | 1,791 | cpp | C++ | src/GameObjectCollection.cpp | jenningsm42/sfml-boilerplate | fb7ecafeaae2e598f6c5d5b2cc9ece00eaf1e4f9 | [
"MIT"
] | 1 | 2020-12-08T00:11:38.000Z | 2020-12-08T00:11:38.000Z | src/GameObjectCollection.cpp | jenningsm42/sfml-boilerplate | fb7ecafeaae2e598f6c5d5b2cc9ece00eaf1e4f9 | [
"MIT"
] | null | null | null | src/GameObjectCollection.cpp | jenningsm42/sfml-boilerplate | fb7ecafeaae2e598f6c5d5b2cc9ece00eaf1e4f9 | [
"MIT"
] | null | null | null | #include "GameObjectCollection.hpp"
std::weak_ptr<GameObject> GameObjectCollection::getObject(const std::string& name) const noexcept {
if (m_gameObjectMap.find(name) != m_gameObjectMap.end()) {
return m_gameObjectMap.at(name);
}
return std::weak_ptr<GameObject>();
}
void GameObjectCollection::addObject(const std::string& name, std::shared_ptr<GameObject> object, int zIndex) {
m_gameObjectMap.emplace(name, object);
m_gameObjectDrawOrder[zIndex].push_back(object);
}
GameObjectCollection::iterator GameObjectCollection::begin() const {
auto drawOrderIt = m_gameObjectDrawOrder.begin();
return iterator(drawOrderIt, m_gameObjectDrawOrder.end(), drawOrderIt->second.begin());
}
GameObjectCollection::iterator GameObjectCollection::end() const {
auto drawOrderIt = m_gameObjectDrawOrder.end();
return iterator(drawOrderIt, m_gameObjectDrawOrder.end(), drawOrderIt->second.end());
}
GameObjectCollection::iterator::iterator(
GameObjectDrawOrder::const_iterator drawOrderIt,
GameObjectDrawOrder::const_iterator drawOrderEnd,
GameObjectList::const_iterator objectIt)
: m_drawOrderIt(drawOrderIt), m_drawOrderEnd(drawOrderEnd), m_objectIt(objectIt) {
}
GameObjectCollection::iterator GameObjectCollection::iterator::operator++() {
if (++m_objectIt == m_drawOrderIt->second.end()) {
if (++m_drawOrderIt == m_drawOrderEnd) {
m_objectIt = m_drawOrderIt->second.end();
}
}
return *this;
}
bool GameObjectCollection::iterator::operator != (const GameObjectCollection::iterator& other) const {
return m_drawOrderIt != other.m_drawOrderIt || m_objectIt != other.m_objectIt;
}
const std::shared_ptr<GameObject>& GameObjectCollection::iterator::operator*() const {
return *m_objectIt;
}
| 36.55102 | 111 | 0.744277 | [
"object"
] |
93a65ac12d8833d581ca1ba44f9359a094015ba1 | 9,864 | cpp | C++ | cpp/min_path_to_Bucharest.cpp | fastbird/astar-algorithm-cpp | 7e24991518c89f21406ccd6776ef92ceccd6b603 | [
"MIT"
] | 336 | 2015-01-29T03:40:15.000Z | 2022-03-30T12:40:07.000Z | cpp/min_path_to_Bucharest.cpp | fastbird/astar-algorithm-cpp | 7e24991518c89f21406ccd6776ef92ceccd6b603 | [
"MIT"
] | 20 | 2015-01-29T17:29:58.000Z | 2021-04-25T20:04:23.000Z | cpp/min_path_to_Bucharest.cpp | fastbird/astar-algorithm-cpp | 7e24991518c89f21406ccd6776ef92ceccd6b603 | [
"MIT"
] | 165 | 2015-01-02T18:48:43.000Z | 2022-02-25T03:39:09.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This example code illustrate how to use STL A* Search implementation to find the minimum path between two
// cities given a map. The example is taken from the book AI: A Modern Approach, 3rd Ed., by Russel, where a map
// of Romania is given. The target node is Bucharest, and the user can specify the initial city from which the
// search algorithm will start looking for the minimum path to Bucharest.
//
// Usage: min_path_to_Bucharest <start city name>
// Example:
// min_path_to_Bucharest Arad
//
// Thanks to Rasoul Mojtahedzadeh for this contribution
// Mojtahedzadeh _atsign_ gmail com
//
// Please note that this exercise is academic in nature and that the distances between the cities may not be
// correct compared to the latitude and longnitude differences in real life. Thanks to parthi2929 for noticing
// this issue. In a real application you would use some kind of exact x,y position of each city in order to get
// accurate heuristics. In fact, that is part of the point of this example, in the book you will see Norvig
// mention that the algorithm does some backtracking because the heuristic is not accurate (yet still admissable).
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "stlastar.h"
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#define DEBUG_LISTS 0
#define DEBUG_LIST_LENGTHS_ONLY 0
using namespace std;
const int MAX_CITIES = 20;
enum ENUM_CITIES{Arad=0, Bucharest, Craiova, Drobeta, Eforie, Fagaras, Giurgiu, Hirsova, Iasi, Lugoj, Mehadia, Neamt, Oradea, Pitesti, RimnicuVilcea, Sibiu, Timisoara, Urziceni, Vaslui, Zerind};
vector<string> CityNames(MAX_CITIES);
float RomaniaMap[MAX_CITIES][MAX_CITIES];
class PathSearchNode
{
public:
ENUM_CITIES city;
PathSearchNode() { city = Arad; }
PathSearchNode( ENUM_CITIES in ) { city = in; }
float GoalDistanceEstimate( PathSearchNode &nodeGoal );
bool IsGoal( PathSearchNode &nodeGoal );
bool GetSuccessors( AStarSearch<PathSearchNode> *astarsearch, PathSearchNode *parent_node );
float GetCost( PathSearchNode &successor );
bool IsSameState( PathSearchNode &rhs );
void PrintNodeInfo();
};
// check if "this" node is the same as "rhs" node
bool PathSearchNode::IsSameState( PathSearchNode &rhs )
{
if(city == rhs.city) return(true);
return(false);
}
// Euclidean distance between "this" node city and Bucharest
// Note: Numbers are taken from the book
float PathSearchNode::GoalDistanceEstimate( PathSearchNode &nodeGoal )
{
// goal is always Bucharest!
switch(city)
{
case Arad: return 366; break;
case Bucharest: return 0; break;
case Craiova: return 160; break;
case Drobeta: return 242; break;
case Eforie: return 161; break;
case Fagaras: return 176; break;
case Giurgiu: return 77; break;
case Hirsova: return 151; break;
case Iasi: return 226; break;
case Lugoj: return 244; break;
case Mehadia: return 241; break;
case Neamt: return 234; break;
case Oradea: return 380; break;
case Pitesti: return 100; break;
case RimnicuVilcea: return 193; break;
case Sibiu: return 253; break;
case Timisoara: return 329; break;
case Urziceni: return 80; break;
case Vaslui: return 199; break;
case Zerind: return 374; break;
}
cerr << "ASSERT: city = " << CityNames[city] << endl;
return 0;
}
// check if "this" node is the goal node
bool PathSearchNode::IsGoal( PathSearchNode &nodeGoal )
{
if( city == Bucharest ) return(true);
return(false);
}
// generates the successor nodes of "this" node
bool PathSearchNode::GetSuccessors( AStarSearch<PathSearchNode> *astarsearch, PathSearchNode *parent_node )
{
PathSearchNode NewNode;
for(int c=0; c<MAX_CITIES; c++)
{
if(RomaniaMap[city][c] < 0) continue;
NewNode = PathSearchNode((ENUM_CITIES)c);
astarsearch->AddSuccessor( NewNode );
}
return true;
}
// the cost of going from "this" node to the "successor" node
float PathSearchNode::GetCost( PathSearchNode &successor )
{
return RomaniaMap[city][successor.city];
}
// prints out information about the node
void PathSearchNode::PrintNodeInfo()
{
cout << " " << CityNames[city] << "\n";
}
int main( int argc, char *argv[] )
{
// creating map of Romania
for(int i=0; i<MAX_CITIES; i++)
for(int j=0; j<MAX_CITIES; j++)
RomaniaMap[i][j]=-1.0;
RomaniaMap[Arad][Sibiu]=140;
RomaniaMap[Arad][Zerind]=75;
RomaniaMap[Arad][Timisoara]=118;
RomaniaMap[Bucharest][Giurgiu]=90;
RomaniaMap[Bucharest][Urziceni]=85;
RomaniaMap[Bucharest][Fagaras]=211;
RomaniaMap[Bucharest][Pitesti]=101;
RomaniaMap[Craiova][Drobeta]=120;
RomaniaMap[Craiova][RimnicuVilcea]=146;
RomaniaMap[Craiova][Pitesti]=138;
RomaniaMap[Drobeta][Craiova]=120;
RomaniaMap[Drobeta][Mehadia]=75;
RomaniaMap[Eforie][Hirsova]=75;
RomaniaMap[Fagaras][Bucharest]=211;
RomaniaMap[Fagaras][Sibiu]=99;
RomaniaMap[Giurgiu][Bucharest]=90;
RomaniaMap[Hirsova][Eforie]=86;
RomaniaMap[Hirsova][Urziceni]=98;
RomaniaMap[Iasi][Vaslui]=92;
RomaniaMap[Iasi][Neamt]=87;
RomaniaMap[Lugoj][Timisoara]=111;
RomaniaMap[Lugoj][Mehadia]=70;
RomaniaMap[Mehadia][Lugoj]=70;
RomaniaMap[Mehadia][Drobeta]=75;
RomaniaMap[Neamt][Iasi]=87;
RomaniaMap[Oradea][Zerind]=71;
RomaniaMap[Oradea][Sibiu]=151;
RomaniaMap[Pitesti][Bucharest]=101;
RomaniaMap[Pitesti][RimnicuVilcea]=97;
RomaniaMap[Pitesti][Craiova]=138;
RomaniaMap[RimnicuVilcea][Pitesti]=97;
RomaniaMap[RimnicuVilcea][Craiova]=146;
RomaniaMap[RimnicuVilcea][Sibiu]=80;
RomaniaMap[Sibiu][RimnicuVilcea]=80;
RomaniaMap[Sibiu][Fagaras]=99;
RomaniaMap[Sibiu][Oradea]=151;
RomaniaMap[Sibiu][Arad]=140;
RomaniaMap[Timisoara][Arad]=118;
RomaniaMap[Timisoara][Lugoj]=111;
RomaniaMap[Urziceni][Bucharest]=85;
RomaniaMap[Urziceni][Hirsova]=98;
RomaniaMap[Urziceni][Vaslui]=142;
RomaniaMap[Vaslui][Urziceni]=142;
RomaniaMap[Vaslui][Iasi]=92;
RomaniaMap[Zerind][Arad]=75;
RomaniaMap[Zerind][Oradea]=71;
// City names
CityNames[Arad].assign("Arad");
CityNames[Bucharest].assign("Bucharest");
CityNames[Craiova].assign("Craiova");
CityNames[Drobeta].assign("Drobeta");
CityNames[Eforie].assign("Eforie");
CityNames[Fagaras].assign("Fagaras");
CityNames[Giurgiu].assign("Giurgiu");
CityNames[Hirsova].assign("Hirsova");
CityNames[Iasi].assign("Iasi");
CityNames[Lugoj].assign("Lugoj");
CityNames[Mehadia].assign("Mehadia");
CityNames[Neamt].assign("Neamt");
CityNames[Oradea].assign("Oradea");
CityNames[Pitesti].assign("Pitesti");
CityNames[RimnicuVilcea].assign("RimnicuVilcea");
CityNames[Sibiu].assign("Sibiu");
CityNames[Timisoara].assign("Timisoara");
CityNames[Urziceni].assign("Urziceni");
CityNames[Vaslui].assign("Vaslui");
CityNames[Zerind].assign("Zerind");
ENUM_CITIES initCity = Arad;
if(argc == 2)
{
bool found = false;
for(size_t i=0; i<CityNames.size(); i++)
if(CityNames[i].compare(argv[1])==0)
{
initCity = (ENUM_CITIES)i;
found = true;
break;
}
if(not found)
{
cout << "There is no city named "<<argv[1]<<" in the map!\n";
return(1);
}
}
// An instance of A* search class
AStarSearch<PathSearchNode> astarsearch;
unsigned int SearchCount = 0;
const unsigned int NumSearches = 1;
while(SearchCount < NumSearches)
{
// Create a start state
PathSearchNode nodeStart;
nodeStart.city = initCity;
// Define the goal state, always Bucharest!
PathSearchNode nodeEnd;
nodeEnd.city = Bucharest;
// Set Start and goal states
astarsearch.SetStartAndGoalStates( nodeStart, nodeEnd );
unsigned int SearchState;
unsigned int SearchSteps = 0;
do
{
SearchState = astarsearch.SearchStep();
SearchSteps++;
#if DEBUG_LISTS
cout << "Steps:" << SearchSteps << "\n";
int len = 0;
cout << "Open:\n";
PathSearchNode *p = astarsearch.GetOpenListStart();
while( p )
{
len++;
#if !DEBUG_LIST_LENGTHS_ONLY
((PathSearchNode *)p)->PrintNodeInfo();
#endif
p = astarsearch.GetOpenListNext();
}
cout << "Open list has " << len << " nodes\n";
len = 0;
cout << "Closed:\n";
p = astarsearch.GetClosedListStart();
while( p )
{
len++;
#if !DEBUG_LIST_LENGTHS_ONLY
p->PrintNodeInfo();
#endif
p = astarsearch.GetClosedListNext();
}
cout << "Closed list has " << len << " nodes\n";
#endif
}
while( SearchState == AStarSearch<PathSearchNode>::SEARCH_STATE_SEARCHING );
if( SearchState == AStarSearch<PathSearchNode>::SEARCH_STATE_SUCCEEDED )
{
cout << "Search found the goal state\n";
PathSearchNode *node = astarsearch.GetSolutionStart();
cout << "Displaying solution\n";
int steps = 0;
node->PrintNodeInfo();
for( ;; )
{
node = astarsearch.GetSolutionNext();
if( !node ) break;
node->PrintNodeInfo();
steps ++;
};
cout << "Solution steps " << steps << endl;
// Once you're done with the solution you can free the nodes up
astarsearch.FreeSolutionNodes();
}
else if( SearchState == AStarSearch<PathSearchNode>::SEARCH_STATE_FAILED )
{
cout << "Search terminated. Did not find goal state\n";
}
// Display the number of loops the search went through
cout << "SearchSteps : " << SearchSteps << "\n";
SearchCount ++;
astarsearch.EnsureMemoryFreed();
}
return 0;
}
| 31.314286 | 195 | 0.658962 | [
"vector"
] |
93a69c2d6f008caf15b800f16ea194192012febe | 281 | cpp | C++ | engine/runtime/ecs/constructs/prefab.cpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 791 | 2016-11-04T14:13:41.000Z | 2022-03-20T20:47:31.000Z | engine/runtime/ecs/constructs/prefab.cpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 28 | 2016-12-01T05:59:30.000Z | 2021-03-20T09:49:26.000Z | engine/runtime/ecs/constructs/prefab.cpp | ValtoForks/EtherealEngine | ab769803dcd71a61c2805afd259959b62fcdc1ff | [
"BSD-2-Clause"
] | 151 | 2016-12-21T09:44:43.000Z | 2022-03-31T13:42:18.000Z | #include "prefab.h"
#include "utils.h"
runtime::entity prefab::instantiate()
{
std::vector<runtime::entity> out_data;
if(!data)
return {};
if(!ecs::utils::deserialize_data(*data, out_data))
return {};
if(out_data.empty())
return {};
else
return out_data.front();
}
| 15.611111 | 51 | 0.66548 | [
"vector"
] |
93b0c34a495311747f10d85259f0c3327f0cf278 | 166 | cpp | C++ | FMEGraphics/src/IKeyBoardController.cpp | FullMetalNicky/FullMetalEngine | 26fbdd14332f9ab158180efea176e7aaa47f570c | [
"MIT"
] | 12 | 2018-08-05T17:55:40.000Z | 2021-08-22T07:17:12.000Z | FMEGraphics/src/IKeyBoardController.cpp | FullMetalNicky/FullMetalEngine | 26fbdd14332f9ab158180efea176e7aaa47f570c | [
"MIT"
] | null | null | null | FMEGraphics/src/IKeyBoardController.cpp | FullMetalNicky/FullMetalEngine | 26fbdd14332f9ab158180efea176e7aaa47f570c | [
"MIT"
] | 1 | 2020-06-08T10:46:05.000Z | 2020-06-08T10:46:05.000Z | #include "IKeyBoardController.h"
using namespace FME::Graphics;
void IKeyBoardController::SetControlKeys(const std::vector<char>& keys)
{
m_keys = keys;
} | 18.444444 | 72 | 0.728916 | [
"vector"
] |
93bff6b0e75f2b71604143880c81d9fb0f6bbaee | 6,446 | cpp | C++ | tcob/src/game/Game.cpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | 2 | 2021-08-18T19:14:35.000Z | 2021-12-01T14:14:49.000Z | tcob/src/game/Game.cpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | null | null | null | tcob/src/game/Game.cpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Tobias Bohnen
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include <tcob/game/Game.hpp>
#include <SDL.h>
#include <numeric>
#include <tcob/gfx/Canvas.hpp>
namespace tcob {
using hrc = std::chrono::high_resolution_clock;
constexpr MilliSeconds FIXED_TIME_STEPS { 1000.f / 50.f };
constexpr u8 MAX_FRAME_SKIP = 10;
Game::Game(const std::string& path, const std::string& name, bool windowless)
: _name { name }
{
SDL_SetMainReady();
SDL_Init(SDL_INIT_EVERYTHING);
FileSystem::init(path.c_str(), name);
TCOB_LOG("starting", LogLevel::Info);
if (!_config.load()) {
on_config_defaults();
}
_audio = std::make_unique<audio::AudioSystem>();
_input = std::make_unique<Input>();
if (!windowless)
create_context();
_assets = std::make_unique<AssetLibrary>();
Quit.connect(&Game::on_quit, this);
}
Game::~Game()
{
_assets = nullptr;
_window = nullptr;
_input = nullptr;
_audio = nullptr;
_config.save();
TCOB_LOG("exiting", LogLevel::Info);
FileSystem::done();
SDL_Quit();
}
void Game::start()
{
loop();
}
void Game::push_scene(std::shared_ptr<Scene> scene)
{
auto command { [this, scene]() {
if (!_scenes.empty()) {
_scenes.top()->sleep();
}
if (scene) {
scene->start();
_scenes.push(scene);
}
} };
_commandQueue.push(std::move(command));
}
void Game::pop_current_scene()
{
if (!_scenes.empty()) {
_commandQueue.push({ [this]() { pop_scene(); } });
}
}
void Game::pop_scene()
{
_scenes.top()->finish();
_scenes.pop();
if (!_scenes.empty()) {
_scenes.top()->wake_up();
}
}
auto Game::get_config() -> Config&
{
return _config;
}
auto Game::get_input() const -> Input&
{
return *_input;
}
auto Game::get_assets() const -> AssetLibrary&
{
return *_assets;
}
auto Game::get_stats() -> FPSCounter&
{
return _fps;
}
auto Game::get_window() const -> gfx::Window&
{
return *_window;
}
void Game::set_active_cursor(AssetPtr<gfx::Cursor> cursor)
{
SDL_ShowCursor(cursor ? SDL_DISABLE : SDL_ENABLE);
_cursor = std::move(cursor);
}
void Game::on_config_defaults()
{
TCOB_LOG("Config: setting default values", LogLevel::Warning);
// set defaults
_config["Video"]["Fullscreen"] = false;
_config["Video"]["Resolution"] = SizeU { 800, 600 };
_config["Video"]["VSync"] = false;
}
void Game::loop()
{
MilliSeconds now { hrc::now().time_since_epoch() };
MilliSeconds nextTick { now };
MilliSeconds last { now };
const MilliSeconds fixedTimeSteps { FIXED_TIME_STEPS };
PreMainLoop.emit();
do {
process_events();
while (!_commandQueue.empty()) {
_commandQueue.front()();
_commandQueue.pop();
}
_assets->update();
// fixed update
u8 loops { 0 };
while (hrc::now().time_since_epoch() > nextTick && loops < MAX_FRAME_SKIP) {
FixedUpdate.emit(FIXED_TIME_STEPS);
nextTick += fixedTimeSteps;
loops++;
}
// update
now = hrc::now().time_since_epoch();
const MilliSeconds delta { now - last };
last = now;
PreUpdate.emit(delta);
Update.emit(delta);
PostUpdate.emit(delta);
// render
if (_window) {
_defaultTarget.set_size(_window->get_size());
_window->clear({ 0x33, 0x33, 0x33, 0 });
Draw.emit(*_window);
_window->draw(_defaultTarget);
if (_cursor) {
_cursor->draw(_defaultTarget);
_cursor->set_active_mode("default"); // set cursor to default mode if available
}
_window->swap();
}
_fps.run(delta);
} while (!_scenes.empty());
PostMainLoop.emit();
}
void Game::on_quit()
{
while (!_scenes.empty()) {
pop_scene();
}
}
void Game::process_events()
{
SDL_Event ev;
while (SDL_PollEvent(&ev)) {
switch (ev.type) {
case SDL_QUIT:
Quit.emit();
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
case SDL_TEXTINPUT:
case SDL_TEXTEDITING:
case SDL_MOUSEMOTION:
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEWHEEL:
case SDL_JOYAXISMOTION:
case SDL_JOYHATMOTION:
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
case SDL_JOYDEVICEADDED:
case SDL_JOYDEVICEREMOVED:
case SDL_CONTROLLERAXISMOTION:
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
_input->process_events(&ev);
break;
case SDL_WINDOWEVENT:
_window->process_events(&ev);
break;
default:
break;
}
}
}
void Game::create_context()
{
const bool fullscreen { _config["Video"]["FullScreen"] };
const SizeU size { _config["Video"]["Resolution"] };
const bool vsync { _config["Video"]["VSync"] };
_window = std::make_unique<gfx::Window>(size);
_window->set_fullscreen(fullscreen);
_window->set_vsync(vsync);
_window->set_title(_name);
}
////////////////////////////////////////////////////////////
void FPSCounter::run(MilliSeconds delta)
{
u64 count { 0 };
const u64 frametimesindex { _frameCount % FRAME_VALUES };
_frameTimes[frametimesindex] = static_cast<f32>(delta.count());
++_frameCount;
if (_frameCount < FRAME_VALUES) {
count = _frameCount;
} else {
count = FRAME_VALUES;
}
_averageFrames = std::accumulate(_frameTimes.begin(), _frameTimes.end(), 0.f);
_averageFrames /= count;
_averageFrames = 1000.f / _averageFrames;
if (count == FRAME_VALUES) {
_bestFrames = std::max(_bestFrames, _averageFrames);
_worstFrames = std::min(_worstFrames, _averageFrames);
}
}
void FPSCounter::reset()
{
_averageFrames = 0;
_worstFrames = std::numeric_limits<f32>::max();
_bestFrames = 0;
_frameTimes.fill(0);
_frameCount = 0;
}
auto FPSCounter::get_average_fps() const -> f32
{
return _averageFrames;
}
auto FPSCounter::get_best_fps() const -> f32
{
return _bestFrames;
}
auto FPSCounter::get_worst_fps() const -> f32
{
return _worstFrames;
}
} | 21.344371 | 95 | 0.59153 | [
"render"
] |
93d8fcad485ce360c632a9e54cc8cee9e04008eb | 7,620 | cpp | C++ | circe/vk/io/swapchain.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | 1 | 2021-09-17T18:12:47.000Z | 2021-09-17T18:12:47.000Z | circe/vk/io/swapchain.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | null | null | null | circe/vk/io/swapchain.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | 2 | 2021-09-17T18:13:02.000Z | 2021-09-17T18:16:21.000Z | /// Copyright (c) 2019, FilipeCN.
///
/// The MIT License (MIT)
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to
/// deal in the Software without restriction, including without limitation the
/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
/// sell copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
/// IN THE SOFTWARE.
///
///\file vk_swap_chain.cpp
///\author FilipeCN (filipedecn@gmail.com)
///\date 2019-10-30
///
///\brief
#include <circe/vk/io/swapchain.h>
#include <circe/vk/utils/vk_debug.h>
namespace circe::vk {
SwapChain::SwapChain() {
info_.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
info_.pNext = nullptr;
info_.flags = 0;
info_.imageArrayLayers = 1;
info_.queueFamilyIndexCount = 0;
info_.pQueueFamilyIndices = nullptr;
info_.clipped = VK_TRUE;
info_.oldSwapchain = VK_NULL_HANDLE;
info_.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
}
SwapChain::SwapChain(const LogicalDevice::Ref &logical_device,
const SurfaceKHR &presentation_surface, u32 image_count,
VkSurfaceFormatKHR surface_format, VkExtent2D image_size,
VkImageUsageFlags image_usage,
VkSurfaceTransformFlagBitsKHR surface_transform,
VkPresentModeKHR present_mode) : SwapChain() {
init(logical_device, presentation_surface, image_count, surface_format, image_size,
image_usage, surface_transform, present_mode);
}
SwapChain::SwapChain(SwapChain &&other) noexcept {
info_ = other.info_;
logical_device_ = other.logical_device_;
vk_swap_chain_ = other.vk_swap_chain_;
images_ = std::move(other.images_);
other.vk_swap_chain_ = VK_NULL_HANDLE;
}
SwapChain::~SwapChain() { destroy(); }
SwapChain &SwapChain::operator=(SwapChain &&other) noexcept {
destroy();
info_ = other.info_;
logical_device_ = other.logical_device_;
vk_swap_chain_ = other.vk_swap_chain_;
images_ = std::move(other.images_);
other.vk_swap_chain_ = VK_NULL_HANDLE;
return *this;
}
bool SwapChain::init(const LogicalDevice::Ref &logical_device,
const SurfaceKHR &presentation_surface,
u32 image_count,
VkSurfaceFormatKHR surface_format,
VkExtent2D image_size,
VkImageUsageFlags image_usage,
VkSurfaceTransformFlagBitsKHR surface_transform,
VkPresentModeKHR present_mode) {
logical_device_ = logical_device;
set(presentation_surface, image_count, surface_format, image_size,
image_usage, surface_transform, present_mode);
return init();
}
bool SwapChain::init() {
destroy();
HERMES_VALIDATE_EXP_WITH_WARNING(logical_device_.good(), "using bad device.")
R_CHECK_VULKAN(vkCreateSwapchainKHR(logical_device_.handle(), &info_,
nullptr, &vk_swap_chain_), false)
std::vector<VkImage> images;
u32 images_count = 0;
R_CHECK_VULKAN(vkGetSwapchainImagesKHR(logical_device_.handle(), vk_swap_chain_,
&images_count, nullptr), false)
HERMES_LOG_AND_RETURN_VALUE_IF_NOT(0 != images_count, false,
"Could not enumerate swapchain images.")
images.resize(images_count);
R_CHECK_VULKAN(vkGetSwapchainImagesKHR(logical_device_.handle(), vk_swap_chain_,
&images_count, images.data()), false)
images_.clear();
for (auto &image : images)
images_.emplace_back(logical_device_, image);
return true;
}
void SwapChain::destroy() {
if (vk_swap_chain_ != VK_NULL_HANDLE) {
HERMES_CHECK_EXP_WITH_LOG(logical_device_.waitIdle(), "Failed to wait logical device idle")
vkDestroySwapchainKHR(logical_device_.handle(), vk_swap_chain_, nullptr);
vk_swap_chain_ = VK_NULL_HANDLE;
}
}
VkSwapchainKHR SwapChain::handle() const {
HERMES_VALIDATE_EXP_WITH_WARNING(good(), "Accessing bad swap chain handle.")
return vk_swap_chain_;
}
void SwapChain::set(const SurfaceKHR &presentation_surface, u32 image_count,
VkSurfaceFormatKHR surface_format, VkExtent2D image_size,
VkImageUsageFlags image_usage,
VkSurfaceTransformFlagBitsKHR surface_transform,
VkPresentModeKHR present_mode) {
info_.surface = presentation_surface.handle();
info_.minImageCount = image_count;
info_.imageFormat = surface_format.format;
info_.imageColorSpace = surface_format.colorSpace;
info_.imageExtent = image_size;
info_.imageUsage = image_usage;
info_.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
info_.preTransform = surface_transform;
info_.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
info_.presentMode = present_mode;
}
bool SwapChain::good() const {
return logical_device_.good() && vk_swap_chain_;
}
VkResult SwapChain::nextImage(VkSemaphore semaphore, VkFence fence,
u32 &image_index) const {
HERMES_VALIDATE_EXP_WITH_WARNING(logical_device_.good(), "using bad device.")
HERMES_VALIDATE_EXP_WITH_WARNING(semaphore, "using bad semaphore.")
return vkAcquireNextImageKHR(logical_device_.handle(), vk_swap_chain_,
2000000000, semaphore, fence, &image_index);
}
const std::vector<Image::Ref> &SwapChain::images() {
return images_;
}
VkExtent2D SwapChain::imageSize() const { return info_.imageExtent; }
VkSurfaceFormatKHR SwapChain::surfaceFormat() const { return {info_.imageFormat, info_.imageColorSpace}; }
void SwapChain::setPresentationSurface(const SurfaceKHR &surface) {
info_.surface = surface.handle();
}
void SwapChain::setSurfaceFormat(VkSurfaceFormatKHR surface_format) {
info_.imageColorSpace = surface_format.colorSpace;
info_.imageFormat = surface_format.format;
}
void SwapChain::setImageSize(VkExtent2D image_extent) {
info_.imageExtent = image_extent;
}
void SwapChain::setImageUsage(VkImageUsageFlags image_usage) {
info_.imageUsage = image_usage;
}
void SwapChain::setSurfaceTransform(VkSurfaceTransformFlagBitsKHR surface_transform) {
info_.preTransform = surface_transform;
}
void SwapChain::setPresentMode(VkPresentModeKHR present_mode) {
info_.presentMode = present_mode;
}
void SwapChain::setNumberOfImages(u32 image_count) {
info_.minImageCount = image_count;
}
void SwapChain::setLogicalDevice(const LogicalDevice::Ref &logical_device) {
logical_device_ = logical_device;
}
VkSurfaceKHR SwapChain::surface() const {
return info_.surface;
}
VkFormat SwapChain::imageFormat() const {
return info_.imageFormat;
}
} // namespace circe | 38.291457 | 107 | 0.706693 | [
"vector"
] |
93dcb71b312792513e60e4d44d09555980575f8f | 950 | hpp | C++ | src/include/template.hpp | AbstractXan/mdToWebsite | ae1df41ce3884ac226b60a11445539cfcdcb744a | [
"MIT"
] | null | null | null | src/include/template.hpp | AbstractXan/mdToWebsite | ae1df41ce3884ac226b60a11445539cfcdcb744a | [
"MIT"
] | null | null | null | src/include/template.hpp | AbstractXan/mdToWebsite | ae1df41ce3884ac226b60a11445539cfcdcb744a | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <unordered_map>
struct Template
{
std::string name;
std::vector<std::string> args;
std::vector<std::string> textContentList;
std::vector<std::string> argContentList;
};
typedef std::unordered_map<std::string, Template *> TemplateMap;
class TemplateManager
{
private:
TemplateMap *tmap;
void provisionTemplates(std::string templateFile);
public:
TemplateManager(std::string templateFile);
// Read string from md like: {{template}}
std::string renderTemplateFromText(std::string mdTemplateFormat);
Template *getTemplate(std::string templateName);
};
void parseAndSaveTemplateContent(Template *temp, std::string templateContent, bool hasMultipleLines);
std::unordered_map<std::string, std::string> *generateTemplateArgValueMap(std::vector<std::string> args);
std::string renderTemplate(Template *template_ptr, std::unordered_map<std::string, std::string> *argValMap);
| 27.941176 | 108 | 0.766316 | [
"vector"
] |
93deb485fefaca2f677ac2f1f027a3275edd3038 | 778 | cpp | C++ | 61.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 61.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 61.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <climits>
#include <stack>
#include <sstream>
#include <numeric>
#include <unordered_map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL)
return head;
int n = 1;
ListNode* tail = head;
while (tail -> next != NULL) {
tail = tail -> next;
++ n;
}
k = k % n;
ListNode* p = head;
for (int i = 1; i < n - k; ++ i)
p = p -> next;
tail -> next = head;
head = p -> next;
p -> next = NULL;
return head;
}
};
int main() {
return 0;
} | 13.413793 | 50 | 0.579692 | [
"vector"
] |
93e861eae38bb91111c67e4cc4a6717b0cd4709f | 955 | cpp | C++ | 4. Алгоритмы на графах/72. Алгоритм Дейкстры #3831/[OK]220289.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 19 | 2018-05-19T16:37:14.000Z | 2022-03-23T20:13:43.000Z | 4. Алгоритмы на графах/72. Алгоритм Дейкстры #3831/[OK]220289.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 6 | 2020-05-07T21:06:48.000Z | 2020-06-05T17:52:57.000Z | 4. Алгоритмы на графах/72. Алгоритм Дейкстры #3831/[OK]220289.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 31 | 2019-03-01T21:41:38.000Z | 2022-03-27T17:56:39.000Z | #include <iostream>
#include <fstream>
#include <vector>
#include <set>
using namespace std;
vector < pair<int, int> > g[200000];
long long d[200000];
#define INF INT64_MAX
int main()
{
ifstream fin("input.txt");
ofstream fout("output.txt");
int n, m;
fin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w;
fin >> u >> v >> w;
g[u - 1].push_back(make_pair(v - 1, w));
g[v - 1].push_back(make_pair(u - 1, w));
}
int s = 0;
for (int i = 0; i < n; i++) {
d[i] = INF;
}
d[s] = 0;
set < pair<long long, long long> > q;
q.insert(make_pair(d[s], s));
while (!q.empty()) {
int v = q.begin()->second;
q.erase(q.begin());
for (int j = 0; j < g[v].size(); ++j) {
int to = g[v][j].first,
len = g[v][j].second;
if (d[v] + len < d[to]) {
q.erase(make_pair(d[to], to));
d[to] = d[v] + len;
q.insert(make_pair(d[to], to));
}
}
}
fout << d[n - 1];
return 0;
}
| 20.319149 | 43 | 0.495288 | [
"vector"
] |
93efa992d0795bc8c417f010b0960375b16f0e40 | 1,655 | cpp | C++ | ACC/acc3p3.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | ACC/acc3p3.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | ACC/acc3p3.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define gc getchar_unlocked()
#define pc(x) putchar_unlocked(x)
template<typename T> void scan(T &x){x = 0;register bool _=0;register T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;}
template<typename T> void print(T n){register bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=n%10+48;n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);pc(10);}
template<typename First, typename ... Ints>
void scan(First &arg, Ints&... rest){scan(arg);scan(rest...);}
using namespace std;
const int MM = 1e5;
int N, st[MM];
vector<int> nx[26][MM];
string str, ans;
int find(int i, char c){
c -= 'a';
while(!nx[c][i].empty() and nx[c][i].back() < st[i])
nx[c][i].pop_back();
return nx[c][i].empty() ? -1: nx[c][i].back();
}
int main(){
cin.sync_with_stdio(0);
cin.tie(0);
cin >> N;
for(int i = 0; i < N; i++){
cin >> str;
for(int j = str.size()-1; j >= 0; j--)
nx[str[j]-'a'][i].push_back(j);
}
for(char c = 'z'; c >= 'a'; c--){
while(1){
for(int i = 0; i < N; i++){
if(find(i, c) == -1)
goto out;
}
for(int i = 0; i < N; i++){
int at = find(i, c);
st[i] = at+1;
}
ans += c;
}
out:;
}
if(ans.empty())
puts("-1");
else
cout << ans << '\n';
return 0;
} | 26.693548 | 193 | 0.43142 | [
"vector"
] |
93f79b27b13367307abe0add7b3288088eb9b213 | 3,872 | cpp | C++ | dev/Code/Sandbox/Plugins/CryDesigner/Core/SmoothingGroup.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/Sandbox/Plugins/CryDesigner/Core/SmoothingGroup.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/Sandbox/Plugins/CryDesigner/Core/SmoothingGroup.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "SmoothingGroup.h"
#include "Model.h"
#include "ModelDB.h"
#include "BrushHelper.h"
SmoothingGroup::SmoothingGroup(const std::vector<CD::PolygonPtr>& polygons)
: m_pStorage(new CD::Model)
{
Invalidate();
m_pStorage->AddRef();
SetPolygons(polygons);
}
SmoothingGroup::~SmoothingGroup()
{
m_pStorage->Release();
}
void SmoothingGroup::SetPolygons(const std::vector<CD::PolygonPtr>& polygons)
{
m_pStorage->Clear();
for (int i = 0, iPolygonCount(polygons.size()); i < iPolygonCount; ++i)
{
m_PolygonSet.insert(polygons[i]);
m_pStorage->AddPolygon(polygons[i], CD::eOpType_Add);
}
Invalidate();
}
void SmoothingGroup::AddPolygon(CD::PolygonPtr pPolygon)
{
if (m_PolygonSet.find(pPolygon) != m_PolygonSet.end())
{
return;
}
m_PolygonSet.insert(pPolygon);
m_pStorage->AddPolygon(pPolygon, CD::eOpType_Add);
Invalidate();
}
bool SmoothingGroup::HasPolygon(CD::PolygonPtr pPolygon) const
{
return m_PolygonSet.find(pPolygon) != m_PolygonSet.end();
}
bool SmoothingGroup::CalculateNormal(const BrushVec3& vPos, BrushVec3& vOutNormal) const
{
BrushVec3 vNormal(0, 0, 0);
CD::ModelDB::QueryResult qResult;
if (m_pStorage->GetDB()->QueryAsVertex(vPos, qResult) && qResult.size() == 1 && !qResult[0].m_MarkList.empty())
{
for (int i = 0, iCount(qResult[0].m_MarkList.size()); i < iCount; ++i)
{
vNormal += qResult[0].m_MarkList[i].m_pPolygon->GetPlane().Normal();
}
vOutNormal = vNormal.GetNormalized();
return true;
}
return false;
}
int SmoothingGroup::GetPolygonCount() const
{
return m_pStorage->GetPolygonCount();
}
CD::PolygonPtr SmoothingGroup::GetPolygon(int nIndex) const
{
return m_pStorage->GetPolygon(nIndex);
}
std::vector<CD::PolygonPtr> SmoothingGroup::GetAll() const
{
std::vector<CD::PolygonPtr> polygons;
m_pStorage->GetPolygonList(polygons);
return polygons;
}
void SmoothingGroup::Updatemesh(bool bGenerateBackFaces)
{
m_pStorage->ResetDB(CD::eDBRF_Vertex);
m_FlexibleMesh.Clear();
for (int i = 0, iPolygonCount(GetPolygonCount()); i < iPolygonCount; ++i)
{
int nVertexOffset = m_FlexibleMesh.vertexList.size();
if (GetPolygon(i)->CheckFlags(CD::ePolyFlag_Hidden))
{
continue;
}
CD::CreateMeshFacesFromPolygon(GetPolygon(i), m_FlexibleMesh, bGenerateBackFaces);
for (int k = nVertexOffset, iVertexCount(m_FlexibleMesh.vertexList.size()); k < iVertexCount; ++k)
{
CalculateNormal(m_FlexibleMesh.vertexList[k].pos, m_FlexibleMesh.normalList[k]);
}
}
}
void SmoothingGroup::RemovePolygon(CD::PolygonPtr pPolygon)
{
m_PolygonSet.erase(pPolygon);
m_pStorage->RemovePolygon(pPolygon);
Invalidate();
}
const CD::FlexibleMesh& SmoothingGroup::GetFlexibleMesh(bool bGenerateBackFaces)
{
if (!bGenerateBackFaces && !m_bValidmesh[0] || bGenerateBackFaces && !m_bValidmesh[1])
{
if (bGenerateBackFaces)
{
m_bValidmesh[1] = true;
}
else
{
m_bValidmesh[0] = true;
}
Updatemesh(bGenerateBackFaces);
}
return m_FlexibleMesh;
} | 28.262774 | 115 | 0.675878 | [
"vector",
"model"
] |
9e04f6e16622067b6a279db83b3d24d852ff5afd | 58,763 | cpp | C++ | src/memory_implicit.cpp | WatorVapor/wator.dmnn | af33c1a2647175a5b19a0c7594b43ee53498e64d | [
"MIT"
] | null | null | null | src/memory_implicit.cpp | WatorVapor/wator.dmnn | af33c1a2647175a5b19a0c7594b43ee53498e64d | [
"MIT"
] | null | null | null | src/memory_implicit.cpp | WatorVapor/wator.dmnn | af33c1a2647175a5b19a0c7594b43ee53498e64d | [
"MIT"
] | null | null | null | /*
Copyright (c) 2015, Wator Vapor
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 wator 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 "wator.hpp"
using namespace Wator;
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace boost::property_tree;
#include <bitset>
/**
* Constructor
**/
ImplicitMemory::ImplicitMemory()
:searchIndex_(0)
{
}
/**
* Constructor
* @param [in] info layer parameter.
**/
ImplicitMemory::ImplicitMemory(const pt::ptree& info)
:serial_(info)
{
}
/**
* update
**/
void ImplicitMemory::update(int pinch,uint64_t index,int sparse,int w,int h)
{
#if 0
const map<uint64_t,bool> &shotThough = shotThough_3X3_;
if(w == 5 && h == 5) {
shotThough = shotThough_5X5_;
}
const auto itST = shotThough_3X3_.find(index);
if(itST == shotThough.end())
{
return;
}
if(false == itST->second)
{
return;
}
std::bitset<64> memBit(index);
if (memBit.count() < sparse) {
return;
}
// add hold space
for(int i = memory_.size();i < pinch + 1 ;i++) {
memory_.push_back({});
}
INFO_VAR(memory_.size());
auto &memory = memory_.at(pinch);
auto it = memory.find(index);
if (it != memory.end()) {
it->second++;
} else {
memory.insert({index,1});
}
#endif
}
/**
* filter
**/
bool ImplicitMemory::filter3x3(uint64_t index,int threshold)
{
bool ret = false;
for(const auto &shot:shotThough_3X3_) {
auto result = shot.first & index;
std::bitset<9> memBit(result);
TRACE_VAR(memBit);
if(memBit.count() >= threshold) {
return true;
}
}
return false;
}
/**
* get parter.
**/
uint64_t ImplicitMemory::getNext(int id)
{
TRACE_VAR(id);
TRACE_VAR(memSort_.size());
if(id >= memSort_.size()) {
return 0;
}
TRACE_VAR(searchIndex_);
TRACE_VAR(memSort_[id].size());
if(searchIndex_ >= memSort_[id].size()) {
return 0;
}
return memSort_[id][searchIndex_++];
}
/**
* sort
**/
void ImplicitMemory::sort()
{
memRanking_.clear();
memSort_.clear();
for(int index = 0; index < memory_.size();index++) {
memRanking_.push_back({});
}
for(int index = 0; index < memory_.size();index++) {
// map<uint64_t,vector<uint64_t>> sortByCount;
auto &memory = memory_[index];
for (auto it:memory) {
auto memCount = it.second;
std::bitset<25> memBit(it.first);
TRACE_VAR(memBit);
TRACE_VAR(it.second);
auto itSort = memRanking_[index].find(memCount);
if (memRanking_[index].end() != itSort) {
itSort->second.push_back(it.first);
} else {
memRanking_[index][memCount] = {it.first};
}
}
for (auto it:memRanking_[index]) {
auto memCount = it.first;
INFO_VAR(it.second.size());
INFO_VAR(memCount);
for (auto mem:it.second)
{
std::bitset<25> memBit(mem);
INFO_VAR(memBit);
}
}
TRACE_VAR(memory.size());
TRACE_VAR(memRanking_[index].size());
}
for(auto &it:memRanking_){
vector<uint64_t> memory;
for(auto &it2:it) {
memory.insert(memory.begin(),it2.second.begin(),it2.second.end());
}
memSort_.push_back(memory);
}
for(const auto &sortMem :memSort_){
INFO_VAR(sortMem.size());
}
INFO_VAR(memory_.size());
for(const auto &memory :memory_){
INFO_VAR(memory.size());
#if 0
for(const auto &pair:memory){
std::bitset<25> memBit(pair.first);
INFO_VAR(memBit);
INFO_VAR(pair.second);
}
#endif
}
}
#define _3X3(a,b,c) (0b##a##b##c)
const map<uint64_t,bool> ImplicitMemory::shotThough_3X3_ = {
{_3X3(000,
000,
111),true},
{_3X3(000,
111,
000),true},
{_3X3(111,
000,
000),true},
{_3X3(100,
100,
100),true},
{_3X3(010,
010,
010),true},
{_3X3(001,
001,
001),true},
{_3X3(100,
010,
001),true},
{_3X3(001,
010,
100),true},
{_3X3(100,
010,
100),true},
{_3X3(100,
010,
010),true},
{_3X3(010,
100,
100),true},
{_3X3(010,
100,
010),true},
{_3X3(010,
010,
100),true},
{_3X3(010,
010,
001),true},
{_3X3(010,
001,
001),true},
{_3X3(010,
001,
010),true},
{_3X3(001,
010,
010),true},
{_3X3(001,
010,
001),true},
{_3X3(001,
001,
010),true},
{_3X3(110,
001,
000),true},
{_3X3(100,
011,
000),true},
{_3X3(101,
010,
000),true},
{_3X3(011,
100,
000),true},
{_3X3(010,
101,
000),true},
{_3X3(001,
110,
000),true},
{_3X3(000,
110,
001),true},
{_3X3(000,
101,
010),true},
{_3X3(000,
100,
011),true},
{_3X3(000,
011,
100),true},
{_3X3(000,
010,
101),true},
{_3X3(000,
001,
110),true}
};
/*
1000010000100000000000000
1000010000100000000000000
00001
11110
00000
00000
00000
00000
10000
01111
00000
00000
00000
00111
11000
00000
00000
11000
00000
00000
00000
00111
00000
00000
00000
00111
11000
*/
const map<uint64_t,bool> ImplicitMemory::shotThough_5X5_ = {
{0b0000000000000000000011111,true},
{0b0000000000000000000111110,true},
{0b0000000000000000001011101,true},
{0b0000000000000000001111100,true},
{0b0000000000000000010011011,true},
{0b0000000000000000010111010,true},
{0b0000000000000000011011001,true},
{0b0000000000000000011111000,true},
{0b0000000000000000100010111,true},
{0b0000000000000000100110110,true},
{0b0000000000000000101010101,true},
{0b0000000000000000101110100,true},
{0b0000000000000000110010011,true},
{0b0000000000000000110110010,true},
{0b0000000000000000111010001,true},
{0b0000000000000000111110000,true},
{0b0000000000000001000001111,true},
{0b0000000000000001000101110,true},
{0b0000000000000001001001101,true},
{0b0000000000000001001101100,true},
{0b0000000000000001010001011,true},
{0b0000000000000001010101010,true},
{0b0000000000000001011001001,true},
{0b0000000000000001011101000,true},
{0b0000000000000001100000111,true},
{0b0000000000000001100100110,true},
{0b0000000000000001101000101,true},
{0b0000000000000001101100100,true},
{0b0000000000000001110000011,true},
{0b0000000000000001110100010,true},
{0b0000000000000001111000001,true},
{0b0000000000000001111100000,true},
{0b0000000000000010001011100,true},
{0b0000000000000010011011000,true},
{0b0000000000000010101010100,true},
{0b0000000000000010111010000,true},
{0b0000000000000011001001100,true},
{0b0000000000000011011001000,true},
{0b0000000000000011101000100,true},
{0b0000000000000011111000000,true},
{0b0000000000000100000111100,true},
{0b0000000000000100010111000,true},
{0b0000000000000100100110100,true},
{0b0000000000000100110110000,true},
{0b0000000000000101000101100,true},
{0b0000000000000101010101000,true},
{0b0000000000000101100100100,true},
{0b0000000000000101110100000,true},
{0b0000000000000110000011100,true},
{0b0000000000000110010011000,true},
{0b0000000000000110100010100,true},
{0b0000000000000110110010000,true},
{0b0000000000000111000001100,true},
{0b0000000000000111010001000,true},
{0b0000000000000111100000100,true},
{0b0000000000000111110000000,true},
{0b0000000000001000001011001,true},
{0b0000000000001000001111000,true},
{0b0000000000001000100010011,true},
{0b0000000000001000100110010,true},
{0b0000000000001000101010001,true},
{0b0000000000001000101110000,true},
{0b0000000000001001001001001,true},
{0b0000000000001001001101000,true},
{0b0000000000001001100000011,true},
{0b0000000000001001100100010,true},
{0b0000000000001001101000001,true},
{0b0000000000001001101100000,true},
{0b0000000000001010001011000,true},
{0b0000000000001010101010000,true},
{0b0000000000001011001001000,true},
{0b0000000000001011101000000,true},
{0b0000000000001100000111000,true},
{0b0000000000001100100110000,true},
{0b0000000000001101000101000,true},
{0b0000000000001101100100000,true},
{0b0000000000001110000011000,true},
{0b0000000000001110100010000,true},
{0b0000000000001111000001000,true},
{0b0000000000001111100000000,true},
{0b0000000000010001000000111,true},
{0b0000000000010001000100110,true},
{0b0000000000010001001000101,true},
{0b0000000000010001001100100,true},
{0b0000000000010001010000011,true},
{0b0000000000010001010100010,true},
{0b0000000000010001011000001,true},
{0b0000000000010001011100000,true},
{0b0000000000010011001000100,true},
{0b0000000000010011011000000,true},
{0b0000000000010101010100000,true},
{0b0000000000010111010000000,true},
{0b0000000000011001000000011,true},
{0b0000000000011001000100010,true},
{0b0000000000011001001000001,true},
{0b0000000000011001001100000,true},
{0b0000000000011011001000000,true},
{0b0000000000011101000100000,true},
{0b0000000000011111000000000,true},
{0b0000000000100000100000111,true},
{0b0000000000100000100100110,true},
{0b0000000000100000101000101,true},
{0b0000000000100000101100100,true},
{0b0000000000100000110000011,true},
{0b0000000000100000110100010,true},
{0b0000000000100000111000001,true},
{0b0000000000100000111100000,true},
{0b0000000000100010101000100,true},
{0b0000000000100010111000000,true},
{0b0000000000100100100100100,true},
{0b0000000000100100110100000,true},
{0b0000000000100110100000100,true},
{0b0000000000100110110000000,true},
{0b0000000000101000100000011,true},
{0b0000000000101000100100010,true},
{0b0000000000101000101000001,true},
{0b0000000000101000101100000,true},
{0b0000000000101010101000000,true},
{0b0000000000101100100100000,true},
{0b0000000000101110100000000,true},
{0b0000000000110000000000111,true},
{0b0000000000110000000100110,true},
{0b0000000000110000001000101,true},
{0b0000000000110000001100100,true},
{0b0000000000110000010000011,true},
{0b0000000000110000010100010,true},
{0b0000000000110000011000001,true},
{0b0000000000110000011100000,true},
{0b0000000000110010001000100,true},
{0b0000000000110010011000000,true},
{0b0000000000110100010100000,true},
{0b0000000000110110010000000,true},
{0b0000000000111000000000011,true},
{0b0000000000111000000100010,true},
{0b0000000000111000001000001,true},
{0b0000000000111000001100000,true},
{0b0000000000111010001000000,true},
{0b0000000000111100000100000,true},
{0b0000000000111110000000000,true},
{0b0000000001000100000011100,true},
{0b0000000001000100010011000,true},
{0b0000000001000100100010100,true},
{0b0000000001000100110010000,true},
{0b0000000001000101000001100,true},
{0b0000000001000101010001000,true},
{0b0000000001000101100000100,true},
{0b0000000001000101110000000,true},
{0b0000000001001100000011000,true},
{0b0000000001001100100010000,true},
{0b0000000001001101000001000,true},
{0b0000000001001101100000000,true},
{0b0000000001010101010000000,true},
{0b0000000001011101000000000,true},
{0b0000000001100100100000100,true},
{0b0000000001100100110000000,true},
{0b0000000001101100100000000,true},
{0b0000000001110100010000000,true},
{0b0000000001111100000000000,true},
{0b0000000010000010000011100,true},
{0b0000000010000010010011000,true},
{0b0000000010000010100010100,true},
{0b0000000010000010110010000,true},
{0b0000000010000011000001100,true},
{0b0000000010000011010001000,true},
{0b0000000010000011100000100,true},
{0b0000000010000011110000000,true},
{0b0000000010001010000011000,true},
{0b0000000010001010100010000,true},
{0b0000000010001011000001000,true},
{0b0000000010001011100000000,true},
{0b0000000010010011010000000,true},
{0b0000000010011011000000000,true},
{0b0000000010100010100000100,true},
{0b0000000010100010110000000,true},
{0b0000000010101010100000000,true},
{0b0000000010110010010000000,true},
{0b0000000010111010000000000,true},
{0b0000000011000000000011100,true},
{0b0000000011000000010011000,true},
{0b0000000011000000100010100,true},
{0b0000000011000000110010000,true},
{0b0000000011000001000001100,true},
{0b0000000011000001010001000,true},
{0b0000000011000001100000100,true},
{0b0000000011000001110000000,true},
{0b0000000011001000000011000,true},
{0b0000000011001000100010000,true},
{0b0000000011001001000001000,true},
{0b0000000011001001100000000,true},
{0b0000000011010001010000000,true},
{0b0000000011011001000000000,true},
{0b0000000011100000100000100,true},
{0b0000000011100000110000000,true},
{0b0000000011101000100000000,true},
{0b0000000011110000010000000,true},
{0b0000000011111000000000000,true},
{0b0000000100000100000111000,true},
{0b0000000100000100100110000,true},
{0b0000000100000101000101000,true},
{0b0000000100000101100100000,true},
{0b0000000100000110000011000,true},
{0b0000000100000110100010000,true},
{0b0000000100000111000001000,true},
{0b0000000100000111100000000,true},
{0b0000000100010001000000011,true},
{0b0000000100010001000100010,true},
{0b0000000100010001001000001,true},
{0b0000000100010001001100000,true},
{0b0000000100010011001000000,true},
{0b0000000100010101000100000,true},
{0b0000000100010111000000000,true},
{0b0000000100100100100100000,true},
{0b0000000100100110100000000,true},
{0b0000000100110000000000011,true},
{0b0000000100110000000100010,true},
{0b0000000100110000001000001,true},
{0b0000000100110000001100000,true},
{0b0000000100110010001000000,true},
{0b0000000100110100000100000,true},
{0b0000000100110110000000000,true},
{0b0000000101000100000011000,true},
{0b0000000101000100100010000,true},
{0b0000000101000101000001000,true},
{0b0000000101000101100000000,true},
{0b0000000101010101000000000,true},
{0b0000000101100100100000000,true},
{0b0000000101110100000000000,true},
{0b0000000110000010000011000,true},
{0b0000000110000010100010000,true},
{0b0000000110000011000001000,true},
{0b0000000110000011100000000,true},
{0b0000000110010011000000000,true},
{0b0000000110100010100000000,true},
{0b0000000110110010000000000,true},
{0b0000000111000000000011000,true},
{0b0000000111000000100010000,true},
{0b0000000111000001000001000,true},
{0b0000000111000001100000000,true},
{0b0000000111010001000000000,true},
{0b0000000111100000100000000,true},
{0b0000000111110000000000000,true},
{0b0000001000100000000000111,true},
{0b0000001000100000000100110,true},
{0b0000001000100000001000101,true},
{0b0000001000100000001100100,true},
{0b0000001000100000010000011,true},
{0b0000001000100000010100010,true},
{0b0000001000100000011000001,true},
{0b0000001000100000011100000,true},
{0b0000001000100010001000100,true},
{0b0000001000100010011000000,true},
{0b0000001000100100010100000,true},
{0b0000001000100110010000000,true},
{0b0000001000101000000000011,true},
{0b0000001000101000000100010,true},
{0b0000001000101000001000001,true},
{0b0000001000101000001100000,true},
{0b0000001000101010001000000,true},
{0b0000001000101100000100000,true},
{0b0000001000101110000000000,true},
{0b0000001001100100010000000,true},
{0b0000001001101100000000000,true},
{0b0000001010101010000000000,true},
{0b0000001011101000000000000,true},
{0b0000001100100000000000011,true},
{0b0000001100100000000100010,true},
{0b0000001100100000001000001,true},
{0b0000001100100000001100000,true},
{0b0000001100100010001000000,true},
{0b0000001100100100000100000,true},
{0b0000001100100110000000000,true},
{0b0000001101100100000000000,true},
{0b0000001110100010000000000,true},
{0b0000001111100000000000000,true},
{0b0000010000010000000000111,true},
{0b0000010000010000000100110,true},
{0b0000010000010000001000101,true},
{0b0000010000010000001100100,true},
{0b0000010000010000010000011,true},
{0b0000010000010000010100010,true},
{0b0000010000010000011000001,true},
{0b0000010000010000011100000,true},
{0b0000010000010010001000100,true},
{0b0000010000010010011000000,true},
{0b0000010000010100010100000,true},
{0b0000010000010110010000000,true},
{0b0000010000011000000000011,true},
{0b0000010000011000000100010,true},
{0b0000010000011000001000001,true},
{0b0000010000011000001100000,true},
{0b0000010000011010001000000,true},
{0b0000010000011100000100000,true},
{0b0000010000011110000000000,true},
{0b0000010001010100010000000,true},
{0b0000010001011100000000000,true},
{0b0000010010010010010000000,true},
{0b0000010010011010000000000,true},
{0b0000010011010000010000000,true},
{0b0000010011011000000000000,true},
{0b0000010100010000000000011,true},
{0b0000010100010000000100010,true},
{0b0000010100010000001000001,true},
{0b0000010100010000001100000,true},
{0b0000010100010010001000000,true},
{0b0000010100010100000100000,true},
{0b0000010100010110000000000,true},
{0b0000010101010100000000000,true},
{0b0000010110010010000000000,true},
{0b0000010111010000000000000,true},
{0b0000011000000000000000111,true},
{0b0000011000000000000100110,true},
{0b0000011000000000001000101,true},
{0b0000011000000000001100100,true},
{0b0000011000000000010000011,true},
{0b0000011000000000010100010,true},
{0b0000011000000000011000001,true},
{0b0000011000000000011100000,true},
{0b0000011000000010001000100,true},
{0b0000011000000010011000000,true},
{0b0000011000000100010100000,true},
{0b0000011000000110010000000,true},
{0b0000011000001000000000011,true},
{0b0000011000001000000100010,true},
{0b0000011000001000001000001,true},
{0b0000011000001000001100000,true},
{0b0000011000001010001000000,true},
{0b0000011000001100000100000,true},
{0b0000011000001110000000000,true},
{0b0000011001000100010000000,true},
{0b0000011001001100000000000,true},
{0b0000011010001010000000000,true},
{0b0000011011001000000000000,true},
{0b0000011100000000000000011,true},
{0b0000011100000000000100010,true},
{0b0000011100000000001000001,true},
{0b0000011100000000001100000,true},
{0b0000011100000010001000000,true},
{0b0000011100000100000100000,true},
{0b0000011100000110000000000,true},
{0b0000011101000100000000000,true},
{0b0000011110000010000000000,true},
{0b0000011111000000000000000,true},
{0b0000100001000010000100001,true},
{0b0000100001000010000100010,true},
{0b0000100001000010001000001,true},
{0b0000100001000010001000010,true},
{0b0000100001000010001000100,true},
{0b0000100001000010010000010,true},
{0b0000100001000010010000100,true},
{0b0000100001000010010001000,true},
{0b0000100001000010100000100,true},
{0b0000100001000010100001000,true},
{0b0000100001000010100010000,true},
{0b0000100001000011000001000,true},
{0b0000100001000011000010000,true},
{0b0000100001000100000100001,true},
{0b0000100001000100000100010,true},
{0b0000100001000100001000001,true},
{0b0000100001000100001000010,true},
{0b0000100001000100001000100,true},
{0b0000100001000100010000010,true},
{0b0000100001000100010000100,true},
{0b0000100001000100010001000,true},
{0b0000100001000100100000100,true},
{0b0000100001000100100001000,true},
{0b0000100001000100100010000,true},
{0b0000100001000101000001000,true},
{0b0000100001000101000010000,true},
{0b0000100001001000001000001,true},
{0b0000100001001000001000010,true},
{0b0000100001001000001000100,true},
{0b0000100001001000010000010,true},
{0b0000100001001000010000100,true},
{0b0000100001001000010001000,true},
{0b0000100001001000100000100,true},
{0b0000100001001000100001000,true},
{0b0000100001001000100010000,true},
{0b0000100001010000010000010,true},
{0b0000100001010000010000100,true},
{0b0000100001010000010001000,true},
{0b0000100001010000100000100,true},
{0b0000100001010000100001000,true},
{0b0000100001010000100010000,true},
{0b0000100001010001000001000,true},
{0b0000100001010001000010000,true},
{0b0000100001100000100000100,true},
{0b0000100001100000100001000,true},
{0b0000100001100000100010000,true},
{0b0000100001100001000001000,true},
{0b0000100001100001000010000,true},
{0b0000100010000000000011100,true},
{0b0000100010000000010011000,true},
{0b0000100010000000100010100,true},
{0b0000100010000000110010000,true},
{0b0000100010000001000001100,true},
{0b0000100010000001010001000,true},
{0b0000100010000001100000100,true},
{0b0000100010000001110000000,true},
{0b0000100010000010000100001,true},
{0b0000100010000010000100010,true},
{0b0000100010000010001000001,true},
{0b0000100010000010001000010,true},
{0b0000100010000010001000100,true},
{0b0000100010000010010000010,true},
{0b0000100010000010010000100,true},
{0b0000100010000010010001000,true},
{0b0000100010000010100000100,true},
{0b0000100010000010100001000,true},
{0b0000100010000010100010000,true},
{0b0000100010000011000001000,true},
{0b0000100010000011000010000,true},
{0b0000100010000100000100001,true},
{0b0000100010000100000100010,true},
{0b0000100010000100001000001,true},
{0b0000100010000100001000010,true},
{0b0000100010000100001000100,true},
{0b0000100010000100010000010,true},
{0b0000100010000100010000100,true},
{0b0000100010000100010001000,true},
{0b0000100010000100100000100,true},
{0b0000100010000100100001000,true},
{0b0000100010000100100010000,true},
{0b0000100010000101000001000,true},
{0b0000100010000101000010000,true},
{0b0000100010001000000011000,true},
{0b0000100010001000000100001,true},
{0b0000100010001000000100010,true},
{0b0000100010001000001000001,true},
{0b0000100010001000001000010,true},
{0b0000100010001000001000100,true},
{0b0000100010001000010000010,true},
{0b0000100010001000010000100,true},
{0b0000100010001000010001000,true},
{0b0000100010001000100000100,true},
{0b0000100010001000100001000,true},
{0b0000100010001000100010000,true},
{0b0000100010001001000001000,true},
{0b0000100010001001000010000,true},
{0b0000100010001001100000000,true},
{0b0000100010010000010000010,true},
{0b0000100010010000010000100,true},
{0b0000100010010000010001000,true},
{0b0000100010010000100000100,true},
{0b0000100010010000100001000,true},
{0b0000100010010000100010000,true},
{0b0000100010010001000001000,true},
{0b0000100010010001000010000,true},
{0b0000100010010001010000000,true},
{0b0000100010011001000000000,true},
{0b0000100010100000100000100,true},
{0b0000100010100000100001000,true},
{0b0000100010100000100010000,true},
{0b0000100010100000110000000,true},
{0b0000100010100001000001000,true},
{0b0000100010100001000010000,true},
{0b0000100010101000100000000,true},
{0b0000100010110000010000000,true},
{0b0000100010111000000000000,true},
{0b0000100110000000000011000,true},
{0b0000100110000000100010000,true},
{0b0000100110000001000001000,true},
{0b0000100110000001100000000,true},
{0b0000100110010001000000000,true},
{0b0000100110100000100000000,true},
{0b0000100110110000000000000,true},
{0b0000101010101000000000000,true},
{0b0000101110100000000000000,true},
{0b0000110010010000010000000,true},
{0b0000110010011000000000000,true},
{0b0000110110010000000000000,true},
{0b0000111010001000000000000,true},
{0b0000111110000000000000000,true},
{0b0001000001000000000011100,true},
{0b0001000001000000010011000,true},
{0b0001000001000000100010100,true},
{0b0001000001000000110010000,true},
{0b0001000001000001000001100,true},
{0b0001000001000001010001000,true},
{0b0001000001000001100000100,true},
{0b0001000001000001110000000,true},
{0b0001000001000010000100001,true},
{0b0001000001000010000100010,true},
{0b0001000001000010001000001,true},
{0b0001000001000010001000010,true},
{0b0001000001000010001000100,true},
{0b0001000001000010010000010,true},
{0b0001000001000010010000100,true},
{0b0001000001000010010001000,true},
{0b0001000001000010100000100,true},
{0b0001000001000010100001000,true},
{0b0001000001000010100010000,true},
{0b0001000001000011000001000,true},
{0b0001000001000011000010000,true},
{0b0001000001000100000100001,true},
{0b0001000001000100000100010,true},
{0b0001000001000100001000001,true},
{0b0001000001000100001000010,true},
{0b0001000001000100001000100,true},
{0b0001000001000100010000010,true},
{0b0001000001000100010000100,true},
{0b0001000001000100010001000,true},
{0b0001000001000100100000100,true},
{0b0001000001000100100001000,true},
{0b0001000001000100100010000,true},
{0b0001000001000101000001000,true},
{0b0001000001000101000010000,true},
{0b0001000001001000001000001,true},
{0b0001000001001000001000010,true},
{0b0001000001001000001000100,true},
{0b0001000001001000010000010,true},
{0b0001000001001000010000100,true},
{0b0001000001001000010001000,true},
{0b0001000001001000100000100,true},
{0b0001000001001000100001000,true},
{0b0001000001001000100010000,true},
{0b0001000001001001100000000,true},
{0b0001000001010000010000010,true},
{0b0001000001010000010000100,true},
{0b0001000001010000010001000,true},
{0b0001000001010000100000100,true},
{0b0001000001010000100001000,true},
{0b0001000001010000100010000,true},
{0b0001000001010001000001000,true},
{0b0001000001010001000010000,true},
{0b0001000001010001010000000,true},
{0b0001000001011001000000000,true},
{0b0001000001100000100000100,true},
{0b0001000001100000100001000,true},
{0b0001000001100000100010000,true},
{0b0001000001100000110000000,true},
{0b0001000001100001000001000,true},
{0b0001000001100001000010000,true},
{0b0001000001101000100000000,true},
{0b0001000001110000010000000,true},
{0b0001000001111000000000000,true},
{0b0001000010000010000100001,true},
{0b0001000010000010000100010,true},
{0b0001000010000010001000001,true},
{0b0001000010000010001000010,true},
{0b0001000010000010001000100,true},
{0b0001000010000010010000010,true},
{0b0001000010000010010000100,true},
{0b0001000010000010010001000,true},
{0b0001000010000010100000100,true},
{0b0001000010000010100001000,true},
{0b0001000010000010100010000,true},
{0b0001000010000011000001000,true},
{0b0001000010000011000010000,true},
{0b0001000010000100000100001,true},
{0b0001000010000100000100010,true},
{0b0001000010000100001000001,true},
{0b0001000010000100001000010,true},
{0b0001000010000100001000100,true},
{0b0001000010000100010000010,true},
{0b0001000010000100010000100,true},
{0b0001000010000100010001000,true},
{0b0001000010000100100000100,true},
{0b0001000010000100100001000,true},
{0b0001000010000100100010000,true},
{0b0001000010000101000001000,true},
{0b0001000010000101000010000,true},
{0b0001000010001000000100001,true},
{0b0001000010001000000100010,true},
{0b0001000010001000001000001,true},
{0b0001000010001000001000010,true},
{0b0001000010001000001000100,true},
{0b0001000010001000010000010,true},
{0b0001000010001000010000100,true},
{0b0001000010001000010001000,true},
{0b0001000010001000100000100,true},
{0b0001000010001000100001000,true},
{0b0001000010001000100010000,true},
{0b0001000010001001000001000,true},
{0b0001000010001001000010000,true},
{0b0001000010010000010000010,true},
{0b0001000010010000010000100,true},
{0b0001000010010000010001000,true},
{0b0001000010010000100000100,true},
{0b0001000010010000100001000,true},
{0b0001000010010000100010000,true},
{0b0001000010010001000001000,true},
{0b0001000010010001000010000,true},
{0b0001000010100000100000100,true},
{0b0001000010100000100001000,true},
{0b0001000010100000100010000,true},
{0b0001000010100001000001000,true},
{0b0001000010100001000010000,true},
{0b0001000100000010000100001,true},
{0b0001000100000010000100010,true},
{0b0001000100000010001000001,true},
{0b0001000100000010001000010,true},
{0b0001000100000010001000100,true},
{0b0001000100000100000100001,true},
{0b0001000100000100000100010,true},
{0b0001000100000100001000001,true},
{0b0001000100000100001000010,true},
{0b0001000100000100001000100,true},
{0b0001000100000100010000010,true},
{0b0001000100000100010000100,true},
{0b0001000100000100010001000,true},
{0b0001000100000100100000100,true},
{0b0001000100000100100001000,true},
{0b0001000100000100100010000,true},
{0b0001000100000101000001000,true},
{0b0001000100000101000010000,true},
{0b0001000100001000000100001,true},
{0b0001000100001000000100010,true},
{0b0001000100001000001000001,true},
{0b0001000100001000001000010,true},
{0b0001000100001000001000100,true},
{0b0001000100001000010000010,true},
{0b0001000100001000010000100,true},
{0b0001000100001000010001000,true},
{0b0001000100001000100000100,true},
{0b0001000100001000100001000,true},
{0b0001000100001000100010000,true},
{0b0001000100001001000001000,true},
{0b0001000100001001000010000,true},
{0b0001000100010000000100001,true},
{0b0001000100010000000100010,true},
{0b0001000100010000001000001,true},
{0b0001000100010000001000010,true},
{0b0001000100010000001000100,true},
{0b0001000100010000010000010,true},
{0b0001000100010000010000100,true},
{0b0001000100010000010001000,true},
{0b0001000100010000100000100,true},
{0b0001000100010000100001000,true},
{0b0001000100010000100010000,true},
{0b0001000100010001000001000,true},
{0b0001000100010001000010000,true},
{0b0001000100100000100000100,true},
{0b0001000100100000100001000,true},
{0b0001000100100000100010000,true},
{0b0001000100100001000001000,true},
{0b0001000100100001000010000,true},
{0b0001000101000000000011000,true},
{0b0001000101000000100010000,true},
{0b0001000101000001000001000,true},
{0b0001000101000001100000000,true},
{0b0001000101010001000000000,true},
{0b0001000101100000100000000,true},
{0b0001000101110000000000000,true},
{0b0001001001101000000000000,true},
{0b0001001101100000000000000,true},
{0b0001010001010000010000000,true},
{0b0001010001011000000000000,true},
{0b0001010101010000000000000,true},
{0b0001011001001000000000000,true},
{0b0001011101000000000000000,true},
{0b0001100000000000000011100,true},
{0b0001100000000000010011000,true},
{0b0001100000000000100010100,true},
{0b0001100000000000110010000,true},
{0b0001100000000001000001100,true},
{0b0001100000000001010001000,true},
{0b0001100000000001100000100,true},
{0b0001100000000001110000000,true},
{0b0001100000001000100010000,true},
{0b0001100000001001100000000,true},
{0b0001100000010001010000000,true},
{0b0001100000011001000000000,true},
{0b0001100000100000100000100,true},
{0b0001100000100000110000000,true},
{0b0001100000101000100000000,true},
{0b0001100000110000010000000,true},
{0b0001100000111000000000000,true},
{0b0001100100000000000011000,true},
{0b0001100100000000100010000,true},
{0b0001100100000001000001000,true},
{0b0001100100000001100000000,true},
{0b0001100100010001000000000,true},
{0b0001100100100000100000000,true},
{0b0001100100110000000000000,true},
{0b0001101000101000000000000,true},
{0b0001101100100000000000000,true},
{0b0001110000010000010000000,true},
{0b0001110000011000000000000,true},
{0b0001110100010000000000000,true},
{0b0001111000001000000000000,true},
{0b0001111100000000000000000,true},
{0b0010000010000010000011000,true},
{0b0010000010000010000100001,true},
{0b0010000010000010000100010,true},
{0b0010000010000010001000001,true},
{0b0010000010000010001000010,true},
{0b0010000010000010001000100,true},
{0b0010000010000010010000010,true},
{0b0010000010000010010000100,true},
{0b0010000010000010010001000,true},
{0b0010000010000010100000100,true},
{0b0010000010000010100001000,true},
{0b0010000010000010100010000,true},
{0b0010000010000011000001000,true},
{0b0010000010000011000010000,true},
{0b0010000010000011100000000,true},
{0b0010000010000100000100001,true},
{0b0010000010000100000100010,true},
{0b0010000010000100001000001,true},
{0b0010000010000100001000010,true},
{0b0010000010000100001000100,true},
{0b0010000010000100010000010,true},
{0b0010000010000100010000100,true},
{0b0010000010000100010001000,true},
{0b0010000010000100100000100,true},
{0b0010000010000100100001000,true},
{0b0010000010000100100010000,true},
{0b0010000010000101000001000,true},
{0b0010000010000101000010000,true},
{0b0010000010001000000100001,true},
{0b0010000010001000000100010,true},
{0b0010000010001000001000001,true},
{0b0010000010001000001000010,true},
{0b0010000010001000001000100,true},
{0b0010000010001000010000010,true},
{0b0010000010001000010000100,true},
{0b0010000010001000010001000,true},
{0b0010000010001000100000100,true},
{0b0010000010001000100001000,true},
{0b0010000010001000100010000,true},
{0b0010000010001001000001000,true},
{0b0010000010001001000010000,true},
{0b0010000010010000010000010,true},
{0b0010000010010000010000100,true},
{0b0010000010010000010001000,true},
{0b0010000010010000100000100,true},
{0b0010000010010000100001000,true},
{0b0010000010010000100010000,true},
{0b0010000010010001000001000,true},
{0b0010000010010001000010000,true},
{0b0010000010010011000000000,true},
{0b0010000010100000100000100,true},
{0b0010000010100000100001000,true},
{0b0010000010100000100010000,true},
{0b0010000010100001000001000,true},
{0b0010000010100001000010000,true},
{0b0010000010100010100000000,true},
{0b0010000010110010000000000,true},
{0b0010000011000000000011000,true},
{0b0010000011000000100010000,true},
{0b0010000011000001000001000,true},
{0b0010000011000001100000000,true},
{0b0010000011010001000000000,true},
{0b0010000011100000100000000,true},
{0b0010000011110000000000000,true},
{0b0010000100000010000100001,true},
{0b0010000100000010000100010,true},
{0b0010000100000010001000001,true},
{0b0010000100000010001000010,true},
{0b0010000100000010001000100,true},
{0b0010000100000100000100001,true},
{0b0010000100000100000100010,true},
{0b0010000100000100001000001,true},
{0b0010000100000100001000010,true},
{0b0010000100000100001000100,true},
{0b0010000100000100010000010,true},
{0b0010000100000100010000100,true},
{0b0010000100000100010001000,true},
{0b0010000100000100100000100,true},
{0b0010000100000100100001000,true},
{0b0010000100000100100010000,true},
{0b0010000100000101000001000,true},
{0b0010000100000101000010000,true},
{0b0010000100001000000100001,true},
{0b0010000100001000000100010,true},
{0b0010000100001000001000001,true},
{0b0010000100001000001000010,true},
{0b0010000100001000001000100,true},
{0b0010000100001000010000010,true},
{0b0010000100001000010000100,true},
{0b0010000100001000010001000,true},
{0b0010000100001000100000100,true},
{0b0010000100001000100001000,true},
{0b0010000100001000100010000,true},
{0b0010000100001001000001000,true},
{0b0010000100001001000010000,true},
{0b0010000100010000000100001,true},
{0b0010000100010000000100010,true},
{0b0010000100010000001000001,true},
{0b0010000100010000001000010,true},
{0b0010000100010000001000100,true},
{0b0010000100010000010000010,true},
{0b0010000100010000010000100,true},
{0b0010000100010000010001000,true},
{0b0010000100010000100000100,true},
{0b0010000100010000100001000,true},
{0b0010000100010000100010000,true},
{0b0010000100010001000001000,true},
{0b0010000100010001000010000,true},
{0b0010000100100000100000100,true},
{0b0010000100100000100001000,true},
{0b0010000100100000100010000,true},
{0b0010000100100001000001000,true},
{0b0010000100100001000010000,true},
{0b0010001000000010000100001,true},
{0b0010001000000010000100010,true},
{0b0010001000000010001000001,true},
{0b0010001000000010001000010,true},
{0b0010001000000010001000100,true},
{0b0010001000000100000100001,true},
{0b0010001000000100000100010,true},
{0b0010001000000100001000001,true},
{0b0010001000000100001000010,true},
{0b0010001000000100001000100,true},
{0b0010001000000100010000010,true},
{0b0010001000000100010000100,true},
{0b0010001000000100010001000,true},
{0b0010001000001000000100001,true},
{0b0010001000001000000100010,true},
{0b0010001000001000001000001,true},
{0b0010001000001000001000010,true},
{0b0010001000001000001000100,true},
{0b0010001000001000010000010,true},
{0b0010001000001000010000100,true},
{0b0010001000001000010001000,true},
{0b0010001000001000100000100,true},
{0b0010001000001000100001000,true},
{0b0010001000001000100010000,true},
{0b0010001000001001000001000,true},
{0b0010001000001001000010000,true},
{0b0010001000010000000100001,true},
{0b0010001000010000000100010,true},
{0b0010001000010000001000001,true},
{0b0010001000010000001000010,true},
{0b0010001000010000001000100,true},
{0b0010001000010000010000010,true},
{0b0010001000010000010000100,true},
{0b0010001000010000010001000,true},
{0b0010001000010000100000100,true},
{0b0010001000010000100001000,true},
{0b0010001000010000100010000,true},
{0b0010001000010001000001000,true},
{0b0010001000010001000010000,true},
{0b0010001000100000000000011,true},
{0b0010001000100000000100001,true},
{0b0010001000100000000100010,true},
{0b0010001000100000001000001,true},
{0b0010001000100000001000010,true},
{0b0010001000100000001000100,true},
{0b0010001000100000001100000,true},
{0b0010001000100000010000010,true},
{0b0010001000100000010000100,true},
{0b0010001000100000010001000,true},
{0b0010001000100000100000100,true},
{0b0010001000100000100001000,true},
{0b0010001000100000100010000,true},
{0b0010001000100001000001000,true},
{0b0010001000100001000010000,true},
{0b0010001000100010001000000,true},
{0b0010001000100100000100000,true},
{0b0010001000100110000000000,true},
{0b0010001001100100000000000,true},
{0b0010001010100010000000000,true},
{0b0010001011100000000000000,true},
{0b0010010010010010000000000,true},
{0b0010010011010000000000000,true},
{0b0010011000000000000000011,true},
{0b0010011000000000000100010,true},
{0b0010011000000000001000001,true},
{0b0010011000000000001100000,true},
{0b0010011000000010001000000,true},
{0b0010011000000100000100000,true},
{0b0010011000000110000000000,true},
{0b0010011001000100000000000,true},
{0b0010011010000010000000000,true},
{0b0010011011000000000000000,true},
{0b0010100010000000000011000,true},
{0b0010100010000000100010000,true},
{0b0010100010000001000001000,true},
{0b0010100010000001100000000,true},
{0b0010100010010001000000000,true},
{0b0010100010100000100000000,true},
{0b0010100010110000000000000,true},
{0b0010101010100000000000000,true},
{0b0010110010010000000000000,true},
{0b0010111010000000000000000,true},
{0b0011000001000000000011000,true},
{0b0011000001000000100010000,true},
{0b0011000001000001000001000,true},
{0b0011000001000001100000000,true},
{0b0011000001010001000000000,true},
{0b0011000001100000100000000,true},
{0b0011000001110000000000000,true},
{0b0011001001100000000000000,true},
{0b0011010001010000000000000,true},
{0b0011011001000000000000000,true},
{0b0011100000000000000011000,true},
{0b0011100000000000100010000,true},
{0b0011100000000001000001000,true},
{0b0011100000000001100000000,true},
{0b0011100000010001000000000,true},
{0b0011100000100000100000000,true},
{0b0011100000110000000000000,true},
{0b0011101000100000000000000,true},
{0b0011110000010000000000000,true},
{0b0011111000000000000000000,true},
{0b0100000100000010000100001,true},
{0b0100000100000010000100010,true},
{0b0100000100000010001000001,true},
{0b0100000100000010001000010,true},
{0b0100000100000010001000100,true},
{0b0100000100000100000100001,true},
{0b0100000100000100000100010,true},
{0b0100000100000100001000001,true},
{0b0100000100000100001000010,true},
{0b0100000100000100001000100,true},
{0b0100000100000100010000010,true},
{0b0100000100000100010000100,true},
{0b0100000100000100010001000,true},
{0b0100000100000100100000100,true},
{0b0100000100000100100001000,true},
{0b0100000100000100100010000,true},
{0b0100000100000101000001000,true},
{0b0100000100000101000010000,true},
{0b0100000100001000000100001,true},
{0b0100000100001000000100010,true},
{0b0100000100001000001000001,true},
{0b0100000100001000001000010,true},
{0b0100000100001000001000100,true},
{0b0100000100001000010000010,true},
{0b0100000100001000010000100,true},
{0b0100000100001000010001000,true},
{0b0100000100001000100000100,true},
{0b0100000100001000100001000,true},
{0b0100000100001000100010000,true},
{0b0100000100001001000001000,true},
{0b0100000100001001000010000,true},
{0b0100000100010000000100001,true},
{0b0100000100010000000100010,true},
{0b0100000100010000001000001,true},
{0b0100000100010000001000010,true},
{0b0100000100010000001000100,true},
{0b0100000100010000010000010,true},
{0b0100000100010000010000100,true},
{0b0100000100010000010001000,true},
{0b0100000100010000100000100,true},
{0b0100000100010000100001000,true},
{0b0100000100010000100010000,true},
{0b0100000100010001000001000,true},
{0b0100000100010001000010000,true},
{0b0100000100100000100000100,true},
{0b0100000100100000100001000,true},
{0b0100000100100000100010000,true},
{0b0100000100100001000001000,true},
{0b0100000100100001000010000,true},
{0b0100001000000010000100001,true},
{0b0100001000000010000100010,true},
{0b0100001000000010001000001,true},
{0b0100001000000010001000010,true},
{0b0100001000000010001000100,true},
{0b0100001000000100000100001,true},
{0b0100001000000100000100010,true},
{0b0100001000000100001000001,true},
{0b0100001000000100001000010,true},
{0b0100001000000100001000100,true},
{0b0100001000000100010000010,true},
{0b0100001000000100010000100,true},
{0b0100001000000100010001000,true},
{0b0100001000001000000100001,true},
{0b0100001000001000000100010,true},
{0b0100001000001000001000001,true},
{0b0100001000001000001000010,true},
{0b0100001000001000001000100,true},
{0b0100001000001000010000010,true},
{0b0100001000001000010000100,true},
{0b0100001000001000010001000,true},
{0b0100001000001000100000100,true},
{0b0100001000001000100001000,true},
{0b0100001000001000100010000,true},
{0b0100001000001001000001000,true},
{0b0100001000001001000010000,true},
{0b0100001000010000000100001,true},
{0b0100001000010000000100010,true},
{0b0100001000010000001000001,true},
{0b0100001000010000001000010,true},
{0b0100001000010000001000100,true},
{0b0100001000010000010000010,true},
{0b0100001000010000010000100,true},
{0b0100001000010000010001000,true},
{0b0100001000010000100000100,true},
{0b0100001000010000100001000,true},
{0b0100001000010000100010000,true},
{0b0100001000010001000001000,true},
{0b0100001000010001000010000,true},
{0b0100001000100000000100001,true},
{0b0100001000100000000100010,true},
{0b0100001000100000001000001,true},
{0b0100001000100000001000010,true},
{0b0100001000100000001000100,true},
{0b0100001000100000010000010,true},
{0b0100001000100000010000100,true},
{0b0100001000100000010001000,true},
{0b0100001000100000100000100,true},
{0b0100001000100000100001000,true},
{0b0100001000100000100010000,true},
{0b0100001000100001000001000,true},
{0b0100001000100001000010000,true},
{0b0100010000000000000000111,true},
{0b0100010000000000000100110,true},
{0b0100010000000000001000101,true},
{0b0100010000000000001100100,true},
{0b0100010000000000010000011,true},
{0b0100010000000000010100010,true},
{0b0100010000000000011000001,true},
{0b0100010000000000011100000,true},
{0b0100010000000010000100001,true},
{0b0100010000000010000100010,true},
{0b0100010000000010001000001,true},
{0b0100010000000010001000010,true},
{0b0100010000000010001000100,true},
{0b0100010000000010011000000,true},
{0b0100010000000100000100001,true},
{0b0100010000000100000100010,true},
{0b0100010000000100001000001,true},
{0b0100010000000100001000010,true},
{0b0100010000000100001000100,true},
{0b0100010000000100010000010,true},
{0b0100010000000100010000100,true},
{0b0100010000000100010001000,true},
{0b0100010000000100010100000,true},
{0b0100010000000110010000000,true},
{0b0100010000001000001000001,true},
{0b0100010000001000001000010,true},
{0b0100010000001000001000100,true},
{0b0100010000001000001100000,true},
{0b0100010000001000010000010,true},
{0b0100010000001000010000100,true},
{0b0100010000001000010001000,true},
{0b0100010000001000100000100,true},
{0b0100010000001000100001000,true},
{0b0100010000001000100010000,true},
{0b0100010000001010001000000,true},
{0b0100010000001100000100000,true},
{0b0100010000001110000000000,true},
{0b0100010000010000000100001,true},
{0b0100010000010000000100010,true},
{0b0100010000010000001000001,true},
{0b0100010000010000001000010,true},
{0b0100010000010000001000100,true},
{0b0100010000010000010000010,true},
{0b0100010000010000010000100,true},
{0b0100010000010000010001000,true},
{0b0100010000010000100000100,true},
{0b0100010000010000100001000,true},
{0b0100010000010000100010000,true},
{0b0100010000010001000001000,true},
{0b0100010000010001000010000,true},
{0b0100010000100000000100001,true},
{0b0100010000100000000100010,true},
{0b0100010000100000001000001,true},
{0b0100010000100000001000010,true},
{0b0100010000100000001000100,true},
{0b0100010000100000010000010,true},
{0b0100010000100000010000100,true},
{0b0100010000100000010001000,true},
{0b0100010000100000100000100,true},
{0b0100010000100000100001000,true},
{0b0100010000100000100010000,true},
{0b0100010000100001000001000,true},
{0b0100010000100001000010000,true},
{0b0100010001000100010000000,true},
{0b0100010001001100000000000,true},
{0b0100010010001010000000000,true},
{0b0100010011001000000000000,true},
{0b0100010100000000000000011,true},
{0b0100010100000000000100010,true},
{0b0100010100000000001000001,true},
{0b0100010100000000001100000,true},
{0b0100010100000010001000000,true},
{0b0100010100000100000100000,true},
{0b0100010100000110000000000,true},
{0b0100010101000100000000000,true},
{0b0100010110000010000000000,true},
{0b0100010111000000000000000,true},
{0b0100110010001000000000000,true},
{0b0100110110000000000000000,true},
{0b0101010101000000000000000,true},
{0b0101110100000000000000000,true},
{0b0110010000000000000000011,true},
{0b0110010000000000000100010,true},
{0b0110010000000000001000001,true},
{0b0110010000000000001100000,true},
{0b0110010000000010001000000,true},
{0b0110010000000100000100000,true},
{0b0110010000000110000000000,true},
{0b0110010001000100000000000,true},
{0b0110010010000010000000000,true},
{0b0110010011000000000000000,true},
{0b0110110010000000000000000,true},
{0b0111010001000000000000000,true},
{0b0111110000000000000000000,true},
{0b1000001000000000000000111,true},
{0b1000001000000000000100110,true},
{0b1000001000000000001000101,true},
{0b1000001000000000001100100,true},
{0b1000001000000000010000011,true},
{0b1000001000000000010100010,true},
{0b1000001000000000011000001,true},
{0b1000001000000000011100000,true},
{0b1000001000000010000100001,true},
{0b1000001000000010000100010,true},
{0b1000001000000010001000001,true},
{0b1000001000000010001000010,true},
{0b1000001000000010001000100,true},
{0b1000001000000010011000000,true},
{0b1000001000000100000100001,true},
{0b1000001000000100000100010,true},
{0b1000001000000100001000001,true},
{0b1000001000000100001000010,true},
{0b1000001000000100001000100,true},
{0b1000001000000100010000010,true},
{0b1000001000000100010000100,true},
{0b1000001000000100010001000,true},
{0b1000001000000100010100000,true},
{0b1000001000000110010000000,true},
{0b1000001000001000000000011,true},
{0b1000001000001000000100001,true},
{0b1000001000001000000100010,true},
{0b1000001000001000001000001,true},
{0b1000001000001000001000010,true},
{0b1000001000001000001000100,true},
{0b1000001000001000001100000,true},
{0b1000001000001000010000010,true},
{0b1000001000001000010000100,true},
{0b1000001000001000010001000,true},
{0b1000001000001000100000100,true},
{0b1000001000001000100001000,true},
{0b1000001000001000100010000,true},
{0b1000001000001001000001000,true},
{0b1000001000001001000010000,true},
{0b1000001000001010001000000,true},
{0b1000001000001100000100000,true},
{0b1000001000001110000000000,true},
{0b1000001000010000000100001,true},
{0b1000001000010000000100010,true},
{0b1000001000010000001000001,true},
{0b1000001000010000001000010,true},
{0b1000001000010000001000100,true},
{0b1000001000010000010000010,true},
{0b1000001000010000010000100,true},
{0b1000001000010000010001000,true},
{0b1000001000010000100000100,true},
{0b1000001000010000100001000,true},
{0b1000001000010000100010000,true},
{0b1000001000010001000001000,true},
{0b1000001000010001000010000,true},
{0b1000001000100000000100001,true},
{0b1000001000100000000100010,true},
{0b1000001000100000001000001,true},
{0b1000001000100000001000010,true},
{0b1000001000100000001000100,true},
{0b1000001000100000010000010,true},
{0b1000001000100000010000100,true},
{0b1000001000100000010001000,true},
{0b1000001000100000100000100,true},
{0b1000001000100000100001000,true},
{0b1000001000100000100010000,true},
{0b1000001000100001000001000,true},
{0b1000001000100001000010000,true},
{0b1000001001000100010000000,true},
{0b1000001001001100000000000,true},
{0b1000001010001010000000000,true},
{0b1000001011001000000000000,true},
{0b1000001100000000000000011,true},
{0b1000001100000000000100010,true},
{0b1000001100000000001000001,true},
{0b1000001100000000001100000,true},
{0b1000001100000010001000000,true},
{0b1000001100000100000100000,true},
{0b1000001100000110000000000,true},
{0b1000001101000100000000000,true},
{0b1000001110000010000000000,true},
{0b1000001111000000000000000,true},
{0b1000010000000010000100001,true},
{0b1000010000000010000100010,true},
{0b1000010000000010001000001,true},
{0b1000010000000010001000010,true},
{0b1000010000000010001000100,true},
{0b1000010000000100000100001,true},
{0b1000010000000100000100010,true},
{0b1000010000000100001000001,true},
{0b1000010000000100001000010,true},
{0b1000010000000100001000100,true},
{0b1000010000000100010000010,true},
{0b1000010000000100010000100,true},
{0b1000010000000100010001000,true},
{0b1000010000001000001000001,true},
{0b1000010000001000001000010,true},
{0b1000010000001000001000100,true},
{0b1000010000001000010000010,true},
{0b1000010000001000010000100,true},
{0b1000010000001000010001000,true},
{0b1000010000001000100000100,true},
{0b1000010000001000100001000,true},
{0b1000010000001000100010000,true},
{0b1000010000010000000100001,true},
{0b1000010000010000000100010,true},
{0b1000010000010000001000001,true},
{0b1000010000010000001000010,true},
{0b1000010000010000001000100,true},
{0b1000010000010000010000010,true},
{0b1000010000010000010000100,true},
{0b1000010000010000010001000,true},
{0b1000010000010000100000100,true},
{0b1000010000010000100001000,true},
{0b1000010000010000100010000,true},
{0b1000010000010001000001000,true},
{0b1000010000010001000010000,true},
{0b1000010000100000000100001,true},
{0b1000010000100000000100010,true},
{0b1000010000100000001000001,true},
{0b1000010000100000001000010,true},
{0b1000010000100000001000100,true},
{0b1000010000100000010000010,true},
{0b1000010000100000010000100,true},
{0b1000010000100000010001000,true},
{0b1000010000100000100000100,true},
{0b1000010000100000100001000,true},
{0b1000010000100000100010000,true},
{0b1000010000100001000001000,true},
{0b1000010000100001000010000,true},
{0b1000101010001000000000000,true},
{0b1000101110000000000000000,true},
{0b1001001001001000000000000,true},
{0b1001001101000000000000000,true},
{0b1001101000001000000000000,true},
{0b1001101100000000000000000,true},
{0b1010001000000000000000011,true},
{0b1010001000000000000100010,true},
{0b1010001000000000001000001,true},
{0b1010001000000000001100000,true},
{0b1010001000000010001000000,true},
{0b1010001000000100000100000,true},
{0b1010001000000110000000000,true},
{0b1010001001000100000000000,true},
{0b1010001010000010000000000,true},
{0b1010001011000000000000000,true},
{0b1010101010000000000000000,true},
{0b1011001001000000000000000,true},
{0b1011101000000000000000000,true},
{0b1100000000000000000000111,true},
{0b1100000000000000000100110,true},
{0b1100000000000000001000101,true},
{0b1100000000000000001100100,true},
{0b1100000000000000010000011,true},
{0b1100000000000000010100010,true},
{0b1100000000000000011000001,true},
{0b1100000000000000011100000,true},
{0b1100000000000010001000100,true},
{0b1100000000000010011000000,true},
{0b1100000000000100010100000,true},
{0b1100000000000110010000000,true},
{0b1100000000001000001000001,true},
{0b1100000000001000001100000,true},
{0b1100000000001010001000000,true},
{0b1100000000001100000100000,true},
{0b1100000000001110000000000,true},
{0b1100000001000100010000000,true},
{0b1100000001001100000000000,true},
{0b1100000010001010000000000,true},
{0b1100000011001000000000000,true},
{0b1100000100000000000000011,true},
{0b1100000100000000000100010,true},
{0b1100000100000000001000001,true},
{0b1100000100000000001100000,true},
{0b1100000100000010001000000,true},
{0b1100000100000100000100000,true},
{0b1100000100000110000000000,true},
{0b1100000101000100000000000,true},
{0b1100000110000010000000000,true},
{0b1100000111000000000000000,true},
{0b1100100010001000000000000,true},
{0b1100100110000000000000000,true},
{0b1101000101000000000000000,true},
{0b1101100100000000000000000,true},
{0b1110000000000000000000011,true},
{0b1110000000000000000100010,true},
{0b1110000000000000001000001,true},
{0b1110000000000000001100000,true},
{0b1110000000000010001000000,true},
{0b1110000000000100000100000,true},
{0b1110000000000110000000000,true},
{0b1110000001000100000000000,true},
{0b1110000010000010000000000,true},
{0b1110000011000000000000000,true},
{0b1110100010000000000000000,true},
{0b1111000001000000000000000,true},
{0b1111100000000000000000000,true}
};
| 36.206408 | 78 | 0.748907 | [
"vector"
] |
9e05543dc6f9e3799876659cd234ac6907374516 | 1,431 | cpp | C++ | codes/Bipartite Checking.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/Bipartite Checking.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/Bipartite Checking.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : mehrab.24csedu.001@gmail.com
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
#include<bits/stdc++.h>
using namespace std;
int n,e,i,j;
vector<vector<int> > graph;
vector<int> color;
bool vis[100011];
bool isBipartite()
{
color[0] = 1;
queue <int> q;
q.push(0);
while (!q.empty()){
int temp = q.front();
q.pop();
for (i=0;i<n;i++){
if (graph[temp][i] && color[i] == -1) {
color[i] = 1 - color[temp];
q.push(i);
}
else if (graph[temp][i] && color[i] == color[temp])
return 0;
}
}
return 1;
}
int main(){
int x,y;
cout<<"Enter number of vertices and edges respectively:";
cin>>n>>e;
cout<<"\n";
graph.resize(n);
color.resize(n,-1);
memset(vis,0,sizeof(vis));
for(i=0;i<n;i++)
graph[i].resize(n);
for(i=0;i<e;i++){
cout<<"\nEnter edge vertices of edge "<<i+1<<" :";
cin>>x>>y;
x--;
y--;
graph[x][y]=1;
graph[y][x]=1;
}
if(isBipartite())
cout<<"Yes, The given graph is Bipartite.\n";
else
cout<<"No, The given graoh is not Bipartite.\n";
return 0;
}
| 19.08 | 63 | 0.45283 | [
"vector"
] |
9e07fcf430539fa2e8e16191d60cf5867fa08146 | 1,348 | cpp | C++ | Coding Sites Submissions/udemy/WordSearch.cpp | RawRapter/CPlusPlus-Codes | 5c88fa6aaee47f6414fdfaafe8274522cb227605 | [
"MIT"
] | null | null | null | Coding Sites Submissions/udemy/WordSearch.cpp | RawRapter/CPlusPlus-Codes | 5c88fa6aaee47f6414fdfaafe8274522cb227605 | [
"MIT"
] | null | null | null | Coding Sites Submissions/udemy/WordSearch.cpp | RawRapter/CPlusPlus-Codes | 5c88fa6aaee47f6414fdfaafe8274522cb227605 | [
"MIT"
] | null | null | null | /*
Word Search
Given an MxN grid of characters board and a string word , return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are
horizontally or vertically neighboring. The same letter cell may not be used more than once.
Input:
In the function 2-D Vector of character is passed.
Output:
Return true if the word is present otherwise false.
*/
#include <bits/stdc++.h>
using namespace std;
bool chk;
void recur(vector<vector<char>>& board, string &word, int i, int j, int k)
{
if(k == word.size())
{
chk = true;
return;
}
if(i < 0 || j < 0 || i == board.size() || j == board[0].size() || board[i][j] == '-1')
return;
if(board[i][j] == word[k])
{
char c = board[i][j];
board[i][j] = '-1';
recur(board, word, i, j+1, k+1);
recur(board, word, i+1, j, k+1);
recur(board, word, i, j-1, k+1);
recur(board, word, i-1, j, k+1);
board[i][j] = c;
}
return;
}
bool wordSearch(vector<vector<char>> &board, string word)
{
chk = false;
for(int i=0; i<board.size(); i++)
{
for(int j=0; j<board[0].size(); j++)
{
if(board[i][j]==word[0])
recur(board, word, i, j, 0);
}
}
return chk;
} | 25.923077 | 98 | 0.55638 | [
"vector"
] |
9e091c0d953995f45705fc00482826a3caeddff0 | 518 | cpp | C++ | ACM Training/2018-07-02/POJ3384.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 22 | 2018-08-07T06:55:10.000Z | 2021-06-12T02:12:19.000Z | ACM Training/2018-07-02/POJ3384.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 28 | 2020-03-04T23:47:22.000Z | 2022-02-26T18:50:00.000Z | ACM Training/2018-07-02/POJ3384.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 4 | 2019-11-09T15:41:26.000Z | 2021-10-10T08:56:57.000Z | #include <cstdio>
using namespace std;
const double eps = 1e-8;
const int N = 105;
struct Vector
{
double x, y;
Vector () {}
Vector (double _x, double _y)
{
x = _x;
y = _y;
}
void Init()
{
scanf("%lf%lf", &x, &y);
}
};
struct Line
{
Vector p, v;
Line () {}
Line (Vector _p, Vector _v)
{
p = _p;
v = _v;
}
};
int n, r;
Vector p[N];
int main()
{
scanf("%d%d", n, r);
for (int i = 0; i < n; ++i)
p[i].Init();
} | 13.631579 | 33 | 0.436293 | [
"vector"
] |
9e0bf80606746ddf7bd5cb08f26dc014657234fd | 3,045 | cpp | C++ | src/CameraCalibration.cpp | mazenmel/Camera-Calib-and-Panorama-Stitching | dcf3a9fbe15aaad2860f2b4e4eff085927307746 | [
"MIT"
] | 1 | 2021-03-03T15:18:04.000Z | 2021-03-03T15:18:04.000Z | src/CameraCalibration.cpp | mazenmel/Camera-Calib-and-Panorama-Stitching | dcf3a9fbe15aaad2860f2b4e4eff085927307746 | [
"MIT"
] | null | null | null | src/CameraCalibration.cpp | mazenmel/Camera-Calib-and-Panorama-Stitching | dcf3a9fbe15aaad2860f2b4e4eff085927307746 | [
"MIT"
] | null | null | null | /*
* [2020] Computer vision course - lab 04
* All Rights Reserved.
*
* @Author Mazen Mel 1237873
*/
#include "CameraCalibration.h"
CameraCalibration::CameraCalibration(const std::string& Path, int cols, int rows, float square_size) :imagesPath{ Path },
cornersPerRow{ cols },
cornersPerCol{ rows },
squareSize{ square_size }{};
int CameraCalibration::CalibrateCamera() {
int G_ROWS;
int G_COLS;
std::vector<std::vector<cv::Point2f>> corners_2d;
std::vector<cv::Point2f> corners;
std::vector < std::string > images;
cv::Mat gray_img;
std::vector<std::vector<cv::Point3f>> corners_3d;
cv::glob(imagesPath, images);
for (int i = 0; i < images.size(); ++i) {
std::vector<cv::Point3f> temp_vec;
for (int c = 0; c < cornersPerRow; ++c) {
for (int r = 0; r < cornersPerCol; ++r) {
cv::Point3f temp_sub_vec{ c * squareSize, r * squareSize, 0.0f };
temp_vec.push_back(temp_sub_vec);
}
}
corners_3d.push_back(temp_vec);
}
for (int i = 0; i < images.size(); i++) {
cv::Mat image = cv::imread(images[i]);
if (image.empty()) {
std::cout << "ERROR cannot read the image" << std::endl;
return 0;
}
// image dimensions
G_ROWS = image.rows;
G_COLS = image.cols;
cv::cvtColor(image, gray_img, cv::COLOR_RGB2GRAY);
bool is_found = cv::findChessboardCorners(gray_img, cv::Size(cornersPerCol, cornersPerRow), corners, cv::CALIB_CB_FAST_CHECK);
if (is_found) {
//sub pixel refinment
cv::TermCriteria criteria(cv::TermCriteria::Type::EPS + cv::TermCriteria::Type::MAX_ITER, 30, 0.0001);
cv::cornerSubPix(gray_img, corners, cv::Size(5, 5), cv::Size(-1, -1), criteria);
corners_2d.push_back(corners);
}
else {
std::cout << "ERROR could not find corners" << std::endl;
return 0;
}
}
std::cout << "Calibrating camera... Please wait, it might take few minutes." << std::endl;
double reprojection_error = cv::calibrateCamera(corners_3d,corners_2d, cv::Size(G_COLS, G_ROWS),
cameraMatrix,distCoeffs, R, T);
std::cout << "Reprojection_error: " << reprojection_error << std::endl;
return 1;
}
cv::Mat CameraCalibration::GetCameraMatrix() { return cameraMatrix; }
cv::Mat CameraCalibration::GetRotation() { return R; }
cv::Mat CameraCalibration::GetTranslation() { return T; }
cv::Mat CameraCalibration::GetDistCoeffs() { return distCoeffs; } | 38.0625 | 135 | 0.518227 | [
"vector"
] |
9e0c2f102b291f199a16dcbe784485bb98922538 | 670 | hpp | C++ | sputnik/src/component/OriginDrag.hpp | SimonWallner/sputnik | d01159dfcc6f087cb312d027060f8f99395fbc41 | [
"MIT"
] | 3 | 2017-02-23T04:14:07.000Z | 2021-05-25T04:03:11.000Z | sputnik/src/component/OriginDrag.hpp | SimonWallner/sputnik | d01159dfcc6f087cb312d027060f8f99395fbc41 | [
"MIT"
] | null | null | null | sputnik/src/component/OriginDrag.hpp | SimonWallner/sputnik | d01159dfcc6f087cb312d027060f8f99395fbc41 | [
"MIT"
] | null | null | null | #ifndef SPUTNIK_COMPONENT_ORIGIN_DRAG_HPP
#define SPUTNIK_COMPONENT_ORIGIN_DRAG_HPP
#include <kocmoc-core/componentSystem/Component.hpp>
#include <kocmoc-core/component/ObjectBehaviour.hpp>
#include <glm/glm.hpp>
namespace sputnik
{
namespace component
{
/**
* Simple component/behaviour that pulls the object towards a fixed
* origin
*/
class OriginDrag : public kocmoc::core::componentSystem::Component
{
public:
OriginDrag(glm::vec3 origin, float _force = 1.0f);
glm::vec3 origin;
float force;
void init();
void onUpdate(float deltaT, float t);
private:
kocmoc::core::component::ObjectBehaviour* ob;
};
}
}
#endif
| 18.611111 | 69 | 0.720896 | [
"object"
] |
9e0cb1e81c430e7736883b4efd1f9dc7188ebafc | 3,665 | cpp | C++ | cpp/p3/source/p3/backend/OpenGLRenderTarget.cpp | mfkiwl/p3ui | 639030830cf3366e722b2a251c847972ff8df11e | [
"MIT"
] | null | null | null | cpp/p3/source/p3/backend/OpenGLRenderTarget.cpp | mfkiwl/p3ui | 639030830cf3366e722b2a251c847972ff8df11e | [
"MIT"
] | null | null | null | cpp/p3/source/p3/backend/OpenGLRenderTarget.cpp | mfkiwl/p3ui | 639030830cf3366e722b2a251c847972ff8df11e | [
"MIT"
] | null | null | null | /***************************************************************************//*/
Copyright (c) 2021 Martin Rudoff
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
/******************************************************************************/
#include <glad/gl.h>
#include <stdexcept>
#include <p3/log.h>
#include "OpenGLRenderTarget.h"
namespace p3
{
OpenGLRenderTarget::OpenGLRenderTarget(std::uint32_t width, std::uint32_t height)
: _width(width)
, _height(height)
{
glGenFramebuffers(1, &_framebuffer_id);
glGenTextures(1, &reinterpret_cast<GLuint&>(_texture_id));
glGenRenderbuffers(1, &_depth_id);
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer_id);
glBindTexture(GL_TEXTURE_2D, reinterpret_cast<GLuint const&>(_texture_id));
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
_width, _height,
0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
reinterpret_cast<GLuint const&>(_texture_id), 0);
glBindRenderbuffer(GL_RENDERBUFFER, _depth_id);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, _width, _height);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depth_id);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw std::runtime_error("failed to create render target, framebuffer incomplete");
log_debug("render target created ({}x{})", _width, _height);
}
OpenGLRenderTarget::~OpenGLRenderTarget()
{
glDeleteFramebuffers(1, &_framebuffer_id);
glDeleteTextures(1, &reinterpret_cast<GLuint&>(_texture_id));
glDeleteRenderbuffers(1, &_depth_id);
}
unsigned int OpenGLRenderTarget::framebuffer_id() const
{
return _framebuffer_id;
}
TextureId OpenGLRenderTarget::texture_id() const
{
return _texture_id;
}
void OpenGLRenderTarget::bind()
{
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer_id);
glViewport(0, 0, static_cast<GLsizei>(_width), static_cast<GLsizei>(_height));
}
void OpenGLRenderTarget::release()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
std::uint32_t OpenGLRenderTarget::width() const
{
return _width;
}
std::uint32_t OpenGLRenderTarget::height() const
{
return _height;
}
}
| 36.287129 | 104 | 0.680218 | [
"render"
] |
9e0cec4bb70d90623f45f113699a11c20d1c9fbe | 58,326 | cpp | C++ | src/nanogi.cpp | lighttransport/nano | 98cd6b40b8a5b0f96a62e631b51faf4b57c341b3 | [
"BSD-3-Clause"
] | 157 | 2015-09-03T15:16:04.000Z | 2021-12-31T06:15:21.000Z | src/nanogi.cpp | lighttransport/nano | 98cd6b40b8a5b0f96a62e631b51faf4b57c341b3 | [
"BSD-3-Clause"
] | 2 | 2015-09-23T12:32:47.000Z | 2017-08-12T07:58:59.000Z | src/nanogi.cpp | lighttransport/nano | 98cd6b40b8a5b0f96a62e631b51faf4b57c341b3 | [
"BSD-3-Clause"
] | 21 | 2015-09-06T16:56:51.000Z | 2021-10-20T22:19:44.000Z | /*
nanogi - A small, reference GI renderer
Copyright (c) 2015 Light Transport Entertainment Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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 <nanogi/macros.hpp>
#include <nanogi/basic.hpp>
#include <nanogi/rt.hpp>
#include <nanogi/bdpt.hpp>
#include <boost/program_options.hpp>
#pragma warning(push)
#pragma warning(disable:4267)
#include <ctemplate/template.h>
#pragma warning(pop)
#include <eigen3/Eigen/Dense>
using namespace nanogi;
// --------------------------------------------------------------------------------
#pragma region Renderer
enum class RendererType
{
PT,
PTDirect,
LT,
LTDirect,
BDPT,
PTMNEE,
};
const std::string RendererType_String[] =
{
"pt",
"ptdirect",
"lt",
"ltdirect",
"bdpt",
"ptmnee",
};
NGI_ENUM_TYPE_MAP(RendererType);
struct Renderer
{
RendererType Type;
int NumThreads;
long long GrainSize;
long long ProgressUpdateInterval;
double ProgressImageInterval;
double ProgressImageUpdateInterval;
std::string ProgressImageUpdateFormat;
tbb::task_scheduler_init init{tbb::task_scheduler_init::deferred};
struct
{
long long NumSamples;
double RenderTime;
int MaxNumVertices;
int Width;
int Height;
struct
{
std::string SubpathImageDir;
} BDPTStrategy;
} Params;
public:
struct Context
{
int id = -1; // Thread ID
Random rng; // Thread-specific RNG
std::vector<glm::dvec3> film; // Thread specific film
long long processedSamples = 0; // Temp for counting # of processed samples
struct
{
Path subpathL, subpathE; // BDPT subpaths
Path path; // BDPT fullpath
} BDPT;
};
public:
bool Load(const boost::program_options::variables_map& vm)
{
try
{
#pragma region Load parameters
Type = NGI_STRING_TO_ENUM(RendererType, vm["renderer"].as<std::string>());
Params.NumSamples = vm["num-samples"].as<long long>();
Params.RenderTime = vm["render-time"].as<double>();
Params.MaxNumVertices = vm["max-num-vertices"].as<int>();
Params.Width = vm["width"].as<int>();
Params.Height = vm["height"].as<int>();
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Renderer independent parameters
if (vm.count("num-threads") > 0)
{
NumThreads = vm["num-threads"].as<int>();
}
else
{
#if NGI_DEBUG_MODE
NumThreads = 1;
#else
NumThreads = 0;
#endif
}
if (NumThreads <= 0)
{
NumThreads = static_cast<int>(std::thread::hardware_concurrency()) + NumThreads;
}
init.initialize(NumThreads);
NGI_LOG_INFO("Number of threads: " + std::to_string(NumThreads));
GrainSize = vm["grain-size"].as<long long>();
NGI_LOG_INFO("Grain size: " + std::to_string(GrainSize));
ProgressUpdateInterval = vm["progress-update-interval"].as<long long>();
NGI_LOG_INFO("Progress update interval: " + std::to_string(ProgressUpdateInterval));
ProgressImageUpdateInterval = vm["progress-image-update-interval"].as<double>();
if (ProgressImageUpdateInterval > 0)
{
ProgressImageUpdateFormat = vm["progress-image-update-format"].as<std::string>();
NGI_LOG_INFO("Progress image update interval: " + std::to_string(ProgressImageUpdateInterval));
NGI_LOG_INFO("Progress image update format: " + ProgressImageUpdateFormat);
}
#pragma endregion
}
catch (boost::program_options::error& e)
{
std::cerr << "ERROR : " << e.what() << std::endl;
return false;
}
return true;
}
void Render(const Scene& scene, std::vector<glm::dvec3>& film) const
{
#pragma region Random number generator
Random initRng;
#if NGI_DEBUG_MODE
initRng.SetSeed(1008556906);
#else
initRng.SetSeed(static_cast<unsigned int>(std::time(nullptr)));
#endif
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Rendering
{
NGI_ENABLE_FP_EXCEPTION();
const auto start = std::chrono::high_resolution_clock::now();
switch (Type)
{
case RendererType::PT: { RenderProcess(scene, initRng, film, std::bind(&Renderer::ProcessSample_PT, this, std::placeholders::_1, std::placeholders::_2)); break; }
case RendererType::PTDirect: { RenderProcess(scene, initRng, film, std::bind(&Renderer::ProcessSample_PTDirect, this, std::placeholders::_1, std::placeholders::_2)); break; }
case RendererType::LT: { RenderProcess(scene, initRng, film, std::bind(&Renderer::ProcessSample_LT, this, std::placeholders::_1, std::placeholders::_2)); break; }
case RendererType::LTDirect: { RenderProcess(scene, initRng, film, std::bind(&Renderer::ProcessSample_LTDirect, this, std::placeholders::_1, std::placeholders::_2)); break; }
case RendererType::BDPT: { RenderProcess(scene, initRng, film, std::bind(&Renderer::ProcessSample_BDPT, this, std::placeholders::_1, std::placeholders::_2)); break; }
case RendererType::PTMNEE: { RenderProcess(scene, initRng, film, std::bind(&Renderer::ProcessSample_PTMNEE, this, std::placeholders::_1, std::placeholders::_2)); break; }
default: { break; }
};
const auto end = std::chrono::high_resolution_clock::now();
const double elapsed = (double)(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()) / 1000.0;
NGI_LOG_INFO("Elapesed time: " + std::to_string(elapsed));
NGI_DISABLE_FP_EXCEPTION();
}
#pragma endregion
}
using ProcessSampleFuncType = std::function<void(const Scene&, Context&)>;
void RenderProcess(const Scene& scene, Random& initRng, std::vector<glm::dvec3>& film, const ProcessSampleFuncType& processSampleFunc) const
{
#pragma region Thread local storage
tbb::enumerable_thread_specific<Context> contexts;
std::mutex contextInitMutex;
int currentThreadID = 0;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Render loop
std::atomic<long long> processedSamples(0);
long long progressImageCount = 0;
const auto renderStartTime = std::chrono::high_resolution_clock::now();
auto prevImageUpdateTime = renderStartTime;
const long long NumSamples = Params.RenderTime < 0 ? Params.NumSamples : GrainSize * 1000;
while (true)
{
#pragma region Helper function
const auto ProcessProgress = [&](Context& ctx) -> void
{
processedSamples += ctx.processedSamples;
ctx.processedSamples = 0;
if (Params.RenderTime < 0)
{
if (ctx.id == 0)
{
const double progress = (double)(processedSamples) / Params.NumSamples * 100.0;
NGI_LOG_INPLACE(boost::str(boost::format("Progress: %.1f%%") % progress));
}
}
else
{
if (ctx.id == 0)
{
const auto currentTime = std::chrono::high_resolution_clock::now();
const double elapsed = (double)(std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - renderStartTime).count()) / 1000.0;
const double progress = elapsed / Params.RenderTime * 100.0;
NGI_LOG_INPLACE(boost::str(boost::format("Progress: %.1f%% (%.1fs / %.1fs)") % progress % elapsed % Params.RenderTime));
}
}
};
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Parallel loop
std::atomic<bool> done(false);
tbb::parallel_for(tbb::blocked_range<long long>(0, NumSamples, GrainSize), [&](const tbb::blocked_range<long long>& range) -> void
{
if (done)
{
return;
}
// --------------------------------------------------------------------------------
#pragma region Thread local storage
auto& ctx = contexts.local();
if (ctx.id < 0)
{
std::unique_lock<std::mutex> lock(contextInitMutex);
ctx.id = currentThreadID++;
ctx.rng.SetSeed(initRng.NextUInt());
ctx.film.assign(Params.Width * Params.Height, glm::dvec3());
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample loop
for (long long sample = range.begin(); sample != range.end(); sample++)
{
// Process sample
processSampleFunc(scene, ctx);
// Report progress
ctx.processedSamples++;
if (ctx.processedSamples > ProgressUpdateInterval)
{
ProcessProgress(ctx);
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Check termination
if (Params.RenderTime > 0)
{
const auto currentTime = std::chrono::high_resolution_clock::now();
const double elapsed = (double)(std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - renderStartTime).count()) / 1000.0;
if (elapsed > Params.RenderTime)
{
done = true;
}
}
#pragma endregion
});
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Add remaining processed samples
for (auto& ctx : contexts)
{
ProcessProgress(ctx);
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Progress update of intermediate image
if (ProgressImageUpdateInterval > 0)
{
const auto currentTime = std::chrono::high_resolution_clock::now();
const double elapsed = (double)(std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - prevImageUpdateTime).count()) / 1000.0;
if (elapsed > ProgressImageUpdateInterval)
{
// Gather film data
film.assign(Params.Width * Params.Height, glm::dvec3());
contexts.combine_each([&](const Context& ctx)
{
std::transform(film.begin(), film.end(), ctx.film.begin(), film.begin(), std::plus<glm::dvec3>());
});
for (auto& v : film)
{
v *= (double)(Params.Width * Params.Height) / processedSamples;
}
// Output path
progressImageCount++;
std::string path;
{
namespace ct = ctemplate;
ct::TemplateDictionary dict("dict");
dict["count"] = boost::str(boost::format("%010d") % progressImageCount);
std::string output;
auto* tpl = ct::Template::StringToTemplate(ProgressImageUpdateFormat, ct::DO_NOT_STRIP);
if (!tpl->Expand(&output, &dict))
{
NGI_LOG_ERROR("Failed to expand template");
path = ProgressImageUpdateFormat;
}
else
{
path = output;
}
}
// Save image
{
NGI_LOG_INFO("Saving progress: ");
NGI_LOG_INDENTER();
SaveImage(path, film, Params.Width, Params.Height);
}
// Update time
prevImageUpdateTime = currentTime;
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Exit condition
if (Params.RenderTime < 0 || done)
{
break;
}
#pragma endregion
}
NGI_LOG_INFO("Progress: 100.0%");
NGI_LOG_INFO(boost::str(boost::format("# of samples: %d") % processedSamples));
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Gather film data
film.assign(Params.Width * Params.Height, glm::dvec3());
contexts.combine_each([&](const Context& ctx)
{
std::transform(film.begin(), film.end(), ctx.film.begin(), film.begin(), std::plus<glm::dvec3>());
});
for (auto& v : film)
{
v *= (double)(Params.Width * Params.Height) / processedSamples;
}
#pragma endregion
}
private:
#pragma region Process sample
void ProcessSample_PT(const Scene& scene, Context& ctx) const
{
#pragma region Sample a sensor
const auto* E = scene.SampleEmitter(PrimitiveType::E, ctx.rng.Next());
const double pdfE = scene.EvaluateEmitterPDF(E);
assert(pdfE > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample a position on the sensor
SurfaceGeometry geomE;
E->SamplePosition(ctx.rng.Next2D(), geomE);
const double pdfPE = E->EvaluatePositionPDF(geomE, true);
assert(pdfPE > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Temporary variables
auto throughput = E->EvaluatePosition(geomE, true) / pdfPE / pdfE;
const auto* prim = E;
int type = PrimitiveType::E;
auto geom = geomE;
glm::dvec3 wi;
int pixelIndex = -1;
int numVertices = 1;
#pragma endregion
// --------------------------------------------------------------------------------
while (true)
{
if (Params.MaxNumVertices != -1 && numVertices >= Params.MaxNumVertices)
{
break;
}
// --------------------------------------------------------------------------------
#pragma region Sample direction
glm::dvec3 wo;
prim->SampleDirection(ctx.rng.Next2D(), ctx.rng.Next(), type, geom, wi, wo);
const double pdfD = prim->EvaluateDirectionPDF(geom, type, wi, wo, true);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Calculate pixel index for initial vertex
if (type == PrimitiveType::E)
{
#pragma region Calculate raster position
glm::dvec2 rasterPos;
if (!prim->RasterPosition(wo, geom, rasterPos))
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Pixel position
pixelIndex = PixelIndex(rasterPos, Params.Width, Params.Height);
#pragma endregion
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate direction
const auto fs = prim->EvaluateDirection(geom, type, wi, wo, TransportDirection::EL, true);
if (fs == glm::dvec3())
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update throughput
assert(pdfD > 0);
throughput *= fs / pdfD;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Intersection
// Setup next ray
Ray ray = { geom.p, wo };
// Intersection query
Intersection isect;
if (!scene.Intersect(ray, isect))
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Handle hit with light source
if ((isect.Prim->Type & PrimitiveType::L) > 0)
{
// Accumulate to film
ctx.film[pixelIndex] +=
throughput
* isect.Prim->EvaluateDirection(isect.geom, PrimitiveType::L, glm::dvec3(), -ray.d, TransportDirection::EL, false)
* isect.Prim->EvaluatePosition(isect.geom, false);
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Path termination
double rrProb = 0.5;
if (ctx.rng.Next() > rrProb)
{
break;
}
else
{
throughput /= rrProb;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update information
geom = isect.geom;
prim = isect.Prim;
type = isect.Prim->Type & ~PrimitiveType::Emitter;
wi = -ray.d;
numVertices++;
#pragma endregion
}
}
void ProcessSample_PTDirect(const Scene& scene, Context& ctx) const
{
#pragma region Sample a sensor
const auto* E = scene.SampleEmitter(PrimitiveType::E, ctx.rng.Next());
const double pdfE = scene.EvaluateEmitterPDF(E);
assert(pdfE > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample a position on the sensor
SurfaceGeometry geomE;
E->SamplePosition(ctx.rng.Next2D(), geomE);
const double pdfPE = E->EvaluatePositionPDF(geomE, true);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Temporary variables
auto throughput = E->EvaluatePosition(geomE, true) / pdfPE / pdfE;
const auto* prim = E;
int type = PrimitiveType::E;
auto geom = geomE;
glm::dvec3 wi;
int pixelIndex = -1;
int numVertices = 1;
#pragma endregion
// --------------------------------------------------------------------------------
while (true)
{
if (Params.MaxNumVertices != -1 && numVertices >= Params.MaxNumVertices)
{
break;
}
// --------------------------------------------------------------------------------
#pragma region Direct light sampling
{
#pragma region Sample a light
const auto* L = scene.SampleEmitter(PrimitiveType::L, ctx.rng.Next());
const double pdfL = scene.EvaluateEmitterPDF(L);
assert(pdfL > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample a position on the light
SurfaceGeometry geomL;
L->SamplePosition(ctx.rng.Next2D(), geomL);
const double pdfPL = L->EvaluatePositionPDF(geomL, true);
assert(pdfPL > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate contribution
const auto ppL = glm::normalize(geomL.p - geom.p);
const auto fsE = prim->EvaluateDirection(geom, type, wi, ppL, TransportDirection::EL, false);
const auto fsL = L->EvaluateDirection(geomL, PrimitiveType::L, glm::dvec3(), -ppL, TransportDirection::LE, false);
const auto G = GeometryTerm(geom, geomL);
const auto V = scene.Visible(geom.p, geomL.p) ? 1.0 : 0.0;
const auto LeP = L->EvaluatePosition(geomL, true);
const auto C = throughput * fsE * G * V * fsL * LeP / pdfL / pdfPL;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Record to film
if (C != glm::dvec3())
{
// Recompute pixel index if necessary
int index = pixelIndex;
if (type == PrimitiveType::E)
{
glm::dvec2 rasterPos;
prim->RasterPosition(ppL, geom, rasterPos);
index = PixelIndex(rasterPos, Params.Width, Params.Height);
}
// Accumulate to film
ctx.film[index] += C;
}
#pragma endregion
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample next direction
glm::dvec3 wo;
prim->SampleDirection(ctx.rng.Next2D(), ctx.rng.Next(), type, geom, wi, wo);
const double pdfD = prim->EvaluateDirectionPDF(geom, type, wi, wo, true);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Calculate pixel index for initial vertex
if (type == PrimitiveType::E)
{
glm::dvec2 rasterPos;
if (!prim->RasterPosition(wo, geom, rasterPos)) { break; }
pixelIndex = PixelIndex(rasterPos, Params.Width, Params.Height);
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate direction
const auto fs = prim->EvaluateDirection(geom, type, wi, wo, TransportDirection::EL, true);
if (fs == glm::dvec3())
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update throughput
assert(pdfD > 0);
throughput *= fs / pdfD;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Intersection
// Setup next ray
Ray ray = { geom.p, wo };
// Intersection query
Intersection isect;
if (!scene.Intersect(ray, isect))
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Path termination
double rrProb = 0.5;
if (ctx.rng.Next() > rrProb)
{
break;
}
else
{
throughput /= rrProb;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update information
geom = isect.geom;
prim = isect.Prim;
type = isect.Prim->Type & ~PrimitiveType::Emitter;
wi = -ray.d;
numVertices++;
#pragma endregion
}
}
void ProcessSample_LT(const Scene& scene, Context& ctx) const
{
#pragma region Sample a light
const auto* L = scene.SampleEmitter(PrimitiveType::L, ctx.rng.Next());
const double pdfL = scene.EvaluateEmitterPDF(L);
assert(pdfL > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample a position on the light
SurfaceGeometry geomL;
L->SamplePosition(ctx.rng.Next2D(), geomL);
const double pdfPL = L->EvaluatePositionPDF(geomL, true);
assert(pdfPL > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Temporary variables
auto throughput = L->EvaluatePosition(geomL, true) / pdfPL / pdfL;
const auto* prim = L;
int type = PrimitiveType::L;
auto geom = geomL;
glm::dvec3 wi;
int numVertices = 1;
#pragma endregion
// --------------------------------------------------------------------------------
while (true)
{
if (Params.MaxNumVertices != -1 && numVertices >= Params.MaxNumVertices)
{
break;
}
// --------------------------------------------------------------------------------
#pragma region Sample direction
glm::dvec3 wo;
prim->SampleDirection(ctx.rng.Next2D(), ctx.rng.Next(), type, geom, wi, wo);
const double pdfD = prim->EvaluateDirectionPDF(geom, type, wi, wo, true);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate direction
const auto fs = prim->EvaluateDirection(geom, type, wi, wo, TransportDirection::LE, true);
if (fs == glm::dvec3())
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update throughput
assert(pdfD > 0);
throughput *= fs / pdfD;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Intersection
// Setup next ray
Ray ray = { geom.p, wo };
// Intersection query
Intersection isect;
if (!scene.Intersect(ray, isect))
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Handle hit with sensor
if ((isect.Prim->Type & PrimitiveType::E) > 0)
{
#pragma region Calculate raster position
glm::dvec2 rasterPos;
if (!isect.Prim->RasterPosition(-wo, isect.geom, rasterPos))
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Accumulate to film
const int pixelIndex = PixelIndex(rasterPos, Params.Width, Params.Height);
ctx.film[pixelIndex] +=
throughput
* isect.Prim->EvaluateDirection(isect.geom, PrimitiveType::E, glm::dvec3(), -ray.d, TransportDirection::LE, false)
* isect.Prim->EvaluatePosition(isect.geom, false);
#pragma endregion
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Path termination
double rrProb = 0.5;
if (ctx.rng.Next() > rrProb)
{
break;
}
else
{
throughput /= rrProb;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update information
geom = isect.geom;
prim = isect.Prim;
type = isect.Prim->Type & ~PrimitiveType::Emitter;
wi = -ray.d;
numVertices++;
#pragma endregion
}
}
void ProcessSample_LTDirect(const Scene& scene, Context& ctx) const
{
#pragma region Sample a light
const auto* L = scene.SampleEmitter(PrimitiveType::L, ctx.rng.Next());
const double pdfL = scene.EvaluateEmitterPDF(L);
assert(pdfL > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample a position on the light
SurfaceGeometry geomL;
L->SamplePosition(ctx.rng.Next2D(), geomL);
const double pdfPL = L->EvaluatePositionPDF(geomL, true);
assert(pdfPL > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Temporary variables
auto throughput = L->EvaluatePosition(geomL, true) / pdfPL / pdfL;
const auto* prim = L;
int type = PrimitiveType::L;
auto geom = geomL;
glm::dvec3 wi;
int numVertices = 1;
#pragma endregion
// --------------------------------------------------------------------------------
while (true)
{
if (Params.MaxNumVertices != -1 && numVertices >= Params.MaxNumVertices)
{
break;
}
// --------------------------------------------------------------------------------
#pragma region Direct sensor sampling
{
#pragma region Sample a sensor
const auto* E = scene.SampleEmitter(PrimitiveType::E, ctx.rng.Next());
const double pdfE = scene.EvaluateEmitterPDF(E);
assert(pdfE > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample a position on the sensor
SurfaceGeometry geomE;
E->SamplePosition(ctx.rng.Next2D(), geomE);
const double pdfPE = L->EvaluatePositionPDF(geomE, true);
assert(pdfPE > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate contribution
const auto ppE = glm::normalize(geomE.p - geom.p);
const auto fsL = prim->EvaluateDirection(geom, type, wi, ppE, TransportDirection::LE, false);
const auto fsE = E->EvaluateDirection(geomE, PrimitiveType::E, glm::dvec3(), -ppE, TransportDirection::EL, false);
const auto G = GeometryTerm(geom, geomE);
const auto V = scene.Visible(geom.p, geomE.p) ? 1.0 : 0.0;
const auto LeP = L->EvaluatePosition(geomE, true);
const auto C = throughput * fsL * G * V * fsE * LeP / pdfE / pdfPE;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Record to film
if (C != glm::dvec3())
{
// Pixel index
glm::dvec2 rasterPos;
E->RasterPosition(-ppE, geomE, rasterPos);
int index = PixelIndex(rasterPos, Params.Width, Params.Height);
// Accumulate to film
ctx.film[index] += C;
}
#pragma endregion
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Sample next direction
glm::dvec3 wo;
prim->SampleDirection(ctx.rng.Next2D(), ctx.rng.Next(), type, geom, wi, wo);
const double pdfD = prim->EvaluateDirectionPDF(geom, type, wi, wo, true);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate direction
const auto fs = prim->EvaluateDirection(geom, type, wi, wo, TransportDirection::LE, true);
if (fs == glm::dvec3())
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update throughput
assert(pdfD > 0);
throughput *= fs / pdfD;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Intersection
// Setup next ray
Ray ray = { geom.p, wo };
// Intersection query
Intersection isect;
if (!scene.Intersect(ray, isect))
{
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Path termination
double rrProb = 0.5;
if (ctx.rng.Next() > rrProb)
{
break;
}
else
{
throughput /= rrProb;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update information
geom = isect.geom;
prim = isect.Prim;
type = isect.Prim->Type & ~PrimitiveType::Emitter;
wi = -ray.d;
numVertices++;
#pragma endregion
}
}
void ProcessSample_BDPT(const Scene& scene, Context& ctx) const
{
#pragma region Sample subpaths
ctx.BDPT.subpathL.SampleSubpath(scene, ctx.rng, TransportDirection::LE, Params.MaxNumVertices);
ctx.BDPT.subpathE.SampleSubpath(scene, ctx.rng, TransportDirection::EL, Params.MaxNumVertices);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate path combinations
const int nL = static_cast<int>(ctx.BDPT.subpathL.vertices.size());
const int nE = static_cast<int>(ctx.BDPT.subpathE.vertices.size());
for (int n = 2; n <= nE + nL; n++)
{
if (Params.MaxNumVertices != -1 && n > Params.MaxNumVertices)
{
continue;
}
// --------------------------------------------------------------------------------
const int minS = glm::max(0, n - nE);
const int maxS = glm::min(nL, n);
for (int s = minS; s <= maxS; s++)
{
#pragma region Connect subpaths & create fullpath
const int t = n - s;
if (!ctx.BDPT.path.Connect(scene, s, t, ctx.BDPT.subpathL, ctx.BDPT.subpathE))
{
continue;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate contribution
const auto C = ctx.BDPT.path.EvaluateContribution(scene, s) / ctx.BDPT.path.SelectionProb(s);
if (C == glm::dvec3())
{
continue;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Accumulate to film
ctx.film[PixelIndex(ctx.BDPT.path.RasterPosition(), Params.Width, Params.Height)] += C;
#pragma endregion
}
}
#pragma endregion
}
void ProcessSample_PTMNEE(const Scene& scene, Context& ctx) const
{
Path path;
for (int step = 0; Params.MaxNumVertices == -1 || step < Params.MaxNumVertices - 1; step++)
{
if (step == 0)
{
#pragma region Sample initial vertex
PathVertex v;
// Sample an emitter
const auto* emitter = scene.SampleEmitter(PrimitiveType::E, ctx.rng.Next());
v.primitive = emitter;
v.type = PrimitiveType::E;
// Sample a position on the emitter
emitter->SamplePosition(ctx.rng.Next2D(), v.geom);
// Create a vertex
path.vertices.push_back(v);
#pragma endregion
}
else
{
#pragma region Sample intermediate vertex
// Previous & two before vertex
const auto* pv = &path.vertices.back();
const auto* ppv = path.vertices.size() > 1 ? &path.vertices[path.vertices.size() - 2] : nullptr;
// Sample a next direction
glm::dvec3 wo;
const auto wi = ppv ? glm::normalize(ppv->geom.p - pv->geom.p) : glm::dvec3();
pv->primitive->SampleDirection(ctx.rng.Next2D(), ctx.rng.Next(), pv->type, pv->geom, wi, wo);
// Intersection query
Ray ray = { pv->geom.p, wo };
Intersection isect;
if (!scene.Intersect(ray, isect))
{
break;
}
// Set vertex information
PathVertex v;
v.geom = isect.geom;
v.primitive = isect.Prim;
v.type = isect.Prim->Type & ~PrimitiveType::Emitter;
path.vertices.push_back(v);
#pragma endregion
}
// --------------------------------------------------------------------------------
#pragma region Apply NEE or MNEE
if ((path.vertices.back().type & (PrimitiveType::D | PrimitiveType::E)) > 0)
{
#pragma region Sample a seed path
const auto SampleSeedPath = [&scene, &ctx](const Path& path, Path& seedPath) -> bool
{
seedPath.vertices.clear();
// --------------------------------------------------------------------------------
#pragma region Sample a light
PathVertex vL;
{
// Sample a light
const auto* L = scene.SampleEmitter(PrimitiveType::L, ctx.rng.Next());
// Sample a position on the light (x_c in the paper)
SurfaceGeometry geomL;
L->SamplePosition(ctx.rng.Next2D(), geomL);
vL.geom = geomL;
vL.primitive = L;
vL.type = PrimitiveType::L;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Count the number of specular surfaces between x_b and x_c
int countS = 0;
{
auto currP = path.vertices.back().geom.p;
while (true)
{
// Intersection query
Ray ray = { currP, glm::normalize(vL.geom.p - currP) };
Intersection isect;
if (!scene.Intersect(ray, isect, EpsF, (1.0f - EpsF) * (float)(glm::length(vL.geom.p - currP))))
{
break;
}
// --------------------------------------------------------------------------------
// If a vertex with non-specular surface, stop the chain
if ((isect.Prim->Type & PrimitiveType::S) == 0)
{
return false;
}
// --------------------------------------------------------------------------------
// Update information
countS++;
currP = isect.geom.p;
}
}
// If countS is zero, it is the case with NEE
if (countS == 0)
{
seedPath.vertices.push_back(vL);
return true;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Projection to specular manifold
seedPath.vertices.push_back(vL);
for (int i = 0; i < countS + 1; i++)
{
// Previous & two before vertex
const auto* pv = &seedPath.vertices.back();
const auto* ppv = seedPath.vertices.size() > 1 ? &seedPath.vertices[seedPath.vertices.size() - 2] : nullptr;
// --------------------------------------------------------------------------------
// Next direction
glm::dvec3 wo;
if (ppv)
{
assert(pv->type == PrimitiveType::S);
const auto wi = glm::normalize(ppv->geom.p - pv->geom.p);
pv->primitive->SampleDirection(glm::dvec2(), 0, pv->type, pv->geom, wi, wo);
}
else
{
// Initial direction is fixed to x_c to x_b
wo = glm::normalize(path.vertices.back().geom.p - vL.geom.p);
}
// --------------------------------------------------------------------------------
// Intersection query
Ray ray = { pv->geom.p, wo };
Intersection isect;
if (!scene.Intersect(ray, isect))
{
return false;
}
// --------------------------------------------------------------------------------
if (i == countS)
{
// Failed if the last vertex is not 'D'
if ((isect.Prim->Type & PrimitiveType::D) == 0) { return false; }
}
else
{
// Failed if 'S' is not found
if ((isect.Prim->Type & PrimitiveType::S) == 0) { return false; }
}
// --------------------------------------------------------------------------------
// Add a vertex
PathVertex v;
v.geom = isect.geom;
v.primitive = isect.Prim;
v.type = isect.Prim->Type & ~PrimitiveType::Emitter;
seedPath.vertices.push_back(v);
}
// Number of vertices must be countS + 2
assert(seedPath.vertices.size() == countS + 2);
#pragma endregion
// --------------------------------------------------------------------------------
return true;
};
Path seedPath;
if (!SampleSeedPath(path, seedPath))
{
continue;
}
assert(seedPath.vertices.size() >= 1);
if (seedPath.vertices.size() > 1 && (int)(path.vertices.size() + seedPath.vertices.size() - 1) > Params.MaxNumVertices)
{
continue;
}
#pragma endregion
// --------------------------------------------------------------------------------
if (seedPath.vertices.size() == 1)
{
#pragma region Case with NEE
Path evalPath = path;
evalPath.vertices.push_back(seedPath.vertices[0]);
std::reverse(evalPath.vertices.begin(), evalPath.vertices.end());
ctx.film[PixelIndex(evalPath.RasterPosition(), Params.Width, Params.Height)] += evalPath.EvaluateUnweightContribution(scene, 1);
#pragma endregion
}
else
{
#pragma region Case with MNEE
{
#pragma region Manifold walk
Path optPath;
if (!WalkManifold(scene, seedPath, path.vertices.back().geom.p, optPath))
{
continue;
}
Path revOptPath;
if (!WalkManifold(scene, optPath, seedPath.vertices.back().geom.p, revOptPath))
{
continue;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Evaluate contribution
{
#pragma region Compute throughput
glm::dvec3 throughputE;
{
const auto LocalContrb = [](const glm::dvec3& f, double p) -> glm::dvec3
{
assert(p != 0 || (p == 0 && f == glm::dvec3()));
if (f == glm::dvec3()) return glm::dvec3();
return f / p;
};
const auto& v = path.vertices[0];
throughputE = LocalContrb(v.primitive->EvaluatePosition(v.geom, true), v.primitive->EvaluatePositionPDF(v.geom, true) * scene.EvaluateEmitterPDF(v.primitive));
for (size_t i = 0; i < path.vertices.size() - 1; i++)
{
const auto* v = &path.vertices[i];
const auto* vPrev = i >= 1 ? &path.vertices[i - 1] : nullptr;
const auto* vNext = &path.vertices[i + 1];
const auto wi = vPrev ? glm::normalize(vPrev->geom.p - v->geom.p) : glm::dvec3();
const auto wo = glm::normalize(vNext->geom.p - v->geom.p);
throughputE *= LocalContrb(v->primitive->EvaluateDirection(v->geom, v->type, wi, wo, TransportDirection::EL, true), v->primitive->EvaluateDirectionPDF(v->geom, v->type, wi, wo, true));
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute Fs, fsE, fsL, LeP
glm::dvec3 Fs(1);
{
const int n = (int)(optPath.vertices.size());
for (int i = n-2; i >= 1; i--)
{
const auto& v = &optPath.vertices[i];
const auto& vp = &optPath.vertices[i + 1];
const auto& vn = &optPath.vertices[i - 1];
Fs *= v->primitive->EvaluateDirection(v->geom, v->type, glm::normalize(vp->geom.p - v->geom.p), glm::normalize(vn->geom.p - v->geom.p), TransportDirection::EL, true);
}
}
glm::dvec3 fsE;
{
const auto& vE = path.vertices[path.vertices.size()-1];
const auto& vEp = path.vertices[path.vertices.size()-2];
const auto& vEn = optPath.vertices[optPath.vertices.size()-2];
fsE = vE.primitive->EvaluateDirection(vE.geom, vE.type, glm::normalize(vEp.geom.p - vE.geom.p), glm::normalize(vEn.geom.p - vE.geom.p), TransportDirection::EL, true);
}
glm::dvec3 fsL;
{
const auto& vL = optPath.vertices[0];
const auto& vLn = optPath.vertices[1];
fsL = vL.primitive->EvaluateDirection(vL.geom, vL.type, glm::dvec3(), glm::normalize(vLn.geom.p - vL.geom.p), TransportDirection::LE, true);
}
glm::dvec3 LeP;
{
const auto& vL = optPath.vertices[0];
LeP = vL.primitive->EvaluatePosition(vL.geom, true);
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute Jacobian
double J = 1;
{
const int n = (int)(optPath.vertices.size());
ConstraintJacobian nablaC(n - 2);
ComputeConstraintJacobian(optPath, nablaC);
const double Det = ComputeConstraintJacobianDeterminant(nablaC);
J *= Det;
const double G = GeometryTerm(optPath.vertices[0].geom, optPath.vertices[1].geom);
J *= G;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute PDFs
double pdfL;
double pdfPL;
{
const auto& vL = optPath.vertices[0];
pdfL = scene.EvaluateEmitterPDF(vL.primitive);
pdfPL = vL.primitive->EvaluatePositionPDF(vL.geom, true);
}
assert(pdfL > 0);
assert(pdfPL > 0);
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute contribution & Accumulate to film
// Contribution
const auto C = throughputE * fsE * Fs * fsL * LeP * J / pdfL / pdfPL;
// Pixel index
int index;
{
glm::dvec2 rasterPos;
const auto& vE = path.vertices[0];
const auto& vEn = path.vertices[1];
vE.primitive->RasterPosition(glm::normalize(vEn.geom.p - vE.geom.p), vE.geom, rasterPos);
index = PixelIndex(rasterPos, Params.Width, Params.Height);
}
// Accumulate to film
ctx.film[index] += C;
#pragma endregion
}
#pragma endregion
}
#pragma endregion
}
}
#pragma endregion
}
}
#pragma endregion
private:
#pragma region MNEE specific functions
struct VertexConstraintJacobian
{
glm::dmat2 A;
glm::dmat2 B;
glm::dmat2 C;
};
typedef std::vector<VertexConstraintJacobian> ConstraintJacobian;
void ComputeConstraintJacobian(const Path& path, ConstraintJacobian& nablaC) const
{
const int n = (int)(path.vertices.size());
for (int i = 1; i < n - 1; i++)
{
#pragma region Some precomputation
const auto& x = path.vertices[i].geom;
const auto& xp = path.vertices[i-1].geom;
const auto& xn = path.vertices[i+1].geom;
const auto wi = glm::normalize(xp.p - x.p);
const auto wo = glm::normalize(xn.p - x.p);
const auto H = glm::normalize(wi + wo);
const double inv_wiL = 1.0 / glm::length(xp.p - x.p);
const double inv_woL = 1.0 / glm::length(xn.p - x.p);
const double inv_HL = 1.0 / glm::length(wi + wo);
const double dot_H_n = glm::dot(x.sn, H);
const double dot_H_dndu = glm::dot(x.dndu, H);
const double dot_H_dndv = glm::dot(x.dndv, H);
const double dot_u_n = glm::dot(x.dpdu, x.sn);
const double dot_v_n = glm::dot(x.dpdv, x.sn);
const auto s = x.dpdu - dot_u_n * x.sn;
const auto t = x.dpdv - dot_v_n * x.sn;
const double div_inv_wiL_HL = inv_wiL * inv_HL;
const double div_inv_woL_HL = inv_woL * inv_HL;
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute $A_i$ (derivative w.r.t. $x_{i-1}$)
{
const auto tu = (xp.dpdu - wi * glm::dot(wi, xp.dpdu)) * div_inv_wiL_HL;
const auto tv = (xp.dpdv - wi * glm::dot(wi, xp.dpdv)) * div_inv_wiL_HL;
const auto dHdu = tu - H * glm::dot(tu, H);
const auto dHdv = tv - H * glm::dot(tv, H);
nablaC[i-1].A = glm::dmat2(
glm::dot(dHdu, s), glm::dot(dHdu, t),
glm::dot(dHdv, s), glm::dot(dHdv, t));
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute $B_i$ (derivative w.r.t. $x_i$)
{
const auto tu = -x.dpdu * (div_inv_wiL_HL + div_inv_woL_HL) + wi * (glm::dot(wi, x.dpdu) * div_inv_wiL_HL) + wo * (glm::dot(wo, x.dpdu) * div_inv_woL_HL);
const auto tv = -x.dpdv * (div_inv_wiL_HL + div_inv_woL_HL) + wi * (glm::dot(wi, x.dpdv) * div_inv_wiL_HL) + wo * (glm::dot(wo, x.dpdv) * div_inv_woL_HL);
const auto dHdu = tu - H * glm::dot(tu, H);
const auto dHdv = tv - H * glm::dot(tv, H);
nablaC[i-1].B = glm::dmat2(
glm::dot(dHdu, s) - glm::dot(x.dpdu, x.dndu) * dot_H_n - dot_u_n * dot_H_dndu,
glm::dot(dHdu, t) - glm::dot(x.dpdv, x.dndu) * dot_H_n - dot_v_n * dot_H_dndu,
glm::dot(dHdv, s) - glm::dot(x.dpdu, x.dndv) * dot_H_n - dot_u_n * dot_H_dndv,
glm::dot(dHdv, t) - glm::dot(x.dpdv, x.dndv) * dot_H_n - dot_v_n * dot_H_dndv);
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute $C_i$ (derivative w.r.t. $x_{i+1}$)
{
const auto tu = (xn.dpdu - wo * glm::dot(wo, xn.dpdu)) * div_inv_woL_HL;
const auto tv = (xn.dpdv - wo * glm::dot(wo, xn.dpdv)) * div_inv_woL_HL;
const auto dHdu = tu - H * glm::dot(tu, H);
const auto dHdv = tv - H * glm::dot(tv, H);
nablaC[i - 1].C = glm::dmat2(
glm::dot(dHdu, s), glm::dot(dHdu, t),
glm::dot(dHdv, s), glm::dot(dHdv, t));
}
#pragma endregion
}
}
double ComputeConstraintJacobianDeterminant(const ConstraintJacobian& nablaC) const
{
const int n = (int)(nablaC.size());
// $A$
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A(2*n, 2*n);
A.setZero();
for (int i = 0; i < n; i++)
{
if (i > 0)
{
A(2*i+0, 2*(i-1)+0) = nablaC[i].A[0][0];
A(2*i+0, 2*(i-1)+1) = nablaC[i].A[1][0];
A(2*i+1, 2*(i-1)+0) = nablaC[i].A[0][1];
A(2*i+1, 2*(i-1)+1) = nablaC[i].A[1][1];
}
A(2*i+0, 2*i+0) = nablaC[i].B[0][0];
A(2*i+0, 2*i+1) = nablaC[i].B[1][0];
A(2*i+1, 2*i+0) = nablaC[i].B[0][1];
A(2*i+1, 2*i+1) = nablaC[i].B[1][1];
if (i < n - 1)
{
A(2*i+0, 2*(i+1)+0) = nablaC[i+1].C[0][0];
A(2*i+0, 2*(i+1)+1) = nablaC[i+1].C[1][0];
A(2*i+1, 2*(i+1)+0) = nablaC[i+1].C[0][1];
A(2*i+1, 2*(i+1)+1) = nablaC[i+1].C[1][1];
}
}
// $A^-1$
const decltype(A) invA = A.inverse();
// $P_2 A^-1 B_{n}$
const auto Bn_n1p = nablaC[n - 1].C;
glm::dmat2 invA_0_n1p;
invA_0_n1p[0][0] = invA(0, 2*n-2);
invA_0_n1p[0][1] = invA(1, 2*n-2);
invA_0_n1p[1][0] = invA(0, 2*n-1);
invA_0_n1p[1][1] = invA(1, 2*n-1);
return glm::determinant(invA_0_n1p * Bn_n1p);
}
void SolveBlockLinearEq(const ConstraintJacobian& nablaC, const std::vector<glm::dvec2>& V, std::vector<glm::dvec2>& W) const
{
const int n = (int)(nablaC.size());
assert(V.size() == nablaC.size());
// --------------------------------------------------------------------------------
#pragma region LU decomposition
// A'_{0,n-1} = B_{0,n-1}
// B'_{0,n-2} = C_{0,n-2}
// C'_{0,n-2} = A_{1,n-1}
std::vector<glm::dmat2> L(n);
std::vector<glm::dmat2> U(n);
{
// $U_1 = A'_1$
U[0] = nablaC[0].B;
for (int i = 1; i < n; i++)
{
L[i] = nablaC[i].A * glm::inverse(U[i-1]); // $L_i = C'_i U_{i-1}^-1$
U[i] = nablaC[i].B - L[i] * nablaC[i-1].C; // $U_i = A'_i - L_i * B'_{i-1}$
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Forward substitution
// Solve $L V' = V$
std::vector<glm::dvec2> Vp(n);
Vp[0] = V[0];
for (int i = 1; i < n; i++)
{
// V'_i = V_i - L_i V'_{i-1}
Vp[i] = V[i] - L[i] * Vp[i - 1];
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Backward substitution
W.assign(n, glm::dvec2());
// Solve $U_n W_n = V'_n$
W[n - 1] = glm::inverse(U[n - 1]) * Vp[n - 1];
for (int i = n - 2; i >= 0; i--)
{
// Solve $U_i W_i = V'_i - V_i W_{i+1}$
W[i] = glm::inverse(U[i]) * (Vp[i] - V[i] * W[i + 1]);
}
#pragma endregion
}
bool WalkManifold(const Scene& scene, const Path& seedPath, const glm::dvec3& target, Path& outPath) const
{
#pragma region Preprocess
// Number of path vertices
const int n = (int)(seedPath.vertices.size());
// Initial path
Path currPath = seedPath;
// Compute $\nabla C$
ConstraintJacobian nablaC(n - 2);
ComputeConstraintJacobian(currPath, nablaC);
// Compute $L$
double L = 0;
for (const auto& x : currPath.vertices)
{
L = glm::max(L, glm::length(x.geom.p));
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Optimization loop
int iter = 0;
const double MaxBeta = 100.0;
double beta = MaxBeta;
const double Eps = 10e-5;
const int MaxIter = 30;
bool converged = false;
while (true)
{
#pragma region Stop condition
if (iter++ >= MaxIter)
{
break;
}
if (glm::length(currPath.vertices[n - 1].geom.p - target) < Eps * L)
{
converged = true;
break;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Compute movement in tangement plane
// New position of initial specular vertex
glm::dvec3 p;
{
// $x_n$, $x'_n$
const auto& xn = currPath.vertices[n - 1].geom.p;
const auto& xnp = target;
// $T(x_n)^T$
const glm::dmat3x2 TxnT = glm::transpose(glm::dmat2x3(currPath.vertices[n - 1].geom.dpdu, currPath.vertices[n - 1].geom.dpdv));
// $V \equiv B_n T(x_n)^T (x'_n - x)$
const auto Bn_n2p = nablaC[n - 3].C;
const auto V_n2p = Bn_n2p * TxnT * (xnp - xn);
// Solve $AW = V$
std::vector<glm::dvec2> V(n - 2);
std::vector<glm::dvec2> W(n - 2);
for (int i = 0; i < n - 2; i++) { V[i] = i == n - 3 ? V_n2p : glm::dvec2(); }
SolveBlockLinearEq(nablaC, V, W);
// $x_2$, $T(x_2)$
const auto& x2 = currPath.vertices[1].geom.p;
const glm::dmat2x3 Tx2(currPath.vertices[1].geom.dpdu, currPath.vertices[1].geom.dpdv);
// $W_{n-2} = P_2 W$
const auto Wn2p = W[n - 3];
// $p = x_2 - \beta T(x_2) P_2 W_{n-2}$
p = x2 - beta * Tx2 * Wn2p;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Propagate light path to $p - x1$
bool fail = false;
Path nextPath;
// Initial vertex
nextPath.vertices.push_back(currPath.vertices[0]);
for (int i = 0; i < n - 1; i++)
{
// Current vertex & previous vertex
const auto* v = &nextPath.vertices[i];
const auto* vp = i > 0 ? &nextPath.vertices[i-1] : nullptr;
// Next ray direction
glm::dvec3 wo;
if (i == 0)
{
wo = glm::normalize(p - currPath.vertices[0].geom.p);
}
else
{
v->primitive->SampleDirection(glm::dvec2(), 0, v->type, v->geom, glm::normalize(vp->geom.p - v->geom.p), wo);
}
// Intersection query
Ray ray = { v->geom.p, wo };
Intersection isect;
if (!scene.Intersect(ray, isect))
{
fail = true;
break;
}
// Fails if not intersected with specular vertex
if (i < n - 2 && (isect.Prim->Type & PrimitiveType::S) == 0)
{
fail = true;
break;
}
// Create a new vertex
PathVertex vn;
vn.geom = isect.geom;
vn.type = isect.Prim->Type;
vn.primitive = isect.Prim;
nextPath.vertices.push_back(vn);
}
if (!fail)
{
if (nextPath.vertices.size() != currPath.vertices.size())
{
// # of vertices is different
fail = true;
}
else if ((nextPath.vertices.back().type & PrimitiveType::D) == 0)
{
// Last vertex type is not D
fail = true;
}
else
{
// Larger difference
const auto d = glm::length2(currPath.vertices.back().geom.p - target);
const auto dn = glm::length2(nextPath.vertices.back().geom.p - target);
if (dn >= d)
{
fail = true;
}
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Update beta
if (fail)
{
beta *= 0.5;
}
else
{
beta = glm::min(MaxBeta, beta * 1.7);
//beta = glm::min(MaxBeta, beta * 2.0);
currPath = nextPath;
}
#pragma endregion
}
#pragma endregion
// --------------------------------------------------------------------------------
outPath = currPath;
assert(seedPath.vertices.size() == outPath.vertices.size());
return converged;
}
#pragma endregion
};
#pragma endregion
// --------------------------------------------------------------------------------
bool Run(int argc, char** argv)
{
#pragma region Parse arguments
namespace po = boost::program_options;
// Define options
po::options_description opt("Allowed options");
opt.add_options()
("help", "Display help message")
("scene,i", po::value<std::string>(), "Scene file")
("result,o", po::value<std::string>()->default_value("render.hdr"), "Rendered result")
("renderer,r", po::value<std::string>()->required(), "Rendering technique")
("num-samples,n", po::value<long long>()->default_value(10000000L), "Number of samples")
("max-num-vertices,m", po::value<int>()->default_value(-1), "Maximum number of vertices")
("width,w", po::value<int>()->default_value(1280), "Width of the rendered image")
("height,h", po::value<int>()->default_value(720), "Height of the rendered image")
("num-threads,j", po::value<int>(), "Number of threads")
#if NGI_DEBUG_MODE
("grain-size", po::value<long long>()->default_value(10), "Grain size")
#else
("grain-size", po::value<long long>()->default_value(10000), "Grain size")
#endif
("progress-update-interval", po::value<long long>()->default_value(100000), "Progress update interval")
("render-time,t", po::value<double>()->default_value(-1), "Render time in seconds (-1 to use # of samples)")
("progress-image-update-interval", po::value<double>()->default_value(-1), "Progress image update interval (-1: disable)")
("progress-image-update-format", po::value<std::string>()->default_value("progress/{{count}}.png"), "Progress image update format string \n - {{count}}: image count");
// positional arguments
po::positional_options_description p;
p.add("renderer", 1).add("scene", 1).add("result", 1).add("width", 1).add("height", 1);
// Parse options
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).options(opt).positional(p).run(), vm);
if (vm.count("help") || argc == 1)
{
std::cout << "Usage: nanogi [options] <renderer> <scene> <result> <width> <height>" << std::endl;
std::cout << opt << std::endl;
return 1;
}
po::notify(vm);
}
catch (po::required_option& e)
{
std::cerr << "ERROR : " << e.what() << std::endl;
return false;
}
catch (po::error& e)
{
std::cerr << "ERROR : " << e.what() << std::endl;
return false;
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Initial message
NGI_LOG_INFO("nanogi");
NGI_LOG_INFO("Copyright (c) 2015 Light Transport Entertainment Inc.");
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Load scene
Scene scene;
{
NGI_LOG_INFO("Loading scene");
NGI_LOG_INDENTER();
if (!scene.Load(vm["scene"].as<std::string>(), (double)(vm["width"].as<int>()) / vm["height"].as<int>()))
{
return false;
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Initialize renderer
Renderer renderer;
{
NGI_LOG_INFO("Initializing renderer");
NGI_LOG_INDENTER();
if (!renderer.Load(vm))
{
return false;
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Rendering
std::vector<glm::dvec3> film;
{
NGI_LOG_INFO("Rendering");
NGI_LOG_INDENTER();
renderer.Render(scene, film);
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Save rendered image
{
NGI_LOG_INFO("Saving rendered image");
NGI_LOG_INDENTER();
SaveImage(vm["result"].as<std::string>(), film, vm["width"].as<int>(), vm["height"].as<int>());
}
#pragma endregion
// --------------------------------------------------------------------------------
return true;
}
int main(int argc, char** argv)
{
NGI_LOG_RUN();
int result = EXIT_SUCCESS;
try
{
#if NGI_PLATFORM_WINDOWS
_set_se_translator(SETransFunc);
#endif
if (!Run(argc, argv))
{
result = EXIT_FAILURE;
}
}
catch (const std::exception& e)
{
NGI_LOG_ERROR("EXCEPTION | " + std::string(e.what()));
result = EXIT_FAILURE;
}
#if NGI_DEBUG_MODE
std::cerr << "Press any key to exit ...";
std::cin.get();
#endif
NGI_LOG_STOP();
return result;
}
| 27.090571 | 193 | 0.531838 | [
"render",
"vector",
"transform"
] |
9e13f65d6dcba5a2b58e44ae9295430f6fd4b707 | 20,260 | cpp | C++ | lib/ccmutate/Mutex/LockUnlockPairs.cpp | markus-kusano/CCMutator | 66eca5c6a38fbdf8b5f5758b3646fc2604c6c51b | [
"NCSA"
] | 15 | 2016-03-31T12:03:50.000Z | 2021-01-30T08:24:05.000Z | lib/ccmutate/Mutex/LockUnlockPairs.cpp | markus-kusano/CCMutator | 66eca5c6a38fbdf8b5f5758b3646fc2604c6c51b | [
"NCSA"
] | null | null | null | lib/ccmutate/Mutex/LockUnlockPairs.cpp | markus-kusano/CCMutator | 66eca5c6a38fbdf8b5f5758b3646fc2604c6c51b | [
"NCSA"
] | 3 | 2017-11-24T15:18:12.000Z | 2020-08-06T13:12:31.000Z | /**
* This file is distributed under the University of Illinois Open Source
* License. See LICENSE for details.
*/
#include "LockUnlockPairs.h"
#include "../Tools/ItaniumDemangle.h"
#include "../Tools/FileInfo.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/DebugInfo.h"
#include <vector>
#include <string>
// Enable debugging output
#define MUT_DEBUG
// Enable verbose output
#define MUT_DEBUG_VERBOSE
void LockUnlockPairs::enumerate(Module &M, AliasAnalysis &AA) {
// Iterate over every function
Module::iterator fIter = M.begin();
Module::iterator fEnd = M.end();
for(;fIter != fEnd; ++fIter) {
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: checking new function\n";
#endif
// Vector to hold all lock & unlock call for the function
std::vector<CallInst *> mutexCalls;
std::vector<InvokeInst *> mutexInvokes;
// Iterate over every instruction
inst_iterator I;
inst_iterator E;
for (I = inst_begin(&*fIter), E = inst_end(&*fIter);
I != E; ++I) {
// Find target call/invoke instructions
if (CallInst* callInst = dyn_cast<CallInst>(&*I)) {
Function *calledFunc = callInst->getCalledFunction();
if (calledFunc) {
//StringRef funcName = calledFunc->getName();
bool matchedFuncCall;
matchedFuncCall = isMatch(calledFunc);
if (matchedFuncCall) {
mutexCalls.push_back(callInst);
}
}
}
else if (InvokeInst* invokeInst = dyn_cast<InvokeInst>(&*I)) {
Function *calledFunc = invokeInst->getCalledFunction();
if (calledFunc) {
//StringRef funcName = calledFunc->getName();
bool matchedFuncCall;
matchedFuncCall = isMatch(calledFunc);
if (matchedFuncCall) {
mutexInvokes.push_back(invokeInst);
}
}
}
} // end for (insts)
// Find pairs in the current function
//findCallPairs(mutexCalls, AA);
//findInvokePairs(mutexInvokes, AA);
findPairs(mutexCalls, mutexInvokes, AA);
} // end for (funcs)
} // end func
bool LockUnlockPairs::isMatch(Function *func) {
std::string noParams;
bool ret;
ret = false;
noParams = getFunctionName(func);
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: checking for match: " << noParams << '\n';
#endif
if (noParams == "std::__1::mutex::unlock") {
ret = true;
}
else if (noParams == "std::__1::mutex::lock") {
ret = true;
}
else if (noParams == "pthread_mutex_lock") {
ret = true;
}
else if (noParams == "pthread_mutex_unlock") {
ret = true;
}
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: match found? " << ret << '\n';
#endif
return ret;
}
#if 0 // These two functions don't provide full coverage of the case when a
// lock is a CallInst and the unlock call is an Invoke and vice versa.
void LockUnlockPairs::findCallPairs(std::vector<CallInst *> &calls, AliasAnalysis &AA) {
#ifdef MUT_DEBUG
errs() << "DEBUG: attempting to find call pairs in the following\n (size == "
<< calls.size() << ")\n";
for (unsigned i = 0; i < calls.size(); i++) {
errs() << "\t" << *(calls[i]) << '\n';
}
#endif
// Check for a match in the unlock calls that follow a lock call. The
// assumption is that a paired up unlock call cannot be before the
// associated lock call.
for (unsigned i = 0; i < calls.size(); i++) {
CallInst *inst1;;
inst1 = calls[i];
if (isLockCall(inst1->getCalledFunction())) {
for (unsigned j = i + 1; j < calls.size(); j++) {
CallInst *inst2;
inst2 = calls[j];
if (isLockUnlockPair(inst1, inst2, AA)) {
#ifdef MUT_DEBUG
errs() << "DEBUG: found pair:\n\t" << *inst1 << "\n\t" << *inst2 << '\n';
#endif
CallLockUnlockPair *newPair;
newPair = new CallLockUnlockPair;
newPair->lockCall = inst1;
newPair->unlockCall = inst2;
CallPairs.push_back(newPair);
}
}
}
}
}
void LockUnlockPairs::findInvokePairs(std::vector<InvokeInst *> &calls, AliasAnalysis &AA) {
#ifdef MUT_DEBUG
errs() << "DEBUG: attempting to find invoke pairs in the following\n (size == "
<< calls.size() << ")\n";
for (unsigned i = 0; i < calls.size(); i++) {
errs() << "\t" << *(calls[i]) << '\n';
}
#endif
// Check for a match in the unlock calls that follow a lock call. The
// assumption is that a paired up unlock call cannot be before the
// associated lock call.
for (unsigned i = 0; i < calls.size(); i++) {
InvokeInst *inst1;;
inst1 = calls[i];
if (isLockCall(inst1->getCalledFunction())) {
for (unsigned j = i + 1; j < calls.size(); j++) {
InvokeInst *inst2;
inst2 = calls[j];
if (isLockUnlockPair(inst1, inst2, AA)) {
#ifdef MUT_DEBUG
errs() << "DEBUG: found pair:\n\t" << *inst1 << "\n\t" << *inst2 << '\n';
#endif
InvokeLockUnlockPair *newPair;
newPair = new InvokeLockUnlockPair;
newPair->lockCall = inst1;
newPair->unlockCall = inst2;
InvokePairs.push_back(newPair);
}
}
}
}
}
#endif
void LockUnlockPairs::findPairs(std::vector<CallInst *> &calls, std::vector<InvokeInst *> &invokes,
AliasAnalysis &AA) {
// For each lock instruction found in either calls or invokes compare it to
// every other unlock call to see if they are a pair. There is probably a
// more optimal way to do this by also comparing unlock calls to lock
// calls.
// Compare all the call instructions
for (unsigned i = 0; i < calls.size(); i++) {
CallInst *call1;
call1 = calls[i];
if (isLockCall(call1->getCalledFunction())) {
// Compare to all other CallInsts
for (unsigned j = 0; j < calls.size(); j++) {
CallInst *call2;
call2 = calls[j];
if (call1 == call2) {
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: comparing call to it itself, skipping\n"
<< "\t i == " << i << " j == " << j << '\n';
#endif
continue;
}
if (isLockUnlockPair(call1, call2, AA)) {
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: found pair:\n\t" << *call1 << "\n\t" << *call2 << '\n';
#endif
CallCallLockPair *newPair;
newPair = new CallCallLockPair;
newPair->lockCall = call1;
newPair->unlockCall = call2;
CallCallPairs.push_back(newPair);
}
} // end for
for (unsigned j = 0; j < invokes.size(); j++) {
// Compare to invoke instructions
InvokeInst *invoke2;
invoke2 = invokes[j];
if (isLockUnlockPair(call1, invoke2, AA)) {
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: found pair:\n\t" << *call1 << "\n\t" << *invoke2 << '\n';
#endif
CallInvokeLockPair *newPair;
newPair = new CallInvokeLockPair;
newPair->lockCall = call1;
newPair->unlockInvoke = invoke2;
CallInvokePairs.push_back(newPair);
}
}
}
} // end for
// Compare all the invokes
for (unsigned i = 0; i < invokes.size(); i++) {
InvokeInst *invoke1;
invoke1 = invokes[i];
if (isLockCall(invoke1->getCalledFunction())) {
// Compare to all other CallInsts
for (unsigned j = 0; j < calls.size(); j++) {
CallInst *call2;
call2 = calls[j];
if (isLockUnlockPair(invoke1, call2, AA)) {
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: found pair:\n\t" << *invoke1 << "\n\t" << *call2 << '\n';
#endif
InvokeCallLockPair *newPair;
newPair = new InvokeCallLockPair;
newPair->lockInvoke = invoke1;
newPair->unlockCall = call2;
InvokeCallPairs.push_back(newPair);
}
} // end for
for (unsigned j = 0; j < invokes.size(); j++) {
// Compare to invoke instructions
InvokeInst *invoke2;
invoke2 = invokes[j];
if (invoke1 == invoke2) {
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: comparing invoke to it itself, skipping\n"
<< "\t i == " << i << " j == " << j << '\n';
#endif
continue;
}
if (isLockUnlockPair(invoke1, invoke2, AA)) {
#ifdef MUT_DEBUG_VERB
errs() << "DEBUG: found pair:\n\t" << *invoke1 << "\n\t" << *invoke2 << '\n';
#endif
InvokeInvokeLockPair *newPair;
newPair = new InvokeInvokeLockPair;
newPair->lockInvoke = invoke1;
newPair->unlockInvoke = invoke2;
InvokeInvokePairs.push_back(newPair);
}
} // end for
}
} // end for
}
bool LockUnlockPairs::isLockCall(Function *func) const {
StringRef funcName;
std::string noParams;
bool ret = false;
if (func == NULL) {
return false; // indirect function calls are not resolved
}
noParams = getFunctionName(func);
if (noParams == "pthread_mutex_lock") {
ret = true;
}
else if (noParams == "std::__1::mutex::lock") {
ret = true;
}
return ret;
}
bool LockUnlockPairs::isLockUnlockPair(Function *lockFunc, Function *otherFunc,
AliasAnalysis &AA, Value *mut1, Value *mut2) {
if (lockFunc == NULL) {
return false;
}
if (otherFunc == NULL) {
return false;
}
if (isLockCall(otherFunc)) {
return false;
}
// OPTIMIZATION: This can probably be removed.
if (!isLockCall(lockFunc)) {
errs() << "Warning: non lock call passed as lockFunc to isLockUnlockPair()\n";
return false;
}
std::string lockFuncName;
std::string otherFuncName;
otherFuncName = getFunctionName(otherFunc);
lockFuncName = getFunctionName(lockFunc);
AliasAnalysis::AliasResult res;
res = AA.alias(mut1, mut2);
if (lockFuncName == "pthread_mutex_lock" && otherFuncName == "pthread_mutex_unlock") {
// The calls are both to posix locks. The first parameters is the mutex
if (res == AliasAnalysis::MustAlias) {
return true;
}
}
else if (lockFuncName == "std::__1::mutex::lock" && otherFuncName == "std::__1::mutex::unlock") {
if (res == AliasAnalysis::MustAlias) {
return true;
}
}
return false;
}
bool LockUnlockPairs::isLockUnlockPair(CallInst *lockCall, CallInst *otherCall, AliasAnalysis &AA) {
if (lockCall->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex call with < 1 operand, skipping\n";
return false;
}
if (otherCall->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex call with < 1 operand, skipping\n";
return false;
}
Value *mut1;
Value *mut2;
Function *lockFunc;
Function *otherFunc;
mut1 = lockCall->getArgOperand(0);
mut2 = otherCall->getArgOperand(0);
lockFunc = lockCall->getCalledFunction();
otherFunc = otherCall->getCalledFunction();
return isLockUnlockPair(lockFunc, otherFunc, AA, mut1, mut2);
}
bool LockUnlockPairs::isLockUnlockPair(InvokeInst *lockCall, InvokeInst *otherCall, AliasAnalysis &AA) {
if (lockCall->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex invoke with < 1 operand, skipping\n";
return false;
}
if (otherCall->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex invoke with < 1 operand, skipping\n";
return false;
}
Value *mut1;
Value *mut2;
Function *lockFunc;
Function *otherFunc;
mut1 = lockCall->getArgOperand(0);
mut2 = otherCall->getArgOperand(0);
lockFunc = lockCall->getCalledFunction();
otherFunc = otherCall->getCalledFunction();
return isLockUnlockPair(lockFunc, otherFunc, AA, mut1, mut2);
}
bool LockUnlockPairs::isLockUnlockPair(CallInst *lockCall, InvokeInst *otherInvoke, AliasAnalysis &AA) {
if (lockCall->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex call with < 1 operand, skipping\n";
return false;
}
if (otherInvoke->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex invoke with < 1 operand, skipping\n";
return false;
}
Value *mut1;
Value *mut2;
Function *lockFunc;
Function *otherFunc;
mut1 = lockCall->getArgOperand(0);
mut2 = otherInvoke->getArgOperand(0);
lockFunc = lockCall->getCalledFunction();
otherFunc = otherInvoke->getCalledFunction();
return isLockUnlockPair(lockFunc, otherFunc, AA, mut1, mut2);
}
bool LockUnlockPairs::isLockUnlockPair(InvokeInst *lockInvoke, CallInst *otherCall, AliasAnalysis &AA) {
if (lockInvoke->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex call with < 1 operand, skipping\n";
return false;
}
if (otherCall->getNumArgOperands() < 1) {
errs() << "Warning: found a pthread or std::mutex invoke with < 1 operand, skipping\n";
return false;
}
Value *mut1;
Value *mut2;
Function *lockFunc;
Function *otherFunc;
mut1 = lockInvoke->getArgOperand(0);
mut2 = otherCall->getArgOperand(0);
lockFunc = lockInvoke->getCalledFunction();
otherFunc = otherCall->getCalledFunction();
return isLockUnlockPair(lockFunc, otherFunc, AA, mut1, mut2);
}
unsigned LockUnlockPairs::getNumPairs() const {
int ret;
ret = 0;
ret += CallCallPairs.size();
ret += CallInvokePairs.size();
ret += InvokeCallPairs.size();
ret += InvokeInvokePairs.size();
return ret;
}
unsigned LockUnlockPairs::getNumCallCallPairs() const {
return CallCallPairs.size();
}
unsigned LockUnlockPairs::getNumCallInvokePairs() const {
return CallInvokePairs.size();
}
unsigned LockUnlockPairs::getNumInvokeCallPairs() const {
return InvokeCallPairs.size();
}
unsigned LockUnlockPairs::getNumInvokeInvokePairs() const {
return InvokeInvokePairs.size();
}
void LockUnlockPairs::printDebugInfo() const {
for (unsigned i = 0; i < CallCallPairs.size(); i++) {
CallCallLockPair *curPair;
CallInst *lockCall;
CallInst *unlockCall;
Function *parent;
curPair = CallCallPairs[i];
lockCall = curPair->lockCall;
unlockCall = curPair->unlockCall;
parent = lockCall->getParent()->getParent();
errs() << parent->getName() << '\t' << 0 << '\t' << i << '\n';
errs() << '\t' << *lockCall << '\n';
errs() << '\t' << *unlockCall << '\n';
printDebugInfo(lockCall, unlockCall);
}
for (unsigned i = 0; i < CallInvokePairs.size(); i++) {
CallInvokeLockPair *curPair;
CallInst *lockCall;
InvokeInst *unlockInvoke;
Function *parent;
curPair = CallInvokePairs[i];
lockCall = curPair->lockCall;
unlockInvoke = curPair->unlockInvoke;
parent = lockCall->getParent()->getParent();
errs() << parent->getName() << '\t' << 1 << '\t' << i << '\n';
errs() << '\t' << *lockCall << '\n';
errs() << '\t' << *unlockInvoke << '\n';
printDebugInfo(lockCall, unlockInvoke);
}
for (unsigned i = 0; i < InvokeCallPairs.size(); i++) {
InvokeCallLockPair *curPair;
InvokeInst *lockInvoke;
CallInst *unlockCall;
Function *parent;
curPair = InvokeCallPairs[i];
lockInvoke = curPair->lockInvoke;
unlockCall = curPair->unlockCall;
parent = lockInvoke->getParent()->getParent();
errs() << parent->getName() << '\t' << 2 << '\t' << i << '\n';
errs() << '\t' << *lockInvoke << '\n';
errs() << '\t' << *unlockCall << '\n';
printDebugInfo(lockInvoke, unlockCall);
}
for (unsigned i = 0; i < InvokeInvokePairs.size(); i++) {
InvokeInvokeLockPair *curPair;
InvokeInst *lockInvoke;
InvokeInst *unlockInvoke;
Function *parent;
curPair = InvokeInvokePairs[i];
lockInvoke = curPair->lockInvoke;
unlockInvoke = curPair->unlockInvoke;
parent = lockInvoke->getParent()->getParent();
errs() << parent->getName() << 3 << '\t' << i << '\n';
errs() << '\t' << *lockInvoke << '\n';
errs() << '\t' << *unlockInvoke << '\n';
printDebugInfo(lockInvoke, unlockInvoke);
}
}
int LockUnlockPairs::calcDistanceBetween(Instruction *inst1, Instruction *inst2) const {
// Check that the instructions are from the same function
if (inst1->getParent()->getParent() != inst2->getParent()->getParent()) {
errs() << "Warning: unable to calculate the distance between two "
"instructions that are in different functions";
return -1;
}
int distance;
distance = 0;
inst_iterator iter = inst_begin(inst1->getParent()->getParent());
// Find the first instruction in the function
while (&*iter != inst1 && &*iter != inst2) {
++iter;
}
// Increment the iterator past the just found instruction
++iter;
++distance;
while (&*iter != inst1 && &*iter != inst2) {
++distance;
++iter;
}
return distance;
}
void LockUnlockPairs::printDebugInfo(Instruction *lockCall, Instruction *unlockCall) const {
// Lock call filename and line number
StringRef fileName1 = getDebugFilename(lockCall);
unsigned lineNum1 = getDebugLineNum(lockCall);
if (fileName1 == "") {
errs() << "\tno debug filename for lock call";
}
else {
errs() << '\t' << fileName1;
}
if (lineNum1 == UINT_MAX) {
errs() << " no debug line number for lock call";
}
else {
errs() << ' ' << lineNum1;
}
// Unlock call filename and line number
StringRef fileName2 = getDebugFilename(unlockCall);
unsigned lineNum2 = getDebugLineNum(unlockCall);
if (fileName2 == "") {
errs() << "\tno debug filename for lock call";
}
else {
errs() << '\t' << fileName2;
}
if (lineNum1 == UINT_MAX) {
errs() << " no debug line number for lock call";
}
else {
errs() << ' ' << lineNum2;
}
// Distance between the two calls
int distBetween;
distBetween = calcDistanceBetween(lockCall, unlockCall);
if (distBetween < 0 ) {
errs() << "\tunable to calc distance between insts\n";
}
else {
errs() << '\t' << distBetween << '\n';
}
}
LockUnlockPairs::CallCallLockPair *LockUnlockPairs::getCallCallPair(unsigned index) {
if (index < CallCallPairs.size()) {
return CallCallPairs[index];
}
else {
return NULL;
}
}
LockUnlockPairs::CallInvokeLockPair *LockUnlockPairs::getCallInvokePair(unsigned index) {
if (index < CallInvokePairs.size()) {
return CallInvokePairs[index];
}
else {
return NULL;
}
}
LockUnlockPairs::InvokeCallLockPair *LockUnlockPairs::getInvokeCallPair(unsigned index) {
if (index < InvokeCallPairs.size()) {
return InvokeCallPairs[index];
}
else {
return NULL;
}
}
LockUnlockPairs::InvokeInvokeLockPair *LockUnlockPairs::getInvokeInvokePair(unsigned index) {
if (index < InvokeInvokePairs.size()) {
return InvokeInvokePairs[index];
}
else {
return NULL;
}
}
| 32.73021 | 104 | 0.571718 | [
"vector"
] |
9e2f22e2a391e721bd3acebb09c97d40ee3c0cc4 | 3,540 | hpp | C++ | platform/NpapiPluginInstance.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 26 | 2015-04-22T05:25:25.000Z | 2020-11-15T11:07:56.000Z | platform/NpapiPluginInstance.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 2 | 2015-01-05T10:41:27.000Z | 2015-01-06T20:46:11.000Z | platform/NpapiPluginInstance.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 5 | 2016-08-02T11:13:57.000Z | 2018-10-26T11:19:27.000Z | #ifndef ___INANITY_PLATFORM_NPAPI_PLUGIN_INSTANCE_HPP___
#define ___INANITY_PLATFORM_NPAPI_PLUGIN_INSTANCE_HPP___
#include "npapi.hpp"
#include "../graphics/graphics.hpp"
#include "../input/input.hpp"
#include "../script/np/np.hpp"
#include "../Handler.hpp"
BEGIN_INANITY
class File;
END_INANITY
BEGIN_INANITY_GRAPHICS
class Device;
class Presenter;
END_INANITY_GRAPHICS
BEGIN_INANITY_INPUT
#if defined(___INANITY_PLATFORM_WINDOWS)
class Win32WmManager;
#elif defined(___INANITY_PLATFORM_LINUX)
#else
#error Unknown platform
#endif
END_INANITY_INPUT
BEGIN_INANITY_NP
class Any;
END_INANITY_NP
BEGIN_INANITY_PLATFORM
class NpapiPresenter;
#if defined(___INANITY_PLATFORM_WINDOWS)
class Win32Window;
#elif defined(___INANITY_PLATFORM_LINUX)
#else
#error Unknown platform
#endif
/// Base class of instance of the NPAPI plugin.
class NpapiPluginInstance : public Object
{
public:
typedef DataHandler<ptr<File> > ReceiveHandler;
protected:
//*** Settings, should be set in derived class' constructor.
/// Plugin name.
const char* name;
/// Plugin description.
const char* description;
/// Windowless mode.
bool windowless;
/// Transparent mode.
bool transparent;
/// Plugin instance handle.
NPP npp;
/// Left-top corner of client area.
int left, top;
/// Size of client area.
int width, height;
NpapiPluginInstance(bool needInputManager);
~NpapiPluginInstance();
private:
/// Graphics presenter.
ptr<NpapiPresenter> presenter;
bool DoDraw();
#if defined(___INANITY_PLATFORM_WINDOWS)
ptr<Input::Win32WmManager> inputManager;
// Either window or hdc is not-null, depending on windowless mode.
ptr<Win32Window> window;
HDC hdc;
#elif defined(___INANITY_PLATFORM_LINUX)
#else
#error Unknown platform.
#endif
protected:
/// Redefine in derived class to perform initialization.
virtual void PostInit();
/// Get graphics device for rendering.
/** Redefine in derived class. Default implementation
returns nullptr to skip drawing. */
virtual ptr<Graphics::Device> GetGraphicsDevice() const;
/// Perform actual drawing.
/** Redefine in derived class. Default implementation
does nothing. */
virtual void Draw();
/// Script object which will be returned to javascript.
ptr<Script::Np::Any> scriptObject;
struct UrlStream;
static void AsyncCallRoutine(void* data);
public:
NPP GetNpp() const;
static NpapiPluginInstance* FromNpp(NPP npp);
ptr<Script::Np::Any> GetWindowDomObject() const;
ptr<Script::Np::Any> GetPluginDomObject() const;
/// Make HTTP GET request.
void GetUrl(const String& url, ptr<ReceiveHandler> receiveHandler);
/// Make HTTP POST request.
void PostUrl(const String& url, ptr<File> postData, ptr<ReceiveHandler> receiveHandler);
/// Make async call.
void AsyncCall(ptr<Handler> handler);
/// Invalidate visual representation.
void Invalidate();
/// Get presenter to draw into.
/** Valid only in Draw(). */
ptr<Graphics::Presenter> GetPresenter() const;
//*** Internal methods.
void Init(NPP npp);
virtual void Destroy();
NPError NppSetWindow(NPWindow* window);
NPError NppNewStream(NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype);
NPError NppDestroyStream(NPStream* stream, NPReason reason);
int32_t NppWriteReady(NPStream* stream);
int32_t NppWrite(NPStream* stream, int32_t offset, int32_t len, void* buffer);
int16_t NppHandleEvent(void* event);
void NppURLNotify(const char* url, NPReason reason, void* notifyData);
NPError NppGetValue(NPPVariable variable, void* retValue);
};
END_INANITY_PLATFORM
#endif
| 22.83871 | 91 | 0.764972 | [
"object"
] |
9e2f2ef221576796771817d3c9833df15cc73c85 | 3,024 | cpp | C++ | src/ezlog_lock.cpp | JennyGH/ezlog | 274f7bf1719e1cb751038e2423abcb086cf916c7 | [
"MIT"
] | 2 | 2021-03-16T14:16:46.000Z | 2022-01-04T08:43:07.000Z | src/ezlog_lock.cpp | JennyGH/ezlog | 274f7bf1719e1cb751038e2423abcb086cf916c7 | [
"MIT"
] | 1 | 2022-01-18T07:02:19.000Z | 2022-01-18T07:02:19.000Z | src/ezlog_lock.cpp | JennyGH/ezlog | 274f7bf1719e1cb751038e2423abcb086cf916c7 | [
"MIT"
] | null | null | null | #include "ezlog_lock.h"
#include "system.h"
#include <stdio.h>
#include <stdlib.h>
#if _MSC_VER
# include <Windows.h>
# define USE_CRITICAL_SECTION 1
# if USE_CRITICAL_SECTION
typedef CRITICAL_SECTION ezlog_lock_t;
# else
typedef HANDLE ezlog_lock_t;
# endif // USE_CRITICAL_SECTION
#else
# include <unistd.h>
# include <pthread.h>
typedef pthread_mutex_t ezlog_lock_t;
#endif // _MSC_VER
#define _to_ezlog_lock_t(lock) (static_cast<ezlog_lock_t*>(lock))
#define _output_error(fmt, ...) fprintf(stderr, fmt "\n", ##__VA_ARGS__)
#define _strerror_s(eno) ezlog_get_error_message(eno).c_str()
ezlog_lock ezlog_lock_create()
{
ezlog_lock_t* lock_ptr = new ezlog_lock_t();
if (NULL == lock_ptr)
{
_output_error("No enough memory to create an ezlog_lock object.");
exit(-1);
}
#if _MSC_VER
# if USE_CRITICAL_SECTION
::InitializeCriticalSection(lock_ptr);
# else
*lock_ptr = ::CreateMutex(NULL, FALSE, NULL);
# endif // USE_CRITICAL_SECTION
#else
int ret = 0;
pthread_mutexattr_t attr;
ret = pthread_mutexattr_init(&attr);
if (0 != ret)
{
_output_error(
"Unable to create mutex attribute, because: %s",
_strerror_s(ret));
exit(ret);
}
ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if (0 != ret)
{
_output_error(
"Unable to set mutex attribute with `PTHREAD_MUTEX_RECURSIVE`, because: %s",
_strerror_s(ret));
exit(ret);
}
ret = pthread_mutex_init(lock_ptr, &attr);
if (0 != ret)
{
_output_error("Unable to init mutex, because: %s", _strerror_s(ret));
exit(ret);
}
pthread_mutexattr_destroy(&attr);
#endif // _MSC_VER
return lock_ptr;
}
void ezlog_lock_lock(ezlog_lock lock)
{
ezlog_lock_t* lock_ptr = _to_ezlog_lock_t(lock);
if (NULL == lock_ptr)
{
// ASSERT!
return;
}
#if _MSC_VER
# if USE_CRITICAL_SECTION
::EnterCriticalSection(lock_ptr);
# else
::WaitForSingleObject(*lock_ptr, INFINITE);
# endif // USE_CRITICAL_SECTION
#else
pthread_mutex_lock(lock_ptr);
#endif // _MSC_VER
}
void ezlog_lock_unlock(ezlog_lock lock)
{
ezlog_lock_t* lock_ptr = _to_ezlog_lock_t(lock);
if (NULL == lock_ptr)
{
// ASSERT!
return;
}
#if _MSC_VER
# if USE_CRITICAL_SECTION
::LeaveCriticalSection(lock_ptr);
# else
::ReleaseMutex(*lock_ptr);
# endif // USE_CRITICAL_SECTION
#else
pthread_mutex_unlock(lock_ptr);
#endif // _MSC_VER
}
void ezlog_lock_destroy(ezlog_lock lock)
{
ezlog_lock_t* lock_ptr = _to_ezlog_lock_t(lock);
if (NULL == lock_ptr)
{
// ASSERT!
return;
}
#if _MSC_VER
# if USE_CRITICAL_SECTION
::DeleteCriticalSection(lock_ptr);
# else
::CloseHandle(*lock_ptr);
# endif // USE_CRITICAL_SECTION
#else
pthread_mutex_destroy(lock_ptr);
#endif // _MSC_VER
delete lock_ptr;
lock_ptr = NULL;
}
| 24.192 | 88 | 0.650794 | [
"object"
] |
9e3727f893c571d1307790a8c18616f6ad9cf270 | 5,277 | hpp | C++ | metric/modules/utils/poor_mans_quantum.hpp | Stepka/telegram_clustering_contest | 52a012af2ce821410caa98cba840364710eb4256 | [
"Apache-2.0"
] | 2 | 2019-12-03T17:08:04.000Z | 2021-08-25T05:06:29.000Z | metric/modules/utils/poor_mans_quantum.hpp | Stepka/telegram_clustering_contest | 52a012af2ce821410caa98cba840364710eb4256 | [
"Apache-2.0"
] | 1 | 2021-09-02T02:25:51.000Z | 2021-09-02T02:25:51.000Z | metric/modules/utils/poor_mans_quantum.hpp | Stepka/telegram_clustering_contest | 52a012af2ce821410caa98cba840364710eb4256 | [
"Apache-2.0"
] | null | null | null | /* PANDA presents
██████╗ ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ███╗ ██╗███████╗ ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗██╗ ██╗███╗ ███╗
██╔══██╗██╔═══██╗██╔═══██╗██╔══██╗ ████╗ ████║██╔══██╗████╗ ██║██╔════╝ ██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝██║ ██║████╗ ████║
██████╔╝██║ ██║██║ ██║██████╔╝ ██╔████╔██║███████║██╔██╗ ██║███████╗ ██║ ██║██║ ██║███████║██╔██╗ ██║ ██║ ██║ ██║██╔████╔██║
██╔═══╝ ██║ ██║██║ ██║██╔══██╗ ██║╚██╔╝██║██╔══██║██║╚██╗██║╚════██║ ██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║ ██║ ██║██║╚██╔╝██║
██║ ╚██████╔╝╚██████╔╝██║ ██║ ██║ ╚═╝ ██║██║ ██║██║ ╚████║███████║ ╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║ ╚██████╔╝██║ ╚═╝ ██║
╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝ ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
Licensed under MPL 2.0.
Michael Welsch (c) 2019.
a library for computing with random distributed variables
a random distributed variable is just like a single value but with uncertainty around it.
you can do most operation with them like with real numbers
and a few special ones, that do not make sense for real numbers.
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/.
Copyright (c) 2019 Michael Welsch
*/
#ifndef _METRIC_UTILS_POOR_MANS_QUANTUM_HPP
#define _METRIC_UTILS_POOR_MANS_QUANTUM_HPP
#ifndef RV_SAMPLES
#define RV_SAMPLES 10000 // precision [1000 .. 1000000]
#endif
#ifndef RV_ERROR
#define RV_ERROR 0.05 // statistical error level alpha [0.001 .. 0.2]
#endif
#include "poor_mans_quantum/distributions/Discrete.hpp"
namespace metric {
template <typename Distribution = Discrete<float>, typename T = float>
class PMQ {
public:
/**
* @brief Construct a new PMQ object
*
* @param par1
* @param par2
* @param n
* @param d
*/
PMQ(T par1 = 1.0, T par2 = 0.0, size_t n = 1000, Distribution d = Distribution());
/**
* @brief Construct a new PMQ object
*
* @param data
* @param d
*/
PMQ(std::vector<double> data, Distribution d = Distribution());
/**
* @brief Construct a new PMQ object
*
* @param data
* @param d
*/
PMQ(std::vector<float> data, Distribution d = Distribution());
/**
* @brief
*
* @return
*/
T rnd();
/**
* @brief
*
* @return
*/
T median();
/**
* @brief
*
* @param p
* @return
*/
T quantil(T p);
/**
* @brief
*
* @return
*/
T mean();
/**
* @brief
*
* @return
*/
T variance();
/**
* @brief
*
* @param x
* @return
*/
T pdf(T x);
/**
* @brief
*
* @param x
* @return
*/
T cdf(T x);
/**
* @brief
*
* @param x
* @return
*/
T icdf(T x);
/**
* @brief
*
* @return size_t
*/
size_t size();
/**
* @brief
*
* @tparam mT
* @param rv
* @return
*/
template <typename mT>
mT believe(mT rv);
/**
* @brief
*
* @param confidencelevel
* @return
*/
std::tuple<PMQ<Discrete<float>>, PMQ<Discrete<float>>> confidence(const T& confidencelevel = 1 - RV_ERROR) const;
/**
* @brief
*
* @tparam mT1
* @tparam mT2
* @param set_0_left
* @param set_0_right
* @param confidencelevel
* @return
*/
template <typename mT1, typename mT2>
std::tuple<PMQ<Discrete<float>>, PMQ<Discrete<float>>> merged_confidence(
const mT1& set_0_left, const mT2& set_0_right, const T confidencelevel = 1 - RV_ERROR) const;
/**
* @brief
*
* @tparam mT1
* @tparam mT2
* @param set_left
* @param set_right
* @return
*/
template <typename mT1, typename mT2>
float in_confidence(const mT1& set_left, const mT2& set_right) const;
/**
* @brief
*
* @tparam mT1
* @tparam mT2
* @param set_left
* @param set_right
* @return
*/
template <typename mT1, typename mT2>
float out_confidence(const mT1& set_left, const mT2& set_right) const;
/**
* @brief
*
* @return
*/
float is_normal_distributed();
/**
* @brief
*
* @return
*/
float is_weibull_distributed();
private:
Distribution _dist;
std::mt19937_64 _generator;
};
}
#include "poor_mans_quantum/poor_mans_quantum.cpp"
#endif // headerguard
| 24.658879 | 180 | 0.40667 | [
"object",
"vector"
] |
9e3af51d9f34bd54ad1df8dad063823639d1a6fb | 3,314 | cpp | C++ | source/omni/core/model/literal_expression.cpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | 33 | 2015-03-21T04:12:45.000Z | 2021-04-18T21:44:33.000Z | source/omni/core/model/literal_expression.cpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | null | null | null | source/omni/core/model/literal_expression.cpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | 2 | 2016-03-05T12:57:05.000Z | 2017-09-12T10:11:52.000Z | #include <omni/core/model/literal_expression.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/not_implemented_error.hpp>
#include <sstream>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info literal_expressionMetaInfo;
}
/**
@brief Creates a new literal_expression from the human-readable `text'.
The format of a human-readable text that can be converted to a literal follows this form:
<number> <type specifier>
The numer can be typed in the current locale's form, e.g. in English environments, it uses "," as the thousands separator and "." as the decimal separator,
whereas e.g. in German environments, "." as the thousands separator and "," as the decimal separator.
When the same literal will be converted to text on a different locale, it will automatically adapt to the new environment. The internal storage is binary and
therefore independent from the locale.
The resulting object will be a subclass of literal_expression, for example builtin_literal_expression.
@param context The context that the literal should be created in.
@param text The text that represents the literal and should be converted to a literal.
@param originatingLiteral If the text was provided as a modification of an existing literal, pass that literal as the `originatingLiteral'. A missing
type specifier will then be derived from the origin.
@return A new literal_expression, if text can be converted to any kind of literal_expression. nullptr, if text is empty or can not be converted.
**/
std::shared_ptr <omni::core::model::literal_expression> omni::core::model::literal_expression::fromString (
context & context,
std::string const & text,
literal_expression * originatingLiteral)
{
unsigned int value = 0u;
std::stringstream str (text);
str >> value;
auto result = std::make_shared <builtin_literal_expression <int>> (context, value);
return result;
}
omni::core::model::meta_info & omni::core::model::literal_expression::getStaticMetaInfo ()
{
return omniMetaImpl::literal_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::literal_expression::getMetaInfo () const
{
return literal_expression::getStaticMetaInfo ();
}
/**
@brief Connects a handler to the ValueChanged signal that is emitted, after the current value of this builtin_literal has been changed.
@param handler The handler that will be called after the current value changed.
@return A signal connection that can be used disconnect this handler.
**/
boost::signals2::connection omni::core::model::literal_expression::connectValueChanged (ValueChangedSignal::slot_type handler)
{
return _valueChangedSignal.connect (handler);
}
/**
@brief Emits the signals ValueChanged and Changed, int his order.
When overriding this function, make sure to call the base class implementation. Otherwise, all other functionality that depends on the ValueChanged and Changed signals will break.
@param oldValue The value that this builtin_literal had, before it was changed.
@param newValue The new, current value of this builtin_literal.
**/
void omni::core::model::literal_expression::valueChanged (boost::any oldValue, boost::any newValue)
{
_valueChangedSignal (* this, oldValue, newValue);
changed ();
}
| 44.186667 | 179 | 0.777007 | [
"object",
"model"
] |
eafd5de283b5fd1efa79b6822c81802eb0a6c174 | 1,939 | cpp | C++ | aws-cpp-sdk-fsx/source/model/OpenZFSUserOrGroupQuota.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-fsx/source/model/OpenZFSUserOrGroupQuota.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-fsx/source/model/OpenZFSUserOrGroupQuota.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/fsx/model/OpenZFSUserOrGroupQuota.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace FSx
{
namespace Model
{
OpenZFSUserOrGroupQuota::OpenZFSUserOrGroupQuota() :
m_type(OpenZFSQuotaType::NOT_SET),
m_typeHasBeenSet(false),
m_id(0),
m_idHasBeenSet(false),
m_storageCapacityQuotaGiB(0),
m_storageCapacityQuotaGiBHasBeenSet(false)
{
}
OpenZFSUserOrGroupQuota::OpenZFSUserOrGroupQuota(JsonView jsonValue) :
m_type(OpenZFSQuotaType::NOT_SET),
m_typeHasBeenSet(false),
m_id(0),
m_idHasBeenSet(false),
m_storageCapacityQuotaGiB(0),
m_storageCapacityQuotaGiBHasBeenSet(false)
{
*this = jsonValue;
}
OpenZFSUserOrGroupQuota& OpenZFSUserOrGroupQuota::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Type"))
{
m_type = OpenZFSQuotaTypeMapper::GetOpenZFSQuotaTypeForName(jsonValue.GetString("Type"));
m_typeHasBeenSet = true;
}
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetInteger("Id");
m_idHasBeenSet = true;
}
if(jsonValue.ValueExists("StorageCapacityQuotaGiB"))
{
m_storageCapacityQuotaGiB = jsonValue.GetInteger("StorageCapacityQuotaGiB");
m_storageCapacityQuotaGiBHasBeenSet = true;
}
return *this;
}
JsonValue OpenZFSUserOrGroupQuota::Jsonize() const
{
JsonValue payload;
if(m_typeHasBeenSet)
{
payload.WithString("Type", OpenZFSQuotaTypeMapper::GetNameForOpenZFSQuotaType(m_type));
}
if(m_idHasBeenSet)
{
payload.WithInteger("Id", m_id);
}
if(m_storageCapacityQuotaGiBHasBeenSet)
{
payload.WithInteger("StorageCapacityQuotaGiB", m_storageCapacityQuotaGiB);
}
return payload;
}
} // namespace Model
} // namespace FSx
} // namespace Aws
| 20.410526 | 93 | 0.738525 | [
"model"
] |
d8000f37e4be8ed72c0c5850d4686a0ffbab68cd | 2,180 | cpp | C++ | altFillTheMat.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | altFillTheMat.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | altFillTheMat.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
#include <queue>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,qu;
scanf("%d%d",&n,&qu);
int i,j,val;
vector<int> a(n+1);
vector< pair<int,int> > vec[n+1];
int flag=0;
for(int k=0;k<qu;k++)
{
scanf("%d%d%d",&i,&j,&val);
if(i!=j)
{
vec[i].push_back(pair<int,int>(j,val));
vec[j].push_back(pair<int,int>(i,val));
}
else if(val==1)flag=1;
}
if(flag==1)
{
printf("no\n");
continue;
}
queue<int> q0,q1;
vector<int> acc(n+1);
for(int k=1;k<=n;k++)
{
if(acc[k]==0)
{
acc[k]=1;
a[k]=9;
for(int l=0;l<vec[k].size();l++)
{
a[vec[k][l].first]=a[k]+vec[k][l].second;
if(vec[k][l].second==0)
q0.push(vec[k][l].first);
else q1.push(vec[k][l].first);
}
while(true)
{
while(!q0.empty())
{
int x=q0.front();
acc[x]=1;
q0.pop();
for(int l=0;l<vec[x].size();l++)
{
if(a[vec[x][l].first]!=0 && a[vec[x][l].first]!=(a[x]+vec[x][l].second) && a[vec[x][l].first]!=(a[x]-vec[x][l].second))
{
flag=1;
break;
}
else if(a[vec[x][l].first]==0)
{
a[vec[x][l].first]=a[x]+vec[x][l].second;
if(vec[x][l].first==0)
q0.push(vec[x][l].first);
else q1.push(vec[x][l].first);
}
}
if(flag==1)
break;
}
while(!q1.empty())
{
int x=q1.front();
acc[x]=1;
q1.pop();
for(int l=0;l<vec[x].size();l++)
{
if(a[vec[x][l].first]!=0 && a[vec[x][l].first]!=(a[x]+vec[x][l].second) && a[vec[x][l].first]!=(a[x]-vec[x][l].second))
{
flag=1;
break;
}
else if(a[vec[x][l].first]==0)
{
a[vec[x][l].first]=a[x]+vec[x][l].second;
if(vec[x][l].first==0)
q0.push(vec[x][l].first);
else q1.push(vec[x][l].first);
}
}
if(flag==1)
break;
}
if(flag==1)
break;
if(q0.empty() && q1.empty())
break;
}
}
if(flag==1)
break;
}
if(flag==1)
{
printf("no\n");
}
else printf("yes\n");
}
} | 19.292035 | 126 | 0.43945 | [
"vector"
] |
d809376ea9895eaeea64a6d7035bafa0b899190d | 3,046 | cpp | C++ | ManagedScripts/MCommandLineParser.cpp | mpforums/RenSharp | 5b3fb8bff2a1772a82a4148bcf3e1265a11aa097 | [
"Apache-2.0"
] | 1 | 2021-10-04T02:34:33.000Z | 2021-10-04T02:34:33.000Z | ManagedScripts/MCommandLineParser.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 9 | 2019-07-03T19:19:59.000Z | 2020-03-02T22:00:21.000Z | ManagedScripts/MCommandLineParser.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 2 | 2019-08-14T08:37:36.000Z | 2020-09-29T06:44:26.000Z | /*
Copyright 2020 Neijwiert
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 "stdafx.h"
#include "MCommandLineParser.h"
#include "Imports.h"
#include "UnmanagedContainer.h"
#pragma managed(push, off)
#pragma warning(push)
#pragma warning(disable : 4251 4244 26495 26454)
#include <CommandLineParser.h>
#pragma warning(pop)
#pragma managed(pop)
namespace RenSharp
{
CommandLineParser::CommandLineParser(String^ command)
{
if (command == nullptr)
{
throw gcnew ArgumentNullException("command");
}
IntPtr commandHandle = Marshal::StringToHGlobalAnsi(command);
try
{
Pointer = IntPtr(Imports::CreateCommandLineParser(
reinterpret_cast<char*>(commandHandle.ToPointer())));
}
finally
{
Marshal::FreeHGlobal(commandHandle);
}
}
CommandLineParser::CommandLineParser(IntPtr pointer)
: AbstractUnmanagedObject(pointer)
{
}
IUnmanagedContainer<ICommandLineParser^>^ CommandLineParser::CreateCommandLineParser(String^ command)
{
return gcnew UnmanagedContainer<ICommandLineParser^>(gcnew CommandLineParser(command));
}
bool CommandLineParser::Equals(Object^ other)
{
if (AbstractUnmanagedObject::Equals(other))
{
return true;
}
ICommandLineParser^ otherThis = dynamic_cast<ICommandLineParser^>(other);
if (otherThis == nullptr)
{
return nullptr;
}
return CommandLineParserPointer.Equals(otherThis->CommandLineParserPointer);
}
void CommandLineParser::Skip()
{
InternalCommandLineParserPointer->skip();
}
String^ CommandLineParser::GetString()
{
auto result = InternalCommandLineParserPointer->getString();
if (result == nullptr)
{
return nullptr;
}
else
{
return gcnew String(result);
}
}
String^ CommandLineParser::GetRemainingString()
{
auto result = InternalCommandLineParserPointer->getRemainingString();
if (result == nullptr)
{
return nullptr;
}
else
{
return gcnew String(result);
}
}
int CommandLineParser::GetInt()
{
return InternalCommandLineParserPointer->getInt();
}
double CommandLineParser::GetDouble()
{
return InternalCommandLineParserPointer->getDouble();
}
IntPtr CommandLineParser::CommandLineParserPointer::get()
{
return IntPtr(InternalCommandLineParserPointer);
}
bool CommandLineParser::InternalDestroyPointer()
{
Imports::DestroyCommandLineParser(InternalCommandLineParserPointer);
Pointer = IntPtr::Zero;
return true;
}
::CommandLineParser* CommandLineParser::InternalCommandLineParserPointer::get()
{
return reinterpret_cast<::CommandLineParser*>(Pointer.ToPointer());
}
} | 22.397059 | 102 | 0.752134 | [
"object"
] |
d8122c3d1bac91f7132e48e1c5e484c251bc010b | 7,735 | cpp | C++ | LilEngie/Core/src/Game/SceneLoader.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | LilEngie/Core/src/Game/SceneLoader.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | LilEngie/Core/src/Game/SceneLoader.cpp | Nordaj/LilEngie | 453cee13c45ae33abe2665e1446fc90e67b1117a | [
"MIT"
] | null | null | null | #include <string>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <Graphics/ModelHandler.h>
#include <Graphics/Model.h>
#include <Graphics/Texture.h>
#include <Graphics/TextureHandler.h>
#include <Graphics/Shader.h>
#include <Graphics/ShaderHandler.h>
#include <Graphics/Material.h>
#include <Graphics/MaterialHandler.h>
#include <Graphics/Text/TextHandler.h>
#include <Utilities/ModelLoader.h>
#include <Entity/Scene.h>
#include <Entity/SceneManager.h>
#include "../../ComponentConstruction.h"
#include "SceneLoader.h"
//I'm lazy... dont judge me
typedef std::vector<std::string> sVec;
std::vector<std::string> Split(std::string &ref, char refChar)
{
std::vector<std::string> val;
//Store remaining params as i cycle through
std::string remaining = ref;
//Loop through each param
for (;;)
{
//Get index of char
int index = remaining.find(refChar);
//Check if done
if (index == std::string::npos)
{
if (remaining.size() > 0)
index = remaining.size();
else
break;
}
//Get it into string
std::string param = remaining.substr(0, index);
//Add to vector
val.push_back(param);
//Remove from remaining
remaining.erase(0, index + 1);
}
return val;
}
std::vector<std::string> SplitParams(std::string &ref)
{
bool inParam = false;
int prev = -1;
std::string rem = ref; //Stores remaining
sVec params;
for (int i = 0; i < ref.size(); i++)
{
//Keep track of whether im in a param
if (rem[i] == '(')
inParam = true;
else if (rem[i] == ')')
inParam = false;
//Split if im a space
if ((rem[i] == ' ' || i == rem.size() - 1) && !inParam)
{
std::string param = rem.substr(prev + 1, i + 1 - (prev + 1));
prev = i;
//Remove space if its there
if (param[param.size() - 1] == ' ')
param.erase(param.size() - 1, 1);
params.push_back(param);
}
}
if (inParam)
ERROR(("You have a problem with your parenthesis: \n" + ref).c_str());
return params;
}
void Erase(std::string &ref, char c)
{
for (;;)
{
//Get index to remove if necessary
int index = ref.find(c);
if (index == std::string::npos)
break;
ref.erase(index, 1);
}
}
void GetNamesNValues(sVec *names, sVec *values, sVec &splits)
{
for (int i = 0; i < splits.size(); i++)
{
int index = splits[i].find('(');
std::string name = splits[i].substr(0, index);
std::string vals = splits[i].substr(index + 1, splits[i].size() - (index + 2));
names->push_back(name);
values->push_back(vals);
}
}
void ReadModelCmd(std::string &line, Scene *scene)
{
//Filter command parameters
sVec splits = Split(line, ' ');
Erase(splits[2], '"');
//Setup model TODO
Model *model = ModelLoader::Load(splits[2].c_str());
scene->models.AddModel(splits[1], model);
}
void ReadTextureCmd(std::string &line, Scene *scene)
{
//Filter command parameters
sVec splits = Split(line, ' ');
Erase(splits[2], '"');
//Setup texture
Texture tex = Texture(splits[2].c_str());
scene->textures.AddTex(splits[1], tex);
}
void ReadShaderCmd(std::string &line, Scene *scene)
{
//Filter command parameters
sVec splits = Split(line, ' ');
Erase(splits[2], '"');
//Add to shaders
scene->shaders.Create(splits[1], splits[2].c_str());
}
void ReadMaterialCmd(std::string &line, Scene *scene)
{
//Filter command parameters
sVec splits = Split(line, ' ');
//Create material
scene->materials.Add(splits[1], splits[2], &scene->shaders);
}
void ReadObjectCmd(std::string &line, Scene *scene)
{
//Filter command parameters
sVec splits = Split(line, ' ');
//Add to current scene
scene->AddObject(splits[1]);
}
void ReadFontCmd(std::string &line, Scene *scene)
{
sVec params = Split(line, ' ');
Erase(params[2], '"');
scene->texts.AddFont(params[1].c_str(), params[2].c_str());
}
void UseMaterialDash(std::string &line, std::string &passed, Scene *scene)
{
//Get material name
std::string matName = Split(passed, ' ')[1];
//Filter command parameters
sVec splits = Split(line, ' ');
//Remove quotes
Erase(splits[1], '"');
//Add correct uniform looking at type
if (splits[0] == "-col")
{
scene->materials.Get(matName)->AddColor(
splits[1].c_str(),
std::stof(splits[2]),
std::stof(splits[3]),
std::stof(splits[4]),
std::stof(splits[5]));
}
else if (splits[0] == "-tex")
{
scene->materials.Get(matName)->AddTexture(
splits[1].c_str(),
*scene->textures.Get(splits[2]));
}
else if (splits[0] == "-flt")
{
scene->materials.Get(matName)->AddFloat(
splits[1].c_str(),
std::stof(splits[2]));
}
else if (splits[0] == "-int")
{
scene->materials.Get(matName)->AddInt(
splits[1].c_str(),
std::stoi(splits[2]));
}
}
void UseObjectDash(std::string &line, std::string &passed, Scene *scene)
{
//Get last obj string
std::string last = Split(passed, ' ')[1];
//Split up parameters
sVec splits = SplitParams(line);
std::string type = splits[0];
Erase(type, '-');
splits.erase(splits.begin());
//Split param names and values
sVec names;
sVec values;
GetNamesNValues(&names, &values, splits);
//Add stuff to map
std::unordered_map<std::string, sVec> parameters;
for (int i = 0; i < names.size(); i++)
{
sVec vals = Split(values[i], ',');
parameters.insert(std::make_pair(names[i], vals));
}
//Call component listing
void *t = CompConstruct::Create(type, scene->GetObject(last), ¶meters);
//Error handling (not great but can hopefully kinda work for now)
if (t == nullptr)
ERROR(("Could not create component with: \n" + line).c_str());
}
void SceneLoader::LoadScene(const char *path, Scene **inScene, bool setCurrent)
{
//Make sure its empty
if (*inScene != nullptr)
ERROR("Empty scene expected in LoadScene(). Pass a scene pointer holding nullptr instead.");
//Construct scene
Scene *scene = new Scene();
//Open file
std::ifstream file = std::ifstream(path);
if (!file.is_open())
ERROR(((std::string)"Could not load .lilscn file with the path:\n" + path).c_str());
//Keep track of commands that have -'s after the line
std::string passedLine;
//Go through lines
std::string line;
while (std::getline(file, line))
{
if (line.substr(0, 2) == "//") //Comment
{
continue;
}
else if (line == "") //White line
{
continue;
}
if (line.substr(0, 3) == "mdl") //Model
{
ReadModelCmd(line, scene);
}
else if (line.substr(0, 3) == "tex") //Texture
{
ReadTextureCmd(line, scene);
}
else if (line.substr(0, 3) == "shd") //Shader
{
ReadShaderCmd(line, scene);
}
else if (line.substr(0, 3) == "mat") //Material
{
passedLine = line;
ReadMaterialCmd(line, scene);
}
else if (line.substr(0, 3) == "obj") //Object
{
passedLine = line;
ReadObjectCmd(line, scene);
}
else if (line[0] == '-')
{
//Decide parameter type
if (passedLine.substr(0, 3) == "mat")
UseMaterialDash(line, passedLine, scene);
else if (passedLine.substr(0, 3) == "obj")
UseObjectDash(line, passedLine, scene);
}
else if (line.substr(0, 3) == "amb") //Ambient color
{
sVec params = Split(line, ' ');
scene->ambient = glm::vec3(
std::stof(params[1]),
std::stof(params[2]),
std::stof(params[3])
);
}
else if (line.substr(0, 3) == "clr") //Clear color
{
sVec params = Split(line, ' ');
scene->clearColor = glm::vec3(
std::stof(params[1]),
std::stof(params[2]),
std::stof(params[3])
);
}
else if (line.substr(0, 3) == "fnt") //Font
{
ReadFontCmd(line, scene);
}
else //Not a valid command type
{
ERROR(("Invalid command type: \n" + line).c_str());
}
}
//Set scene as loaded
scene->isLoaded = true;
//Set current if necessary
if (setCurrent)
SceneManager::SetScene(scene);
//Assign input pointer
*inScene = scene;
}
| 22.42029 | 94 | 0.632321 | [
"object",
"vector",
"model"
] |
d813aa224151a0881ff46a6ab06601292a247bc8 | 5,701 | cpp | C++ | src/main.cpp | DrXVII/websocket_playground | 221ee76bc57f6038dca3f69cd8c0940518792ac0 | [
"MIT"
] | null | null | null | src/main.cpp | DrXVII/websocket_playground | 221ee76bc57f6038dca3f69cd8c0940518792ac0 | [
"MIT"
] | null | null | null | src/main.cpp | DrXVII/websocket_playground | 221ee76bc57f6038dca3f69cd8c0940518792ac0 | [
"MIT"
] | null | null | null | #include "client_ws.hpp"
#include "server_ws.hpp"
using namespace std;
using WsServer = SimpleWeb::SocketServer<SimpleWeb::WS>;
using WsClient = SimpleWeb::SocketClient<SimpleWeb::WS>;
void replace_char(string* _str, const char _from, const char _to);
int main() {
// WebSocket (WS)-server at port 8080 using 1 thread
WsServer server;
server.config.port = 8080;
// echo WebSocket endpoint
auto &echo = server.endpoint["^/echo/?$"];
echo.on_message =
[](shared_ptr<WsServer::Connection> connection,
shared_ptr<WsServer::Message> message)
{
auto message_str = message->string();
//if(message->fin_rsv_opcode != WS_DATA_TYPE_TXT) {
// cout << "Server: Received non-text data, closing connection"
// << endl;
// connection->send_close(999);
// return;
//}
cout << "Server: Message received: \"" << message_str << "\" "
<< "from " << connection.get() << endl;
cout << "Server: Creating response..." << endl;
replace_char(&message_str, '?', '!');
cout << "Server: Sending response \"" << message_str
<< "\" to " << connection.get() << endl;
auto send_stream = make_shared<WsServer::SendStream>();
*send_stream << message_str;
// connection->send is an asynchronous function
connection->send(send_stream, [](const SimpleWeb::error_code &ec) {
if(ec) {
cout << "Server: Error sending message. " <<
// See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings
"Error: " << ec << ", error message: " << ec.message() << endl;
}
});
};
echo.on_open = [](shared_ptr<WsServer::Connection> connection) {
cout << "Server: Opened connection " << connection.get() << endl;
};
// See RFC 6455 7.4.1. for status codes
echo.on_close = [](shared_ptr<WsServer::Connection> connection, int status, const string & /*reason*/) {
cout << "Server: Closed connection " << connection.get() << " with status code " << status << endl;
};
// See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings
echo.on_error = [](shared_ptr<WsServer::Connection> connection, const SimpleWeb::error_code &ec) {
cout << "Server: Error in connection " << connection.get() << ". "
<< "Error: " << ec << ", error message: " << ec.message() << endl;
};
//--------------------------------------------------------------------------
thread server_thread([&server]() {
// Start WS-server
server.start();
});
// Wait for server to start so that the client can connect
this_thread::sleep_for(chrono::seconds(1));
// Example 4: Client communication with server
// Possible output:
// Server: Opened connection 0x7fcf21600380
// Client: Opened connection
// Client: Sending message: "Hello"
// Server: Message received: "Hello" from 0x7fcf21600380
// Server: Sending message "Hello" to 0x7fcf21600380
// Client: Message received: "Hello"
// Client: Sending close connection
// Server: Closed connection 0x7fcf21600380 with status code 1000
// Client: Closed connection with status code 1000
WsClient client("localhost:8080/echo");
client.on_message = [](shared_ptr<WsClient::Connection> connection, shared_ptr<WsClient::Message> message) {
cout << "Client: Message received: \"" << message->string() << "\"" << endl;
cout << "Client: Sending close connection" << endl;
connection->send_close(1000);
};
client.on_open = [](shared_ptr<WsClient::Connection> connection) {
cout << "Client: Opened connection" << endl;
//remembering things we want to send
vector<string> messages;
//string message = "Hello? Is anybody listening? Am I alone?";
messages.push_back(string("Hello? Is anybody listening? Am I alone?"));
messages.push_back(string("?"));
messages.push_back(string("???"));
messages.push_back(string("!!!"));
messages.push_back(string("? Woot? Yay!"));
auto send_stream = make_shared<WsClient::SendStream>();
for(size_t i {0}; i < messages.size(); ++i) {
cout << "Client: Sending message: \"" << messages[i]
<< "\"" << endl;
*send_stream << messages[i];
connection->send(send_stream);
}
//*send_stream << "before non_text";
//connection->send(send_stream);
//*send_stream << "non_text";
//connection->send(send_stream, nullptr, WS_DATA_TYPE_BIN);
//*send_stream << "after non_text";
//connection->send(send_stream);
};
client.on_close = [](shared_ptr<WsClient::Connection> /*connection*/, int status, const string & /*reason*/) {
cout << "Client: Closed connection with status code " << status << endl;
};
// See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings
client.on_error = [](shared_ptr<WsClient::Connection> /*connection*/, const SimpleWeb::error_code &ec) {
cout << "Client: Error: " << ec << ", error message: " << ec.message() << endl;
};
client.start();
server_thread.join();
}
void replace_char(string* _str, const char _from, const char _to)
{
for(size_t i {0}; i < _str->size(); ++i) {
if((*_str)[i] == _from) {(*_str)[i] = _to;}
}
}
| 38.52027 | 139 | 0.586739 | [
"vector"
] |
d813fe138de37a4b266527e1dbc5ed143e87da2f | 7,058 | cpp | C++ | diffsim_torch3d/arcsim/src/util.cpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/util.cpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/util.cpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "util.hpp"
#include "io.hpp"
#include "mesh.hpp"
#include <algorithm>
#include <cstdarg>
#include <cstdio>
#include <iomanip>
#include <limits>
#include <map>
#include <sstream>
using namespace std;
using torch::Tensor;
inline string stringf (const string &format, ...) {
char buf[256];
va_list args;
va_start(args, format);
vsnprintf(buf, 256, format.c_str(), args);
va_end(args);
return std::string(buf);
}
template <typename T> string name (const T *p) {
stringstream ss;
ss << setw(3) << setfill('0') << hex << ((size_t)p/sizeof(T))%0xfff;
return ss.str();
}
ostream &operator<< (ostream &out, const Vert *vert) {
out << "v:" << name(vert); return out;}
ostream &operator<< (ostream &out, const Node *node) {
out << "n:" << name(node) << node->verts; return out;}
ostream &operator<< (ostream &out, const Edge *edge) {
out << "e:" << name(edge) << "(" << edge->n[0] << "-" << edge->n[1] << ")"; return out;}
ostream &operator<< (ostream &out, const Face *face) {
out << "f:" << name(face) << "(" << face->v[0] << "-" << face->v[1] << "-" << face->v[2] << ")"; return out;}
Tensor sgn(Tensor x){return (x>=0)*ONE-(x<0)*ONE;}
int solve_quadratic (Tensor a, Tensor b, Tensor c, Tensor x[2]) {
// http://en.wikipedia.org/wiki/Quadratic_formula#Floating_point_implementation
Tensor d = b*b - 4*a*c;
if ((d < 0).item<int>()) {
x[0] = -b/(2*a);
return 0;
}
Tensor q = -(b + sgn(b).to(torch::kF64)*sqrt(d))/2;
int i = 0;
if ((abs(a) > 1e-12*abs(q)).item<int>())
x[i++] = q/a;
if ((abs(q) > 1e-12*abs(c)).item<int>())
x[i++] = c/q;
if (i==2 && (x[0] > x[1]).item<int>())
swap(x[0], x[1]);
return i;
}
int solve_quadratic (double a, double b, double c, double x[2]) {
// http://en.wikipedia.org/wiki/Quadratic_formula#Floating_point_implementation
double d = b*b - 4*a*c;
if (d < 0) {
x[0] = -b/(2*a);
return 0;
}
double q = -(b + sqrt(d))/2;
double q1 = -(b - sqrt(d))/2;
int i = 0;
if (abs(a) > 1e-12) {
x[i++] = q/a;
x[i++] = q1/a;
} else {
x[i++] = -c/b;
}
if (i==2 && x[0] > x[1])
swap(x[0], x[1]);
return i;
}
double newtons_method (double a, double b, double c, double d, double x0,
int init_dir) {
if (init_dir != 0) {
// quadratic approximation around x0, assuming y' = 0
double y0 = d + x0*(c + x0*(b + x0*a)),
ddy0 = 2*b + (x0+init_dir*1e-6)*(6*a);
x0 += init_dir*sqrt(abs(2*y0/ddy0));
}
for (int iter = 0; iter < 100; iter++) {
double y = d + x0*(c + x0*(b + x0*a));
double dy = c + x0*(2*b + x0*3*a);
if (dy == 0)
return x0;
double x1 = x0 - y/dy;
if (abs(x0 - x1) < 1e-6)
return x0;
x0 = x1;
}
return x0;
}
Tensor solve_cubic_forward(Tensor aa, Tensor bb, Tensor cc, Tensor dd){
double a = aa.item<double>(), b = bb.item<double>();
double c = cc.item<double>(), d = dd.item<double>();
double xc[2], x[3];
x[0]=x[1]=x[2]=-1;
xc[0]=xc[1]=-1;
int ncrit = solve_quadratic(3*a, 2*b, c, xc);
if (ncrit == 0) {
x[0] = newtons_method(a, b, c, d, xc[0], 0);
return torch::tensor({x[0]},TNOPT);
} else if (ncrit == 1) {// cubic is actually quadratic
int nsol = solve_quadratic(b, c, d, x);
return torch::tensor(vector<double>(x,x+nsol), TNOPT);
} else {
double yc[2] = {d + xc[0]*(c + xc[0]*(b + xc[0]*a)),
d + xc[1]*(c + xc[1]*(b + xc[1]*a))};
int i = 0;
if (yc[0]*a >= 0)
x[i++] = newtons_method(a, b, c, d, xc[0], -1);
if (yc[0]*yc[1] <= 0) {
int closer = abs(yc[0])<abs(yc[1]) ? 0 : 1;
x[i++] = newtons_method(a, b, c, d, xc[closer], closer==0?1:-1);
}
if (yc[1]*a <= 0)
x[i++] = newtons_method(a, b, c, d, xc[1], 1);
return torch::tensor(vector<double>(x,x+i), TNOPT);
}
}
Tensor solve_cubic(Tensor a, Tensor b, Tensor c, Tensor d){
py::object func = py::module::import("util_py").attr("solve_cubic");
Tensor ans = func(a, b, c, d).cast<Tensor>();
// Tensor ans = solve_cubic_forward(a, b, c, d);
return ans;
}
vector<Tensor> solve_cubic_backward(Tensor dldz, Tensor ans, Tensor a, Tensor b, Tensor c, Tensor d) {
Tensor dldd = dldz / (ans*(3*a*ans+2*b)+c);
Tensor dldc = dldd * ans;
Tensor dldb = dldc * ans;
Tensor dlda = dldb * ans;
return {dlda, dldb, dldc, dldd};
}
bool is_seam_or_boundary (const Vert *v) {
return is_seam_or_boundary(v->node);
}
bool is_seam_or_boundary (const Node *n) {
for (int e = 0; e < n->adje.size(); e++)
if (is_seam_or_boundary(n->adje[e]))
return true;
return false;
}
bool is_seam_or_boundary (const Edge *e) {
return !e->adjf[0] || !e->adjf[1] || edge_vert(e,0,0) != edge_vert(e,1,0);
}
bool is_seam_or_boundary (const Face *f) {
return is_seam_or_boundary(f->adje[0])
|| is_seam_or_boundary(f->adje[1])
|| is_seam_or_boundary(f->adje[2]);
}
void debug_save_meshes (const vector<Mesh*> &meshvec, const string &name,
int n) {
static map<string,int> savecount;
if (n == -1)
n = savecount[name];
else
savecount[name] = n;
save_objs(meshvec, stringf("tmp/%s%04d", name.c_str(), n));
savecount[name]++;
}
void debug_save_mesh (const Mesh &mesh, const string &name, int n) {
static map<string,int> savecount;
if (n == -1)
n = savecount[name];
else
savecount[name] = n;
save_obj(mesh, stringf("tmp/%s%04d.obj", name.c_str(), n));
savecount[name]++;
}
| 33.292453 | 113 | 0.579201 | [
"mesh",
"object",
"vector"
] |
d8165af4b181c5070385b31514054b6973a7e791 | 9,590 | hpp | C++ | src/main/resources/FactParser.hpp | HarvardPL/formulog | 508c7688bbe826a6951cc8c3e70026e57548e044 | [
"Apache-2.0"
] | 109 | 2019-05-10T16:51:36.000Z | 2022-03-13T02:39:31.000Z | src/main/resources/FactParser.hpp | HarvardPL/formulog | 508c7688bbe826a6951cc8c3e70026e57548e044 | [
"Apache-2.0"
] | 11 | 2020-12-03T18:37:29.000Z | 2022-02-14T17:11:34.000Z | src/main/resources/FactParser.hpp | HarvardPL/formulog | 508c7688bbe826a6951cc8c3e70026e57548e044 | [
"Apache-2.0"
] | 5 | 2019-10-08T10:00:27.000Z | 2021-02-22T17:06:05.000Z | #pragma once
#include <cmath>
#include <iostream>
#include <limits>
#include <string>
// The Souffle header is here just to make sure that it is pulled in before the
// Antlr one, since the latter unsets the EOF macro it depends on.
#include <souffle/CompiledSouffle.h>
#include <antlr4-runtime.h>
#include "parsing/FormulogParser.h"
#include "parsing/FormulogLexer.h"
#include "parsing/FormulogBaseVisitor.h"
#include "Term.hpp"
#include "rels.hpp"
namespace flg {
using namespace std;
using namespace antlr4;
class TermParser : private FormulogBaseVisitor {
public:
term_ptr parse(FormulogParser::TermContext* ctx);
private:
term_ptr* parse(vector<FormulogParser::TermContext*> ctxs);
antlrcpp::Any visitHoleTerm(FormulogParser::HoleTermContext* ctx) override;
antlrcpp::Any visitVarTerm(FormulogParser::VarTermContext* ctx) override;
antlrcpp::Any visitStringTerm(FormulogParser::StringTermContext* ctx) override;
antlrcpp::Any visitConsTerm(FormulogParser::ConsTermContext* ctx) override;
antlrcpp::Any visitIndexedFunctor(FormulogParser::IndexedFunctorContext* ctx) override;
antlrcpp::Any visitFoldTerm(FormulogParser::FoldTermContext* ctx) override;
antlrcpp::Any visitTupleTerm(FormulogParser::TupleTermContext* ctx) override;
antlrcpp::Any visitI32Term(FormulogParser::I32TermContext* ctx) override;
antlrcpp::Any visitI64Term(FormulogParser::I64TermContext* ctx) override;
antlrcpp::Any visitFloatTerm(FormulogParser::FloatTermContext* ctx) override;
antlrcpp::Any visitDoubleTerm(FormulogParser::DoubleTermContext* ctx) override;
antlrcpp::Any visitSpecialFPTerm(FormulogParser::SpecialFPTermContext* ctx) override;
antlrcpp::Any visitRecordTerm(FormulogParser::RecordTermContext* ctx) override;
antlrcpp::Any visitRecordUpdateTerm(FormulogParser::RecordUpdateTermContext* ctx) override;
antlrcpp::Any visitUnopTerm(FormulogParser::UnopTermContext* ctx) override;
antlrcpp::Any visitBinopTerm(FormulogParser::BinopTermContext* ctx) override;
antlrcpp::Any visitListTerm(FormulogParser::ListTermContext* ctx) override;
antlrcpp::Any visitParensTerm(FormulogParser::ParensTermContext* ctx) override;
antlrcpp::Any visitFormulaTerm(FormulogParser::FormulaTermContext* ctx) override;
antlrcpp::Any visitNotFormula(FormulogParser::NotFormulaContext* ctx) override;
antlrcpp::Any visitBinopFormula(FormulogParser::BinopFormulaContext* ctx) override;
antlrcpp::Any visitLetFormula(FormulogParser::LetFormulaContext* ctx) override;
antlrcpp::Any visitQuantifiedFormula(FormulogParser::QuantifiedFormulaContext* ctx) override;
antlrcpp::Any visitIteTerm(FormulogParser::IteTermContext* ctx) override;
antlrcpp::Any visitTermSymFormula(FormulogParser::TermSymFormulaContext* ctx) override;
antlrcpp::Any visitMatchExpr(FormulogParser::MatchExprContext* ctx) override;
antlrcpp::Any visitLetExpr(FormulogParser::LetExprContext* ctx) override;
antlrcpp::Any visitLetFunExpr(FormulogParser::LetFunExprContext* ctx) override;
antlrcpp::Any visitIfExpr(FormulogParser::IfExprContext* ctx) override;
static antlrcpp::Any die(const string& feature);
};
term_ptr* TermParser::parse(vector<FormulogParser::TermContext*> ctxs) {
term_ptr* a = new term_ptr[ctxs.size()];
size_t i{0};
for (auto& ctx : ctxs) {
const term_ptr& t = parse(ctx);
a[i++] = t;
}
return a;
}
antlrcpp::Any TermParser::visitHoleTerm(FormulogParser::HoleTermContext* ctx) {
return die("hole terms");
}
antlrcpp::Any TermParser::visitVarTerm(FormulogParser::VarTermContext* ctx) {
return die("variables");
}
antlrcpp::Any TermParser::visitStringTerm(FormulogParser::StringTermContext* ctx) {
string s = ctx->QSTRING()->getText();
s = s.substr(1, s.length() - 2);
return Term::make<string>(s);
}
antlrcpp::Any TermParser::visitConsTerm(FormulogParser::ConsTermContext* ctx) {
return Term::make(Symbol::cons, 2, parse(ctx->term()));
}
antlrcpp::Any TermParser::visitIndexedFunctor(FormulogParser::IndexedFunctorContext* ctx) {
if (!ctx->parameterList()->parameter().empty()) {
die("parameterized terms");
}
string name = ctx->id->getText();
if (name == "true") {
return Term::make<bool>(true);
}
if (name == "false") {
return Term::make<bool>(false);
}
auto sym = lookup_symbol(name);
auto arity = symbol_arity(sym);
auto args = parse(ctx->termArgs()->term());
return Term::make(sym, arity, args);
}
antlrcpp::Any TermParser::visitFoldTerm(FormulogParser::FoldTermContext* ctx) {
return die("fold");
}
antlrcpp::Any TermParser::visitTupleTerm(FormulogParser::TupleTermContext* ctx) {
auto terms = ctx->tuple()->term();
auto arity = terms.size();
auto sym = lookup_tuple_symbol(arity);
auto args = parse(terms);
return Term::make(sym, arity, args);
}
antlrcpp::Any TermParser::visitI32Term(FormulogParser::I32TermContext* ctx) {
return Term::make<int32_t>(stoi(ctx->val->getText(), nullptr, 0));
}
antlrcpp::Any TermParser::visitI64Term(FormulogParser::I64TermContext* ctx) {
return Term::make<int64_t>(stoll(ctx->val->getText(), nullptr, 0));
}
antlrcpp::Any TermParser::visitFloatTerm(FormulogParser::FloatTermContext* ctx) {
return Term::make<float>(stof(ctx->val->getText()));
}
antlrcpp::Any TermParser::visitDoubleTerm(FormulogParser::DoubleTermContext* ctx) {
return Term::make<double>(stod(ctx->val->getText()));
}
antlrcpp::Any TermParser::visitSpecialFPTerm(FormulogParser::SpecialFPTermContext* ctx) {
switch (ctx->val->getType()) {
case FormulogParser::FP32_NAN:
return Term::make<float>(nanf(""));
case FormulogParser::FP32_POS_INFINITY:
return Term::make<float>(numeric_limits<float>::infinity());
case FormulogParser::FP32_NEG_INFINITY:
return Term::make<float>(-numeric_limits<float>::infinity());
case FormulogParser::FP64_NAN:
return Term::make<double>(nan(""));
case FormulogParser::FP64_POS_INFINITY:
return Term::make<double>(numeric_limits<double>::infinity());
case FormulogParser::FP64_NEG_INFINITY:
return Term::make<double>(-numeric_limits<double>::infinity());
}
__builtin_unreachable();
}
antlrcpp::Any TermParser::visitRecordTerm(FormulogParser::RecordTermContext* ctx) {
return die("records");
}
antlrcpp::Any TermParser::visitRecordUpdateTerm(FormulogParser::RecordUpdateTermContext* ctx) {
return die("record updates");
}
antlrcpp::Any TermParser::visitUnopTerm(FormulogParser::UnopTermContext* ctx) {
return die("unops");
}
antlrcpp::Any TermParser::visitBinopTerm(FormulogParser::BinopTermContext* ctx) {
return die("binops");
}
antlrcpp::Any TermParser::visitListTerm(FormulogParser::ListTermContext* ctx) {
auto l = Term::make(Symbol::nil, 0, new term_ptr[0]);
auto terms = ctx->list()->term();
for (auto it = terms.rbegin(); it != terms.rend(); ++it) {
auto val = parse(*it);
l = Term::make(Symbol::cons, 2, new term_ptr[2] { val, l });
}
return l;
}
antlrcpp::Any TermParser::visitParensTerm(FormulogParser::ParensTermContext* ctx) {
return parse(ctx->term());
}
antlrcpp::Any TermParser::visitFormulaTerm(FormulogParser::FormulaTermContext* ctx) {
return die("formulas");
}
antlrcpp::Any TermParser::visitNotFormula(FormulogParser::NotFormulaContext* ctx) {
return die("formulas");
}
antlrcpp::Any TermParser::visitBinopFormula(FormulogParser::BinopFormulaContext* ctx) {
return die("formulas");
}
antlrcpp::Any TermParser::visitLetFormula(FormulogParser::LetFormulaContext* ctx) {
return die("formulas");
}
antlrcpp::Any TermParser::visitQuantifiedFormula(FormulogParser::QuantifiedFormulaContext* ctx) {
return die("formulas");
}
antlrcpp::Any TermParser::visitIteTerm(FormulogParser::IteTermContext* ctx) {
return die("formulas");
}
antlrcpp::Any TermParser::visitTermSymFormula(FormulogParser::TermSymFormulaContext* ctx) {
return die("formula variables");
}
antlrcpp::Any TermParser::visitMatchExpr(FormulogParser::MatchExprContext* ctx) {
return die("match expressions");
}
antlrcpp::Any TermParser::visitLetExpr(FormulogParser::LetExprContext* ctx) {
return die("let expressions");
}
antlrcpp::Any TermParser::visitLetFunExpr(FormulogParser::LetFunExprContext* ctx) {
return die("let fun expressions");
}
antlrcpp::Any TermParser::visitIfExpr(FormulogParser::IfExprContext* ctx) {
return die("if expressions");
}
antlrcpp::Any TermParser::die(const string& feature) {
cerr << "Feature unsupported in external EDBs: " << feature << endl;
abort();
return nullptr;
}
term_ptr TermParser::parse(FormulogParser::TermContext* ctx) {
term_ptr res = ctx->accept(this);
return res;
}
template <typename T>
struct FactParser {
void parse(const string& file, T& rel);
private:
TermParser term_parser;
void parse(FormulogParser::TabSeparatedTermLineContext* line, T& rel);
};
template <typename T>
void FactParser<T>::parse(const string& file, T& rel) {
ifstream stream;
stream.open(file);
ANTLRInputStream input(stream);
FormulogLexer lexer(&input);
BufferedTokenStream tokens(&lexer);
FormulogParser parser(&tokens);
FormulogParser::TsvFileContext* tree = parser.tsvFile();
for (auto& line : tree->tabSeparatedTermLine()) {
parse(line, rel);
}
}
template <typename T>
void FactParser<T>::parse(FormulogParser::TabSeparatedTermLineContext* line, T& rel) {
Tuple<T::arity> tup;
auto terms = line->term();
if (terms.size() != T::arity) {
cerr << "Wrong number of terms" << endl;
abort();
}
size_t i{0};
for (auto& term_ctx : terms) {
tup[i++] = term_parser.parse(term_ctx);
}
rel.insert(tup);
}
} // namespace flg
| 34.007092 | 97 | 0.745255 | [
"vector"
] |
d8192db11401b4de9aef3dc2b248192460747ecd | 52,301 | cpp | C++ | Src/SettingsUI.cpp | slgoldberg/LiveTraffic | 3a051853d2a75151a912be736ca325e03c72b07c | [
"MIT"
] | null | null | null | Src/SettingsUI.cpp | slgoldberg/LiveTraffic | 3a051853d2a75151a912be736ca325e03c72b07c | [
"MIT"
] | null | null | null | Src/SettingsUI.cpp | slgoldberg/LiveTraffic | 3a051853d2a75151a912be736ca325e03c72b07c | [
"MIT"
] | null | null | null | //
// SettingsUI.cpp
// LiveTraffic
/*
* Copyright (c) 2018, Birger Hoppe
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "LiveTraffic.h"
//
//MARK: LTSettingsUI
//
LTSettingsUI::LTSettingsUI () :
widgetIds(nullptr)
{}
LTSettingsUI::~LTSettingsUI()
{
// just in case...
Disable();
}
//
//MARK: Window Structure
// Basics | Debug
//
// indexes into the below definition array, must be kept in synch with the same
enum UI_WIDGET_IDX_T {
UI_MAIN_WND = 0,
// Buttons to select 'tabs'
UI_BTN_BASICS,
UI_BTN_AC_LABELS,
UI_BTN_ADVANCED,
UI_BTN_CSL,
UI_BTN_DEBUG,
UI_BTN_HELP,
// "Basics" tab
UI_BASICS_LIVE_SUB_WND,
UI_BASICS_BTN_ENABLE,
UI_BASICS_BTN_AUTO_START,
UI_BASICS_CAP_FDCHANNELS,
UI_BASICS_BTN_OPENSKY_LIVE,
UI_BASICS_BTN_OPENSKY_MASTERDATA,
UI_BASICS_BTN_ADSB_LIVE,
UI_BASICS_TXT_ADSB_API_KEY,
UI_BASICS_BTN_REALTRAFFIC_LIVE,
UI_BASICS_CAP_REALTRAFFIC_STATUS,
UI_BASICS_CAP_REALTRAFFIC_METAR,
UI_BASICS_CAP_VERSION_TXT,
UI_BASICS_CAP_VERSION,
UI_BASICS_RIGHT_SUB_WND,
UI_BASICS_CAP_MISC,
UI_BASICS_BTN_LND_LIGHTS_TAXI,
UI_BASICS_CAP_PARALLEL,
UI_BASICS_CAP_HIDE_BELOW_AGL,
UI_BASICS_INT_HIDE_BELOW_AGL,
UI_BASICS_BTN_HIDE_TAXIING,
UI_BASICS_BTN_AI_ON_REQUEST,
UI_BASICS_CAP_OUTPUT_CHANNELS,
UI_BASICS_BTN_FOREFLIGHT_SEND,
UI_BASICS_INT_FOREFLIGHT_INTVL,
UI_BASICS_CAP_FOREFLIGHT_S,
UI_BASICS_BTN_FOREFLIGHT_USERSPLANE,
UI_BASICS_BTN_FOREFLIGHT_TRAFFIC,
UI_BASICS_CAP_DBG_LIMIT,
// "A/C Labels" tab
UI_LABELS_SUB_WND,
UI_LABELS_CAP_STATIC,
UI_LABELS_BTN_TYPE,
UI_LABELS_BTN_AC_ID,
UI_LABELS_BTN_TRANSP,
UI_LABELS_BTN_REG,
UI_LABELS_BTN_OP,
UI_LABELS_BTN_CALL_SIGN,
UI_LABELS_BTN_FLIGHT_NO,
UI_LABELS_BTN_ROUTE,
UI_LABELS_CAP_DYNAMIC,
UI_LABELS_BTN_PHASE,
UI_LABELS_BTN_HEADING,
UI_LABELS_BTN_ALT,
UI_LABELS_BTN_HEIGHT,
UI_LABELS_BTN_SPEED,
UI_LABELS_BTN_VSI,
UI_LABELS_CAP_COLOR,
UI_LABELS_BTN_DYNAMIC,
UI_LABELS_BTN_FIXED,
UI_LABELS_TXT_COLOR,
UI_LABELS_BTN_YELLOW,
UI_LABELS_BTN_RED,
UI_LABELS_BTN_GREEN,
UI_LABELS_BTN_BLUE,
UI_LABELS_CAP_WHEN,
UI_LABELS_BTN_EXTERNAL,
UI_LABELS_BTN_INTERNAL,
UI_LABELS_BTN_VR,
// "Advanced" tab
UI_ADVCD_SUB_WND,
UI_ADVCD_CAP_LOGLEVEL,
UI_ADVCD_BTN_LOG_FATAL,
UI_ADVCD_BTN_LOG_ERROR,
UI_ADVCD_BTN_LOG_WARNING,
UI_ADVCD_BTN_LOG_INFO,
UI_ADVCD_BTN_LOG_DEBUG,
UI_ADVCD_CAP_MSGAREA_LEVEL,
UI_ADVCD_BTN_MSGAREA_FATAL,
UI_ADVCD_BTN_MSGAREA_ERROR,
UI_ADVCD_BTN_MSGAREA_WARNING,
UI_ADVCD_BTN_MSGAREA_INFO,
UI_ADVCD_CAP_MAX_NUM_AC,
UI_ADVCD_INT_MAX_NUM_AC,
UI_ADVCD_CAP_MAX_FULL_NUM_AC,
UI_ADVCD_INT_MAX_FULL_NUM_AC,
UI_ADVCD_CAP_FULL_DISTANCE,
UI_ADVCD_INT_FULL_DISTANCE,
UI_ADVCD_CAP_FD_STD_DISTANCE,
UI_ADVCD_INT_FD_STD_DISTANCE,
UI_ADVCD_CAP_FD_REFRESH_INTVL,
UI_ADVCD_INT_FD_REFRESH_INTVL,
UI_ADVCD_CAP_FD_BUF_PERIOD,
UI_ADVCD_INT_FD_BUF_PERIOD,
UI_ADVCD_CAP_AC_OUTDATED_INTVL,
UI_ADVCD_INT_AC_OUTDATED_INTVL,
// "CSL" tab
UI_CSL_SUB_WND,
UI_CSL_CAP_PATHS,
UI_CSL_BTN_ENABLE_1,
UI_CSL_TXT_PATH_1,
UI_CSL_BTN_LOAD_1,
UI_CSL_BTN_ENABLE_2,
UI_CSL_TXT_PATH_2,
UI_CSL_BTN_LOAD_2,
UI_CSL_BTN_ENABLE_3,
UI_CSL_TXT_PATH_3,
UI_CSL_BTN_LOAD_3,
UI_CSL_BTN_ENABLE_4,
UI_CSL_TXT_PATH_4,
UI_CSL_BTN_LOAD_4,
UI_CSL_BTN_ENABLE_5,
UI_CSL_TXT_PATH_5,
UI_CSL_BTN_LOAD_5,
UI_CSL_BTN_ENABLE_6,
UI_CSL_TXT_PATH_6,
UI_CSL_BTN_LOAD_6,
UI_CSL_BTN_ENABLE_7,
UI_CSL_TXT_PATH_7,
UI_CSL_BTN_LOAD_7,
UI_CSL_CAP_DEFAULT_AC_TYPE,
UI_CSL_TXT_DEFAULT_AC_TYPE,
UI_CSL_CAP_GROUND_VEHICLE_TYPE,
UI_CSL_TXT_GROUND_VEHICLE_TYPE,
// "Debug" tab
UI_DEBUG_SUB_WND,
UI_DEBUG_CAP_FILTER,
UI_DEBUG_TXT_FILTER,
UI_DEBUG_BTN_LOG_ACPOS,
UI_DEBUG_BTN_LOG_MODELMATCH,
UI_DEBUG_BTN_LOG_RAW_FD,
UI_DEBUG_CAP_CSL_MODEL_MATCHING,
UI_DEBUG_CAP_FIX_AC_ICAO_TYPE,
UI_DEBUG_TXT_FIX_AC_ICAO_TYPE,
UI_DEBUG_CAP_FIX_OP_ICAO,
UI_DEBUG_TXT_FIX_OP_ICAO,
UI_DEBUG_CAP_FIX_LIVERY,
UI_DEBUG_TXT_FIX_LIVERY,
// always last: number of UI elements
UI_NUMBER_OF_ELEMENTS
};
// for ease of definition coordinates start at (0|0)
// window will be centered shortly before presenting it
TFWidgetCreate_t SETTINGS_UI[] =
{
{ 0, 0, 400, 330, 0, "LiveTraffic Settings", 1, NO_PARENT, xpWidgetClass_MainWindow, {xpProperty_MainWindowHasCloseBoxes, 1, xpProperty_MainWindowType,xpMainWindowStyle_Translucent,0,0} },
// Buttons to select 'tabs'
{ 10, 30, 65, 10, 1, "Basics", 0, UI_MAIN_WND, xpWidgetClass_Button, {xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0, 0,0} },
{ 75, 30, 65, 10, 1, "A/C Labels", 0, UI_MAIN_WND, xpWidgetClass_Button, {xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0, 0,0} },
{ 140, 30, 65, 10, 1, "Advanced", 0, UI_MAIN_WND, xpWidgetClass_Button, {xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0, 0,0} },
{ 205, 30, 65, 10, 1, "CSL", 0, UI_MAIN_WND, xpWidgetClass_Button, {xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0, 0,0} },
{ 270, 30, 65, 10, 1, "Debug", 0, UI_MAIN_WND, xpWidgetClass_Button, {xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0, 0,0} },
// Push button for help
{ 360, 30, 30, 10, 1, "?", 0, UI_MAIN_WND, xpWidgetClass_Button, {xpProperty_ButtonBehavior, xpButtonBehaviorPushButton, 0,0, 0,0} },
// "Basics" tab
{ 10, 50, 190, -10, 0, "Basics Live", 0, UI_MAIN_WND, xpWidgetClass_SubWindow, {0,0, 0,0, 0,0} },
{ 10, 10, 10, 10, 1, "Show Live Aircrafts", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 25, 10, 10, 1, "Auto Start", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 5, 50, -5, 10, 1, "Flight Data Channels:",0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 10, 70, 10, 10, 1, "OpenSky Network", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 85, 10, 10, 1, "OpenSky Network Master Data", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 105, 10, 10, 1, "ADS-B Exchange, API Key:", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 120, -5, 15, 1, "", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_TextField, {xpProperty_MaxCharacters,36, 0,0, 0,0} },
{ 10, 150, 10, 10, 1, "RealTraffic", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 5, 165, -5, 10, 1, "", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 5, 180, -5, 10, 1, "", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 5, -15, -5, 10, 1, "Version", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 50, -15, -5, 10, 1, "", 0, UI_BASICS_LIVE_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 200, 50, -10, -10, 0, "Basics Right", 0, UI_MAIN_WND, xpWidgetClass_SubWindow, {0,0, 0,0, 0,0} },
{ 5, 8, -5, 10, 1, "Misc options:", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 10, 25, 10, 10, 1, "Landing lights during taxi", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 5, 50, -5, 10, 1, "Parallel with other traffic plugins:",0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 5, 68, 140, 10, 1, "No a/c below [ft AGL]",0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ -50, 68, -10, 15, 1, "", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,6, 0,0, 0,0} },
{ 10, 85, 10, 10, 1, "Hide a/c while taxiing", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 100, 10, 10, 1, "AI/TCAS on request only", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 5, 125, -5, 10, 1, "Output Channels:", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 10, 140, 10, 10, 1, "ForeFlight | every", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ -50, 138, -15, 15, 1, "", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,6, 0,0, 0,0} },
{ -15, 140, -10, 10, 1, "s", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 25, 155, 10, 10, 1, "User's Plane", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 120, 155, 10, 10, 1, "Traffic", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 5, -15, -5, 10, 1, "", 0, UI_BASICS_RIGHT_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
// "A/C Label" tab
{ 10, 50, -10, -10, 0, "A/C Label", 0, UI_MAIN_WND, xpWidgetClass_SubWindow, {0,0,0,0,0,0} },
{ 5, 10, 190, 10, 1, "Static info:", 0, UI_LABELS_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 10, 30, 10, 10, 1, "ICAO A/C Type Code", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 45, 10, 10, 1, "Any A/C ID", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 60, 10, 10, 1, "Transponder Hex Code",0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 75, 10, 10, 1, "Registration", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 90, 10, 10, 1, "ICAO Operator Code", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 105, 10, 10, 1, "Call Sign", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 120, 10, 10, 1, "Flight Number (rare)",0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 135, 10, 10, 1, "Route", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 200, 10, -10, 10, 1, "Dynamic data:", 0, UI_LABELS_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 200, 30, 10, 10, 1, "Flight Phase", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 200, 45, 10, 10, 1, "Heading", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 200, 60, 10, 10, 1, "Altitude [ft]", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 200, 75, 10, 10, 1, "Height AGL [ft]", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 200, 90, 10, 10, 1, "Speed [kn]", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 200, 105, 10, 10, 1, "VSI [ft/min]", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 5, 155, 50, 10, 1, "Label Color:", 0, UI_LABELS_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 10, 170, 10, 10, 1, "Dynamic by Flight Model",0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 10, 185, 10, 10, 1, "Fixed:", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 60, 182, 60, 15, 1, "", 0, UI_LABELS_SUB_WND, xpWidgetClass_TextField, {xpProperty_MaxCharacters,6, 0,0, 0,0} },
{ 120, 185, 50, 10, 1, "Yellow", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 170, 185, 50, 10, 1, "Red", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 220, 185, 50, 10, 1, "Green", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 270, 185, 50, 10, 1, "Blue", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 5, 205, 50, 10, 1, "In which views to show A/C labels:", 0, UI_LABELS_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 10, 225, 10, 10, 1, "External", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 80, 225, 10, 10, 1, "Internal", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 150, 225, 10, 10, 1, "VR", 0, UI_LABELS_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
// "Advanced" tab
{ 10, 50, -10, -10, 0, "Advanced", 0, UI_MAIN_WND, xpWidgetClass_SubWindow, {0,0,0,0,0,0} },
{ 5, 10, -5, 10, 1, "Log Level:", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 80, 10, 10, 10, 1, "Fatal", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 140, 10, 10, 10, 1, "Error", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 200, 10, 10, 10, 1, "Warning", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 270, 10, 10, 10, 1, "Info", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 320, 10, 10, 10, 1, "Debug", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 5, 30, -5, 10, 1, "Msg Area:", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 80, 30, 10, 10, 1, "Fatal", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 140, 30, 10, 10, 1, "Error", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 200, 30, 10, 10, 1, "Warning", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 270, 30, 10, 10, 1, "Info", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorRadioButton, 0,0} },
{ 5, 50, 225, 10, 1, "Max number of aircrafts", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 230, 50, 50, 15, 1, "", 0, UI_ADVCD_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,3, 0,0, 0,0} },
{ 5, 70, 225, 10, 1, "Max number of full a/c to draw", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 230, 70, 50, 15, 1, "", 0, UI_ADVCD_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,3, 0,0, 0,0} },
{ 5, 90, 225, 10, 1, "Max distance for drawing full a/c [nm]", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 230, 90, 50, 15, 1, "", 0, UI_ADVCD_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,2, 0,0, 0,0} },
{ 5, 110, 225, 10, 1, "Search distance [nm]", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 230, 110, 50, 15, 1, "", 0, UI_ADVCD_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,3, 0,0, 0,0} },
{ 5, 130, 225, 10, 1, "Live data refresh [s]", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 230, 130, 50, 15, 1, "", 0, UI_ADVCD_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,3, 0,0, 0,0} },
{ 5, 150, 225, 10, 1, "Buffering period [s]", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 230, 150, 50, 15, 1, "", 0, UI_ADVCD_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,3, 0,0, 0,0} },
{ 5, 170, 225, 10, 1, "a/c outdated period [s]", 0, UI_ADVCD_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 230, 170, 50, 15, 1, "", 0, UI_ADVCD_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,3, 0,0, 0,0} },
// "CSL" tab
{ 10, 50, -10, -10, 0, "CSL", 0, UI_MAIN_WND, xpWidgetClass_SubWindow, {0,0,0,0,0,0} },
{ 5, 10, -5, 10, 1, "Enabled | Paths to CSL packages:", 0, UI_CSL_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 10, 30, 10, 10, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 25, 27, 300, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField, {0,0, 0,0, 0,0} },
{ 330, 30, 50, 10, 1, "Load", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 10, 50, 10, 10, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 25, 47, 300, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField, {0,0, 0,0, 0,0} },
{ 330, 50, 50, 10, 1, "Load", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 10, 70, 10, 10, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 25, 67, 300, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField, {0,0, 0,0, 0,0} },
{ 330, 70, 50, 10, 1, "Load", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 10, 90, 10, 10, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 25, 87, 300, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField, {0,0, 0,0, 0,0} },
{ 330, 90, 50, 10, 1, "Load", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 10, 110, 10, 10, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 25, 107, 300, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField, {0,0, 0,0, 0,0} },
{ 330, 110, 50, 10, 1, "Load", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 10, 130, 10, 10, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 25, 127, 300, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField, {0,0, 0,0, 0,0} },
{ 330, 130, 50, 10, 1, "Load", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 10, 150, 10, 10, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 25, 147, 300, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField, {0,0, 0,0, 0,0} },
{ 330, 150, 50, 10, 1, "Load", 0, UI_CSL_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpPushButton, xpProperty_ButtonBehavior,xpButtonBehaviorPushButton, 0,0} },
{ 5, 230, 130, 10, 1, "Default a/c type", 0, UI_CSL_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 135, 227, 50, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,4, 0,0, 0,0} },
{ 5, 250, 130, 10, 1, "Ground vehicle type", 0, UI_CSL_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 135, 247, 50, 15, 1, "", 0, UI_CSL_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,4, 0,0, 0,0} },
// "Debug" tab
{ 10, 50, -10, -10, 0, "Debug", 0, UI_MAIN_WND, xpWidgetClass_SubWindow, {0,0,0,0,0,0} },
{ 5, 10, 215, 10, 1, "Filter for transponder hex code:", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 220, 10, 70, 15, 1, "", 0, UI_DEBUG_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,8, 0,0, 0,0} },
{ 10, 30, 10, 10, 1, "Debug: Log a/c positions", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 45, 10, 10, 1, "Debug: Log model matching (XPlaneMP)", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 10, 60, 10, 10, 1, "Debug: Log raw network flight data (LTRawFD.log)", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Button, {xpProperty_ButtonType, xpRadioButton, xpProperty_ButtonBehavior, xpButtonBehaviorCheckBox, 0,0} },
{ 5, 80, -5, 10, 1, "Forced model matching parameters for next aircrafts to create:", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 5, 95, 215, 10, 1, "ICAO a/c type:", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 220, 95, 70, 15, 1, "", 0, UI_DEBUG_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,4, 0,0, 0,0} },
{ 5, 115, 215, 10, 1, "ICAO operator/airline:", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 220, 115, 70, 15, 1, "", 0, UI_DEBUG_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,3, 0,0, 0,0} },
{ 5, 135, 215, 10, 1, "livery/registration:", 0, UI_DEBUG_SUB_WND, xpWidgetClass_Caption, {0,0, 0,0, 0,0} },
{ 220, 135, 70, 15, 1, "", 0, UI_DEBUG_SUB_WND, xpWidgetClass_TextField,{xpProperty_MaxCharacters,8, 0,0, 0,0} },
};
constexpr int NUM_WIDGETS = sizeof(SETTINGS_UI)/sizeof(SETTINGS_UI[0]);
static_assert(UI_NUMBER_OF_ELEMENTS == NUM_WIDGETS,
"UI_WIDGET_IDX_T and SETTINGS_UI[] differ in number of elements!");
// creates the main window and all its widgets based on the above
// definition array
void LTSettingsUI::Enable()
{
if (!isEnabled()) {
// array, which receives ids of all created widgets
widgetIds = new XPWidgetID[NUM_WIDGETS];
LOG_ASSERT(widgetIds);
memset(widgetIds, 0, sizeof(XPWidgetID)*NUM_WIDGETS );
// create all widgets, i.e. the entire window structure, but keep invisible
if (!TFUCreateWidgetsEx(SETTINGS_UI, NUM_WIDGETS, NULL, widgetIds,
GetDefaultWndOpenMode()))
{
SHOW_MSG(logERR,ERR_WIDGET_CREATE);
return;
}
setId(widgetIds[0]); // register in base class for message handling
// some widgets with objects
subBasicsLive.setId(widgetIds[UI_BASICS_LIVE_SUB_WND]);
subBasicsRight.setId(widgetIds[UI_BASICS_RIGHT_SUB_WND]);
subAcLabel.setId(widgetIds[UI_LABELS_SUB_WND]);
subAdvcd.setId(widgetIds[UI_ADVCD_SUB_WND]);
subCSL.setId(widgetIds[UI_CSL_SUB_WND]);
subDebug.setId(widgetIds[UI_DEBUG_SUB_WND]);
// organise the tab button group
tabGrp.Add({
widgetIds[UI_BTN_BASICS],
widgetIds[UI_BTN_AC_LABELS],
widgetIds[UI_BTN_ADVANCED],
widgetIds[UI_BTN_CSL],
widgetIds[UI_BTN_DEBUG]
});
tabGrp.SetChecked(widgetIds[UI_BTN_BASICS]);
HookButtonGroup(tabGrp);
// *** Basic ***
// the following widgets are linked to dataRefs,
// i.e. the dataRefs are changed automatically as soon as the
// widget's status/contents changes. This in turn
// directly controls LiveTraffic (see class DataRefs,
// which receives the callbacks for the changed dataRefs)
// Class LTSettingsUI has no more code for handling these:
btnBasicsEnable.setId(widgetIds[UI_BASICS_BTN_ENABLE],
DATA_REFS_LT[DR_CFG_AIRCRAFTS_DISPLAYED]);
btnBasicsAutoStart.setId(widgetIds[UI_BASICS_BTN_AUTO_START],
DATA_REFS_LT[DR_CFG_AUTO_START]);
btnOpenSkyLive.setId(widgetIds[UI_BASICS_BTN_OPENSKY_LIVE],
DATA_REFS_LT[DR_CHANNEL_OPEN_SKY_ONLINE]);
btnOpenSkyMasterdata.setId(widgetIds[UI_BASICS_BTN_OPENSKY_MASTERDATA],
DATA_REFS_LT[DR_CHANNEL_OPEN_SKY_AC_MASTERDATA]);
btnADSBLive.setId(widgetIds[UI_BASICS_BTN_ADSB_LIVE],
DATA_REFS_LT[DR_CHANNEL_ADSB_EXCHANGE_ONLINE]);
txtADSBAPIKey.setId(widgetIds[UI_BASICS_TXT_ADSB_API_KEY]);
if (dataRefs.GetADSBExAPIKey().empty()) { // no API key
btnADSBLive.Set(0); // disable channel
btnADSBLive.SetEnabled(false); // disable check box
}
else
txtADSBAPIKey.SetDescriptor(dataRefs.GetADSBExAPIKey());
btnRealTraffic.setId(widgetIds[UI_BASICS_BTN_REALTRAFFIC_LIVE],
DATA_REFS_LT[DR_CHANNEL_REAL_TRAFFIC_ONLINE]);
capRealTrafficStatus.setId(widgetIds[UI_BASICS_CAP_REALTRAFFIC_STATUS]);
capRealTrafficMetar.setId(widgetIds[UI_BASICS_CAP_REALTRAFFIC_METAR]);
UpdateRealTraffic();
// * right-hand side *
// landing lights during taxi?
btnLndLightsTaxi.setId(widgetIds[UI_BASICS_BTN_LND_LIGHTS_TAXI],
DATA_REFS_LT[DR_CFG_LND_LIGHTS_TAXI]);
// enhance parallel operation with other multiplayer clients
intHideBelowAGL.setId(widgetIds[UI_BASICS_INT_HIDE_BELOW_AGL],
DATA_REFS_LT[DR_CFG_HIDE_BELOW_AGL]);
// hide a/c while taxiing?
btnHideTaxiing.setId(widgetIds[UI_BASICS_BTN_HIDE_TAXIING],
DATA_REFS_LT[DR_CFG_HIDE_TAXIING]);
// AI/TCAS on request only?
btnAIonRequest.setId(widgetIds[UI_BASICS_BTN_AI_ON_REQUEST],
DATA_REFS_LT[DR_CFG_AI_ON_REQUEST]);
// ForeFlight
btnForeFlight.setId(widgetIds[UI_BASICS_BTN_FOREFLIGHT_SEND],
DATA_REFS_LT[DR_CHANNEL_FORE_FLIGHT_SENDER]);
intFFTrfcIntvl.setId(widgetIds[UI_BASICS_INT_FOREFLIGHT_INTVL],
DATA_REFS_LT[DR_CFG_FF_SEND_TRAFFIC_INTVL]);
btnFFUsersPlane.setId(widgetIds[UI_BASICS_BTN_FOREFLIGHT_USERSPLANE],
DATA_REFS_LT[DR_CFG_FF_SEND_USER_PLANE]);
btnFFTraffic.setId(widgetIds[UI_BASICS_BTN_FOREFLIGHT_TRAFFIC],
DATA_REFS_LT[DR_CFG_FF_SEND_TRAFFIC]);
// version number
XPSetWidgetDescriptor(widgetIds[UI_BASICS_CAP_VERSION],
LT_VERSION_FULL);
if (LT_BETA_VER_LIMIT)
{
char dbgLimit[100];
snprintf(dbgLimit,sizeof(dbgLimit), BETA_LIMITED_VERSION,LT_BETA_VER_LIMIT_TXT);
XPSetWidgetDescriptor(widgetIds[UI_BASICS_CAP_DBG_LIMIT],
dbgLimit);
}
// *** A/C Labels ***
drCfgLabels.setDataRef(DATA_REFS_LT[DR_CFG_LABELS]);
drCfgLabelShow.setDataRef(DATA_REFS_LT[DR_CFG_LABEL_SHOWN]);
LabelBtnInit();
// Color
btnGrpLabelColorDyn.Add({
widgetIds[UI_LABELS_BTN_DYNAMIC],
widgetIds[UI_LABELS_BTN_FIXED]
});
btnGrpLabelColorDyn.SetChecked(dataRefs.IsLabelColorDynamic() ?
widgetIds[UI_LABELS_BTN_DYNAMIC] :
widgetIds[UI_LABELS_BTN_FIXED]
);
HookButtonGroup(btnGrpLabelColorDyn);
drLabelColDyn.setDataRef(DATA_REFS_LT[DR_CFG_LABEL_COL_DYN]);
intLabelColor.setId(widgetIds[UI_LABELS_TXT_COLOR],
DATA_REFS_LT[DR_CFG_LABEL_COLOR],
TFTextFieldWidget::TFF_HEX);
// *** Advanced ***
logLevelGrp.Add({
widgetIds[UI_ADVCD_BTN_LOG_DEBUG], // index 0 equals logDEBUG, which is also 0
widgetIds[UI_ADVCD_BTN_LOG_INFO], // ...
widgetIds[UI_ADVCD_BTN_LOG_WARNING],
widgetIds[UI_ADVCD_BTN_LOG_ERROR],
widgetIds[UI_ADVCD_BTN_LOG_FATAL], // index 4 equals logFATAL, which is also 4
});
logLevelGrp.SetCheckedIndex(dataRefs.GetLogLevel());
HookButtonGroup(logLevelGrp);
msgAreaLevelGrp.Add({
widgetIds[UI_ADVCD_BTN_MSGAREA_INFO], // index 0 is logINFO, which is 1
widgetIds[UI_ADVCD_BTN_MSGAREA_WARNING],
widgetIds[UI_ADVCD_BTN_MSGAREA_ERROR],
widgetIds[UI_ADVCD_BTN_MSGAREA_FATAL], // index 4 equals logFATAL, which is also 4
});
msgAreaLevelGrp.SetCheckedIndex(dataRefs.GetMsgAreaLevel() - 1);
HookButtonGroup(msgAreaLevelGrp);
// link some buttons directly to dataRefs:
intMaxNumAc.setId(widgetIds[UI_ADVCD_INT_MAX_NUM_AC],
DATA_REFS_LT[DR_CFG_MAX_NUM_AC]);
intMaxFullNumAc.setId(widgetIds[UI_ADVCD_INT_MAX_FULL_NUM_AC],
DATA_REFS_LT[DR_CFG_MAX_FULL_NUM_AC]);
intFullDistance.setId(widgetIds[UI_ADVCD_INT_FULL_DISTANCE],
DATA_REFS_LT[DR_CFG_FULL_DISTANCE]);
intFdStdDistance.setId(widgetIds[UI_ADVCD_INT_FD_STD_DISTANCE],
DATA_REFS_LT[DR_CFG_FD_STD_DISTANCE]);
intFdRefreshIntvl.setId(widgetIds[UI_ADVCD_INT_FD_REFRESH_INTVL],
DATA_REFS_LT[DR_CFG_FD_REFRESH_INTVL]);
intFdBufPeriod.setId(widgetIds[UI_ADVCD_INT_FD_BUF_PERIOD],
DATA_REFS_LT[DR_CFG_FD_BUF_PERIOD]);
intAcOutdatedIntvl.setId(widgetIds[UI_ADVCD_INT_AC_OUTDATED_INTVL],
DATA_REFS_LT[DR_CFG_AC_OUTDATED_INTVL]);
// *** CSL ***
// Initialize all paths (3 elements each: check box, text field, button)
const DataRefs::vecCSLPaths& paths = dataRefs.GetCSLPaths();
for (size_t i=0; i < SETUI_CSL_PATHS; i++) {
const size_t wIdx = UI_CSL_BTN_ENABLE_1 + i*SETUI_CSL_ELEMS_PER_PATH;
txtCSLPaths[i].setId(widgetIds[wIdx+1]); // connect text object to widget
if (i < paths.size()) { // if there is a configured path for this line
XPSetWidgetProperty(widgetIds[wIdx ], // check box
xpProperty_ButtonState,
paths[i].enabled());
txtCSLPaths[i].SetDescriptor(paths[i].path); // text field
}
}
txtDefaultAcType.setId(widgetIds[UI_CSL_TXT_DEFAULT_AC_TYPE]);
txtDefaultAcType.tfFormat = TFTextFieldWidget::TFF_UPPER_CASE;
txtDefaultAcType.SetDescriptor(dataRefs.GetDefaultAcIcaoType());
txtGroundVehicleType.setId(widgetIds[UI_CSL_TXT_GROUND_VEHICLE_TYPE]);
txtGroundVehicleType.tfFormat = TFTextFieldWidget::TFF_UPPER_CASE;
txtGroundVehicleType.SetDescriptor(dataRefs.GetDefaultCarIcaoType());
// *** Debug ***
// filter for transponder hex code
txtDebugFilter.setId(widgetIds[UI_DEBUG_TXT_FILTER]);
txtDebugFilter.SearchFlightData(dataRefs.GetDebugAcFilter());
// debug options
btnDebugLogACPos.setId(widgetIds[UI_DEBUG_BTN_LOG_ACPOS],
DATA_REFS_LT[DR_DBG_AC_POS]);
btnDebugLogModelMatch.setId(widgetIds[UI_DEBUG_BTN_LOG_MODELMATCH],
DATA_REFS_LT[DR_DBG_MODEL_MATCHING]);
btnDebugLogRawFd.setId(widgetIds[UI_DEBUG_BTN_LOG_RAW_FD],
DATA_REFS_LT[DR_DBG_LOG_RAW_FD]);
// forced values for CSL model matching tests
txtFixAcType.setId(widgetIds[UI_DEBUG_TXT_FIX_AC_ICAO_TYPE]);
txtFixAcType.tfFormat = TFTextFieldWidget::TFF_UPPER_CASE;
txtFixAcType.SetDescriptor(dataRefs.cslFixAcIcaoType);
txtFixOp.setId(widgetIds[UI_DEBUG_TXT_FIX_OP_ICAO]);
txtFixOp.tfFormat = TFTextFieldWidget::TFF_UPPER_CASE;
txtFixOp.SetDescriptor(dataRefs.cslFixOpIcao);
txtFixLivery.setId(widgetIds[UI_DEBUG_TXT_FIX_LIVERY]);
txtFixLivery.tfFormat = TFTextFieldWidget::TFF_UPPER_CASE;
txtFixOp.SetDescriptor(dataRefs.cslFixLivery);
// center the UI
Center();
}
}
void LTSettingsUI::Disable()
{
if (isEnabled()) {
// remove widgets and free memory
XPDestroyWidget(*widgetIds, 1);
delete widgetIds;
widgetIds = nullptr;
}
}
// make sure I'm created before first use
void LTSettingsUI::Show (bool bShow)
{
if (bShow) // create before use
Enable();
TFWidget::Show(bShow); // show/hide
// make sure we are in the right window mode
if (GetWndMode() != GetDefaultWndOpenMode()) { // only possible in XP11
if (GetDefaultWndOpenMode() == TF_MODE_VR)
SetWindowPositioningMode(xplm_WindowVR, -1);
else
SetWindowPositioningMode(xplm_WindowPositionFree, -1);
}
}
// capture entry into 'filter for transponder hex code' field
// and into CSL paths
bool LTSettingsUI::MsgTextFieldChanged (XPWidgetID textWidget, std::string text)
{
// *** Basic ***
if (txtADSBAPIKey == textWidget) {
// did the key really change?
const std::string newKey(txtADSBAPIKey.GetDescriptor());
if (newKey.empty()) {
dataRefs.SetADSBExAPIKey(newKey);
btnADSBLive.Set(0); // disable channel
btnADSBLive.SetEnabled(false); // disable check box
}
else if (newKey != dataRefs.GetADSBExAPIKey())
{
// key changed, test it
ADSBExchangeConnection::TestADSBExAPIKey(newKey);
btnADSBLive.SetEnabled(true); // enable check box
}
}
// *** Advanced ***
if (txtDebugFilter == textWidget) {
// set the filter a/c if defined
if (txtDebugFilter.HasAcKey())
DataRefs::LTSetDebugAcFilter(NULL,txtDebugFilter.GetAcKeyNum());
else
DataRefs::LTSetDebugAcFilter(NULL,0);
return true;
}
// *** CSL ***
// if any of the paths changed we store that path
for (int i = 0; i < SETUI_CSL_PATHS; i++)
if (widgetIds[UI_CSL_TXT_PATH_1 + i*SETUI_CSL_ELEMS_PER_PATH] == textWidget) {
SaveCSLPath(i);
return true;
}
// if the types change we store them (and if setting fails after validation,
// then we restore the current value)
if (txtDefaultAcType == textWidget) {
if (!dataRefs.SetDefaultAcIcaoType(text))
txtDefaultAcType.SetDescriptor(dataRefs.GetDefaultAcIcaoType());
return true;
}
if (txtGroundVehicleType == textWidget) {
if (!dataRefs.SetDefaultCarIcaoType(text))
txtGroundVehicleType.SetDescriptor(dataRefs.GetDefaultCarIcaoType());
return true;
}
// *** Debug ***
// save forced model matching parameters
if (txtFixAcType == textWidget ||
txtFixOp == textWidget ||
txtFixLivery == textWidget)
{
dataRefs.cslFixAcIcaoType = txtFixAcType.GetDescriptor();
dataRefs.cslFixOpIcao = txtFixOp.GetDescriptor();
dataRefs.cslFixLivery = txtFixLivery.GetDescriptor();
if (dataRefs.cslFixAcIcaoType.empty() &&
dataRefs.cslFixOpIcao.empty() &&
dataRefs.cslFixLivery.empty())
SHOW_MSG(logWARN, MSG_MDL_NOT_FORCED)
else
SHOW_MSG(logWARN, MSG_MDL_FORCED,
dataRefs.cslFixAcIcaoType.c_str(),
dataRefs.cslFixOpIcao.c_str(),
dataRefs.cslFixLivery.c_str());
return true;
}
// not ours
return TFMainWindowWidget::MsgTextFieldChanged(textWidget, text);
}
// writes current values out into config file
bool LTSettingsUI::MsgHidden (XPWidgetID hiddenWidget)
{
if (hiddenWidget == *this) { // only if it was me who got hidden
// then only save the config file
dataRefs.SaveConfigFile();
}
// pass on in class hierarchy
return TFMainWindowWidget::MsgHidden(hiddenWidget);
}
// update state of some buttons from dataRef every second
bool LTSettingsUI::TfwMsgMain1sTime ()
{
TFMainWindowWidget::TfwMsgMain1sTime();
logLevelGrp.SetCheckedIndex(dataRefs.GetLogLevel());
msgAreaLevelGrp.SetCheckedIndex(dataRefs.GetMsgAreaLevel() - 1);
// real traffic stuff
UpdateRealTraffic();
// read current 'when-to-show' config and set accordingly
DataRefs::LabelShowCfgTy show = dataRefs.GetLabelShowCfg();
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_EXTERNAL],xpProperty_ButtonState,show.bExternal);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_INTERNAL],xpProperty_ButtonState,show.bInternal);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_VR],xpProperty_ButtonState,show.bVR);
return true;
}
// handles show/hide of 'tabs', values of logging level
bool LTSettingsUI::MsgButtonStateChanged (XPWidgetID buttonWidget, bool bNowChecked)
{
// first pass up the class hierarchy to make sure the button groups are handled correctly
bool bRet = TFMainWindowWidget::MsgButtonStateChanged(buttonWidget, bNowChecked);
// *** Tab Groups ***
// if the button is one of our tab buttons show/hide the appropriate subwindow
if (widgetIds[UI_BTN_BASICS] == buttonWidget) {
subBasicsLive.Show(bNowChecked);
subBasicsRight.Show(bNowChecked);
return true;
}
else if (widgetIds[UI_BTN_AC_LABELS] == buttonWidget) {
subAcLabel.Show(bNowChecked);
return true;
}
else if (widgetIds[UI_BTN_ADVANCED] == buttonWidget) {
subAdvcd.Show(bNowChecked);
return true;
}
else if (widgetIds[UI_BTN_CSL] == buttonWidget) {
subCSL.Show(bNowChecked);
return true;
}
else if (widgetIds[UI_BTN_DEBUG] == buttonWidget) {
subDebug.Show(bNowChecked);
return true;
}
// *** A/C Labels ***
// if any of the a/c label check boxes changes we set the config accordingly
if (widgetIds[UI_LABELS_BTN_TYPE] == buttonWidget ||
widgetIds[UI_LABELS_BTN_AC_ID] == buttonWidget ||
widgetIds[UI_LABELS_BTN_TRANSP] == buttonWidget ||
widgetIds[UI_LABELS_BTN_REG] == buttonWidget ||
widgetIds[UI_LABELS_BTN_OP] == buttonWidget ||
widgetIds[UI_LABELS_BTN_CALL_SIGN] == buttonWidget ||
widgetIds[UI_LABELS_BTN_FLIGHT_NO] == buttonWidget ||
widgetIds[UI_LABELS_BTN_ROUTE] == buttonWidget ||
widgetIds[UI_LABELS_BTN_PHASE] == buttonWidget ||
widgetIds[UI_LABELS_BTN_HEADING] == buttonWidget ||
widgetIds[UI_LABELS_BTN_ALT] == buttonWidget ||
widgetIds[UI_LABELS_BTN_HEIGHT] == buttonWidget ||
widgetIds[UI_LABELS_BTN_SPEED] == buttonWidget ||
widgetIds[UI_LABELS_BTN_VSI] == buttonWidget ||
// when-to-show selection
widgetIds[UI_LABELS_BTN_EXTERNAL] == buttonWidget ||
widgetIds[UI_LABELS_BTN_INTERNAL] == buttonWidget ||
widgetIds[UI_LABELS_BTN_VR] == buttonWidget)
{
LabelBtnSave();
return true;
}
// dynamic / fixed label colors?
if (widgetIds[UI_LABELS_BTN_DYNAMIC] == buttonWidget ||
widgetIds[UI_LABELS_BTN_FIXED] == buttonWidget)
{
drLabelColDyn.Set(buttonWidget == widgetIds[UI_LABELS_BTN_DYNAMIC]);
return true;
}
// *** Advanced ***
// if any of the log-level radio buttons changes we set log-level accordingly
if (bNowChecked && logLevelGrp.isInGroup(buttonWidget))
{
dataRefs.SetLogLevel(logLevelGrp.GetCheckedIndex());
return true;
}
if (bNowChecked && msgAreaLevelGrp.isInGroup(buttonWidget))
{
dataRefs.SetMsgAreaLevel(msgAreaLevelGrp.GetCheckedIndex() + 1);
return true;
}
// *** CSL ***
// if any of the enable-check boxes changed we store that setting
for (int i = 0; i < SETUI_CSL_PATHS; i++)
if (widgetIds[UI_CSL_BTN_ENABLE_1 + i*SETUI_CSL_ELEMS_PER_PATH] == buttonWidget) {
SaveCSLPath(i);
return true;
}
return bRet;
}
// push buttons
bool LTSettingsUI::MsgPushButtonPressed (XPWidgetID buttonWidget)
{
// *** Help ***
if (widgetIds[UI_BTN_HELP] == buttonWidget)
{
// open help for the currently selected tab of the settings dialog
const char* helpSettingsPaths[5] = HELP_SETTINGS_PATHS;
LTOpenHelp(helpSettingsPaths[tabGrp.GetCheckedIndex()]);
return true;
}
// *** A/C Labels ***
// color presets?
if (widgetIds[UI_LABELS_BTN_YELLOW] == buttonWidget) { intLabelColor.Set(COLOR_YELLOW); return true; }
if (widgetIds[UI_LABELS_BTN_RED] == buttonWidget) { intLabelColor.Set(COLOR_RED); return true; }
if (widgetIds[UI_LABELS_BTN_GREEN] == buttonWidget) { intLabelColor.Set(COLOR_GREEN); return true; }
if (widgetIds[UI_LABELS_BTN_BLUE] == buttonWidget) { intLabelColor.Set(COLOR_BLUE); return true; }
// *** CSL ***
// any of the "Load" buttons pushed?
for (int i=0; i < SETUI_CSL_PATHS; i++) {
if (widgetIds[UI_CSL_BTN_LOAD_1 + i*SETUI_CSL_ELEMS_PER_PATH] == buttonWidget) {
SaveCSLPath(i);
if (dataRefs.LoadCSLPackage(i))
// successfully loaded...not update all CSL models in use
LTFlightData::UpdateAllModels();
return true;
}
}
// we don't know that button...
return TFMainWindowWidget::MsgPushButtonPressed(buttonWidget);
}
// Handle checkboxes for a/c labels
void LTSettingsUI::LabelBtnInit()
{
// read current label configuration and init the checkboxes accordingly
DataRefs::LabelCfgTy cfg = dataRefs.GetLabelCfg();
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_TYPE],xpProperty_ButtonState,cfg.bIcaoType);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_AC_ID],xpProperty_ButtonState,cfg.bAnyAcId);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_TRANSP],xpProperty_ButtonState,cfg.bTranspCode);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_REG],xpProperty_ButtonState,cfg.bReg);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_OP],xpProperty_ButtonState,cfg.bIcaoOp);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_CALL_SIGN],xpProperty_ButtonState,cfg.bCallSign);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_FLIGHT_NO],xpProperty_ButtonState,cfg.bFlightNo);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_ROUTE],xpProperty_ButtonState,cfg.bRoute);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_PHASE],xpProperty_ButtonState,cfg.bPhase);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_HEADING],xpProperty_ButtonState,cfg.bHeading);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_ALT],xpProperty_ButtonState,cfg.bAlt);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_HEIGHT],xpProperty_ButtonState,cfg.bHeightAGL);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_SPEED],xpProperty_ButtonState,cfg.bSpeed);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_VSI],xpProperty_ButtonState,cfg.bVSI);
// read current 'when-to-show' config and init accordingly
DataRefs::LabelShowCfgTy show = dataRefs.GetLabelShowCfg();
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_EXTERNAL],xpProperty_ButtonState,show.bExternal);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_INTERNAL],xpProperty_ButtonState,show.bInternal);
XPSetWidgetProperty(widgetIds[UI_LABELS_BTN_VR],xpProperty_ButtonState,show.bVR);
}
void LTSettingsUI::LabelBtnSave()
{
// store the checkboxes states in a zero-inited configuration
DataRefs::LabelCfgTy cfg = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
cfg.bIcaoType = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_TYPE],xpProperty_ButtonState,NULL);
cfg.bAnyAcId = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_AC_ID],xpProperty_ButtonState,NULL);
cfg.bTranspCode = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_TRANSP],xpProperty_ButtonState,NULL);
cfg.bReg = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_REG],xpProperty_ButtonState,NULL);
cfg.bIcaoOp = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_OP],xpProperty_ButtonState,NULL);
cfg.bCallSign = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_CALL_SIGN],xpProperty_ButtonState,NULL);
cfg.bFlightNo = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_FLIGHT_NO],xpProperty_ButtonState,NULL);
cfg.bRoute = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_ROUTE],xpProperty_ButtonState,NULL);
cfg.bPhase = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_PHASE],xpProperty_ButtonState,NULL);
cfg.bHeading = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_HEADING],xpProperty_ButtonState,NULL);
cfg.bAlt = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_ALT],xpProperty_ButtonState,NULL);
cfg.bHeightAGL = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_HEIGHT],xpProperty_ButtonState,NULL);
cfg.bSpeed = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_SPEED],xpProperty_ButtonState,NULL);
cfg.bVSI = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_VSI],xpProperty_ButtonState,NULL);
// save as current config
drCfgLabels.Set(cfg.GetInt());
// store the when-to-show information in a similar way
DataRefs::LabelShowCfgTy show = { 0, 0, 0 };
show.bExternal = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_EXTERNAL],xpProperty_ButtonState,NULL);
show.bInternal = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_INTERNAL],xpProperty_ButtonState,NULL);
show.bVR = (unsigned)XPGetWidgetProperty(widgetIds[UI_LABELS_BTN_VR],xpProperty_ButtonState,NULL);
drCfgLabelShow.Set(show.GetInt());
}
void LTSettingsUI::UpdateRealTraffic()
{
if (dataRefs.pRTConn) {
capRealTrafficStatus.SetDescriptor(dataRefs.pRTConn->GetStatusWithTimeStr());
capRealTrafficMetar.SetDescriptor(dataRefs.pRTConn->IsConnected() ?
std::to_string(std::lround(dataRefs.pRTConn->GetHPA())) +
" hPa @ " + dataRefs.pRTConn->GetMetarIcao() : "");
} else {
capRealTrafficStatus.SetDescriptor("");
capRealTrafficMetar.SetDescriptor("");
}
}
void LTSettingsUI::SaveCSLPath(int idx)
{
// what to save
DataRefs::CSLPathCfgTy newPath {
static_cast<bool>(XPGetWidgetProperty(widgetIds[UI_CSL_BTN_ENABLE_1 + idx*SETUI_CSL_ELEMS_PER_PATH],
xpProperty_ButtonState,NULL)),
txtCSLPaths[idx].GetDescriptor()
};
// save
dataRefs.SaveCSLPath(idx, newPath);
}
| 57.410538 | 224 | 0.667693 | [
"object",
"model"
] |
d81974b9a2522c715193cb8c45a9507a6788aa98 | 372 | hpp | C++ | inc/TupleStat.hpp | LorisFriedel/learning-sign-language | f87767c43a11c01885628c1de10daa9d1a58e6ad | [
"MIT"
] | null | null | null | inc/TupleStat.hpp | LorisFriedel/learning-sign-language | f87767c43a11c01885628c1de10daa9d1a58e6ad | [
"MIT"
] | null | null | null | inc/TupleStat.hpp | LorisFriedel/learning-sign-language | f87767c43a11c01885628c1de10daa9d1a58e6ad | [
"MIT"
] | null | null | null | //
// @author Loris Friedel
//
#pragma once
#include <vector>
class TupleStat {
public:
TupleStat(const bool success, const int predictedLetter,
const float trustPercentage, const std::vector<float> &predictOutput);
const bool success;
const int predictedLabel;
const float trustPercentage;
const std::vector<float> predictOutput;
}; | 19.578947 | 84 | 0.701613 | [
"vector"
] |
d81a961a1e33fff83c2115294b6314e3f75da142 | 10,829 | cpp | C++ | src/sweepc/source/swp_sintering_model.cpp | sm453/MOpS | f1a706c6552bbdf3ceab504121a02391a1b51ede | [
"MIT"
] | 3 | 2020-09-08T14:06:33.000Z | 2020-12-04T07:52:19.000Z | src/sweepc/source/swp_sintering_model.cpp | sm453/MOpS | f1a706c6552bbdf3ceab504121a02391a1b51ede | [
"MIT"
] | null | null | null | src/sweepc/source/swp_sintering_model.cpp | sm453/MOpS | f1a706c6552bbdf3ceab504121a02391a1b51ede | [
"MIT"
] | 3 | 2021-11-15T05:18:26.000Z | 2022-03-01T13:51:20.000Z | /*
Author(s): Matthew Celnik (msc37)
Project: sweepc (population balance solver)
Sourceforge: http://sourceforge.net/projects/mopssuite
Copyright (C) 2008 Matthew S Celnik.
File purpose:
Implementation of the SinteringModel class declared in the
swp_sintering_model.h header file.
Licence:
This file is part of "sweepc".
sweepc is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2
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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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.
Contact:
Dr Markus Kraft
Dept of Chemical Engineering
University of Cambridge
New Museums Site
Pembroke Street
Cambridge
CB2 3RA
UK
Email: mk306@cam.ac.uk
Website: http://como.cheng.cam.ac.uk
*/
#include "swp_sintering_model.h"
#include "swp_primary.h"
#include "swp_particle.h"
#include "swp_cell.h"
#include <cmath>
#include <stdexcept>
using namespace Sweep;
using namespace Sweep::Processes;
using namespace std;
// CONSTRUCTORS AND DESTRUCTORS.
// Default constructor.
SinteringModel::SinteringModel()
: m_enable(false), m_A(0.0), m_E(0.0), m_dpmin(0.0), m_alpha(0.0), m_type(GBD)
{
}
// Copy constructor.
SinteringModel::SinteringModel(const Sweep::Processes::SinteringModel ©)
{
*this = copy;
}
// Stream-reading constructor.
SinteringModel::SinteringModel(std::istream &in)
{
Deserialize(in);
}
// Destructor.
SinteringModel::~SinteringModel()
{
// Nothing special to destruct.
}
// OPERATOR OVERLOADING.
// Assignment operator.
SinteringModel &SinteringModel::operator=(const Sweep::Processes::SinteringModel &rhs)
{
if (this != &rhs) {
m_enable = rhs.m_enable;
m_A = rhs.m_A;
m_E = rhs.m_E;
m_type = rhs.m_type;
}
return *this;
}
// MODEL ENABLE/DISABLE.
// Returns true is the model is enabled, otherwise false.
bool SinteringModel::IsEnabled(void) const {return m_enable;}
// Enables this sintering model.
void SinteringModel::Enable(void) {m_enable = true;}
// Disables this sintering model.
void SinteringModel::Disable(void) {m_enable = false;}
// PRE-EXPONENTIAL CONSTANT.
// Returns the pre-exponential constant.
double SinteringModel::A(void) const {return m_A;}
// Sets the pre-exponential constant.
void SinteringModel::SetA(double a) {m_A = a;}
// ENERGY PARAMETER.
// Returns the characteristic temperature (E) in Kelvin.
double SinteringModel::E(void) const {return m_E;}
// Sets the characteristic temperature (E) in Kelvin.
void SinteringModel::SetE(double e) {m_E = e;}
// MINIMUM PRIMARY PARTICLE DIAMETER PARAMETER.
// Returns the minimum primary particle diameter in the system (Dpmin) in m.
double SinteringModel::Dpmin(void) const {return m_dpmin;}
// Sets the minimum primary particle diameter in the system (Dpmin) in m.
void SinteringModel::SetDpmin(double dpmin) {m_dpmin = dpmin;}
// CRITICAL EXPONENT
// Returns the critical exponent.
double SinteringModel::alpha(void) const { return m_alpha; }
// Sets the critical exponent.
void SinteringModel::Setalpha(double alpha) { m_alpha = alpha; }
// SINTERING MODEL TYPE.
// Returns the sintering model type.
SinteringModel::SintType SinteringModel::Type(void) const {return m_type;}
// Sets the sintering model type.
void SinteringModel::SetType(SinteringModel::SintType t) {m_type = t;}
// CHARACTERISTIC SINTERING TIME.
// Returns the characteristic sintering time for the
// given particle.
double SinteringModel::SintTime(const Cell &sys, const Particle &p) const
{
if (p.Primary() != NULL) {
return SintTime(sys, *p.Primary());
} else {
return 0.0;
}
}
// Returns the characteristic sintering time for the
// given primary.
double SinteringModel::SintTime(const Cell &sys,const AggModels::Primary &p) const
{
double dp = 6.0 * p.Volume() / p.SurfaceArea();
switch (m_type) {
case ViscousFlow:
return m_A * dp *
exp((m_E*(1-(m_dpmin/dp)))/sys.GasPhase().Temperature());
break;
case GBD:
default:
return m_A * dp * dp * dp * dp * sys.GasPhase().Temperature() *
exp((m_E*(1-pow(m_dpmin/dp,m_alpha)))/sys.GasPhase().Temperature());
break;
case SSD:
return m_A * dp * dp * dp * sys.GasPhase().Temperature() *
exp((m_E*(1-(m_dpmin/dp)))/sys.GasPhase().Temperature());
break;
case Silicon:
// Zachariah & Carrier, J. Aerosol Sci., 1999, 30, 1139-1151
// implementation of the SSD silicon sintering kinetic
// form: tau = A * d^3 * T / (gamma * diff)
// gamma = surface energy = 1.152 - 1.574e-4*T(K) N/m
// diff. = SSD diffusivity = 4.69e-7 exp(-m_E / T) m2/s
// default: m_A = 5396 J/K.m3
// m_E = 7562 K
// m_dpmin = 0 nm
return m_A * dp * dp * dp * sys.GasPhase().Temperature() / (
(1.152 - 1.574e-4 * sys.GasPhase().Temperature()) *
4.69e-7 * exp((m_E*(1-(m_dpmin/dp)))/sys.GasPhase().Temperature())
);
break;
case SilicaKirchoff:
// Kirchoff et al., J. Aerosol Sci., 2012, 45, 26-39
// http://dx.doi.org/10.1016/j.jaerosci.2011.10.006
// form: tau = A * r_sph^2 * exp (Ea/RT)
// where: A = (1-exp(-1)) / (2^(2/3) * k_S)
// r_sph = equiv. spherical radius
// k_S = 3.5e-4 m2/s
// Ea = 3.8 eV
// defaults:
// A = 284.44 s/m2
// Ea = 44080 K
// Recalculate d_sph
dp = pow(6.0 * p.Volume() / Sweep::PI, Sweep::ONE_THIRD);
return m_A * dp * dp * exp(m_E / sys.GasPhase().Temperature());
break;
case Rutile:
// Buesser et al., J. Phys. Chem. C, 2011, 115, 11030-11035
// SintTime function from MD calculations
// default: m_A = 3.7E16 s/m4K,
// m_E = 258 kJ/mol = 31032 K
// m_dpmin = 3.4 nm
return m_A * dp * dp * dp * dp * sys.GasPhase().Temperature() *
exp((m_E* (1 - pow( (m_dpmin/dp) - (sys.GasPhase().Temperature()/4100.0) , 3.76))
/sys.GasPhase().Temperature()));
break;
case Constant:
// Only dependent on the 'pre-exponential' (has units s in this case)
return m_A;
}
}
// RATE CALCULATION.
// Returns the rate of the process for the given particle.
// wjm34: include max() catch on tau to prevent getting stuck in infinite Sinter() loops
double SinteringModel::Rate(double t, const Cell &sys, const Particle &p) const
{
double tau = max(1.0e-30, SintTime(sys, p));
return (p.SurfaceArea() - p.SphSurfaceArea()) / tau;
}
// Returns the rate of the process for the given primary.
double SinteringModel::Rate(double t, const Cell &sys, const AggModels::Primary &p) const
{
double tau = max(1.0e-30, SintTime(sys, p));
return max((p.SurfaceArea() - p.SphSurfaceArea()) / tau, 0.0);
}
// READ/WRITE/COPY.
// Creates a copy of the sintering model.
SinteringModel *const SinteringModel::Clone(void) const
{
return new SinteringModel(*this);
}
// Writes the object to a binary stream.
void SinteringModel::Serialize(std::ostream &out) const
{
const unsigned int trueval = 1;
const unsigned int falseval = 0;
if (out.good()) {
// Output the version ID (=0 at the moment).
const unsigned int version = 0;
out.write((char*)&version, sizeof(version));
// Write if enabled or disabled model.
if (m_enable) {
out.write((char*)&trueval, sizeof(trueval));
} else {
out.write((char*)&falseval, sizeof(falseval));
}
// Write pre-exponential factor.
double val = (double)m_A;
out.write((char*)&val, sizeof(val));
// Write characteristic temperature.
val = (double)m_E;
out.write((char*)&val, sizeof(val));
// Write minimum primary particle diameter.
val = (double)m_dpmin;
out.write((char*)&val, sizeof(val));
// Write critical exponent.
val = (double)m_alpha;
out.write((char*)&val, sizeof(val));
// Write type.
unsigned int t = (unsigned int)m_type;
out.write((char*)&t, sizeof(t));
} else {
throw invalid_argument("Output stream not ready "
"(Sweep, SinteringModel::Serialize).");
}
}
// Reads the object from a binary stream.
void SinteringModel::Deserialize(std::istream &in)
{
if (in.good()) {
// Read the output version. Currently there is only one
// output version, so we don't do anything with this variable.
// Still needs to be read though.
unsigned int version = 0;
in.read(reinterpret_cast<char*>(&version), sizeof(version));
unsigned int n=0;
double val=0.0;
switch (version) {
case 0:
// Read if enabled
in.read(reinterpret_cast<char*>(&n), sizeof(n));
m_enable = (n==1);
// Read pre-exponential factor.
in.read(reinterpret_cast<char*>(&val), sizeof(val));
m_A = (double)val;
// Read characteristic temperature.
in.read(reinterpret_cast<char*>(&val), sizeof(val));
m_E = (double)val;
// Read minimum primary particle diameter.
in.read(reinterpret_cast<char*>(&val), sizeof(val));
m_dpmin = (double)val;
// Read critical exponent.
in.read(reinterpret_cast<char*>(&val), sizeof(val));
m_alpha = (double)val;
// Read type.
in.read(reinterpret_cast<char*>(&n), sizeof(n));
m_type = (SintType)n;
break;
default:
throw runtime_error("Serialized version number is invalid "
"(Sweep, SinteringModel::Deserialize).");
}
} else {
throw invalid_argument("Input stream not ready "
"(Sweep, SinteringModel::Deserialize).");
}
}
| 31.388406 | 89 | 0.606889 | [
"object",
"model"
] |
d81c5542a38b1029ef8167d72e1dbf1ce4cd3fd7 | 11,769 | cpp | C++ | core/src/utils/JsonParserPath.cpp | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 92 | 2016-11-13T01:28:34.000Z | 2022-03-25T01:11:37.000Z | core/src/utils/JsonParserPath.cpp | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 242 | 2016-11-28T11:13:09.000Z | 2022-03-04T13:02:53.000Z | core/src/utils/JsonParserPath.cpp | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 91 | 2017-06-20T10:35:28.000Z | 2022-03-09T14:15:40.000Z | /*
*
* JsonParserPath.cpp
* ledger-core
*
* Created by Pierre Pollastri on 26/06/2019.
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "JsonParserPath.hpp"
#include <utils/Exception.hpp>
#include <sstream>
#include <string>
#include <boost/lexical_cast.hpp>
namespace ledger {
namespace core {
JsonParserPath::JsonParserPath() {
}
void JsonParserPath::startArray() {
value();
_path.emplace_back(JsonParserPathNode(JsonParserPathNodeType::ARRAY));
}
void JsonParserPath::startObject() {
value();
_path.emplace_back(JsonParserPathNode(JsonParserPathNodeType::OBJECT));
}
void JsonParserPath::endArray() {
if (getParent().type != JsonParserPathNodeType::ARRAY && getCurrent().type != JsonParserPathNodeType::ARRAY)
throw std::runtime_error("Can't end a non existing array");
if (getCurrent().type == JsonParserPathNodeType::VALUE)
_path.pop_back();
_path.pop_back();
}
void JsonParserPath::endObject() {
if (getParent().type != JsonParserPathNodeType::OBJECT && getCurrent().type != JsonParserPathNodeType::OBJECT)
throw std::runtime_error("Can't end a non existing array");
if (getCurrent().type == JsonParserPathNodeType::VALUE)
_path.pop_back();
_path.pop_back();
}
void JsonParserPath::key(const std::string &key) {
_lastKey = key;
}
std::string JsonParserPath::toString(int depth) const {
std::stringstream ss;
const JsonParserPathNode *parent = nullptr;
auto iterations = 0;
for (const auto& node : _path) {
iterations += 1;
if (iterations - 1 < depth)
continue;
switch (node.type) {
case JsonParserPathNodeType::OBJECT:
ss << "/";
break;
case JsonParserPathNodeType::ARRAY:
ss << "[";
break;
case JsonParserPathNodeType::VALUE:
if (parent != nullptr && parent->type == JsonParserPathNodeType::OBJECT) {
ss << node.key();
} else if (parent != nullptr && parent->type == JsonParserPathNodeType::ARRAY) {
ss << node.index() << "]";
}
break;
}
parent = &node;
}
return ss.str();
}
std::string JsonParserPath::toString() const {
return toString(0);
}
bool JsonParserPath::match(const JsonParserPathMatcher& matcher, int depth) const {
if ((_path.size() - depth) < matcher.getElements().size())
return false;
auto node = _path.begin();
std::advance(node, depth);
const JsonParserPathNode *parent = nullptr;
auto element = matcher.getElements().begin();
auto elementEnd = matcher.getElements().end();
while (node != _path.end() && element != elementEnd) {
if (element->filter == JsonParserPathMatcherFilter::MATCH_ALL) {
return true;
}
if (node->type != element->node.type) {
return false;
}
if (node->type == JsonParserPathNodeType::VALUE &&
element->filter == JsonParserPathMatcherFilter::EXACT) {
if (!parent) {
return false;
}
if (parent->type == JsonParserPathNodeType::ARRAY &&
node->index() != element->node.index()) {
return false;
} else if (parent->type == JsonParserPathNodeType::OBJECT &&
node->key() != element->node.key()) {
return false;
}
}
parent = &(*node);
node++;
element++;
}
return node == _path.end() && element == elementEnd;
}
void JsonParserPath::value() {
if (_path.empty()) return ;
switch (_path.back().type) {
case JsonParserPathNodeType::OBJECT:
_path.emplace_back(JsonParserPathNode(JsonParserPathNodeType::VALUE, _lastKey));
break;
case JsonParserPathNodeType::ARRAY:
_path.emplace_back(JsonParserPathNode(JsonParserPathNodeType::VALUE, 0));
break;
case JsonParserPathNodeType::VALUE:
if (getParent().type == JsonParserPathNodeType::ARRAY) {
_path.back().content = _path.back().index() + 1;
} else {
_path.back().content = _lastKey;
}
break;
}
}
const JsonParserPathNode &JsonParserPath::getCurrent() const {
return _path.back();
}
const JsonParserPathNode &JsonParserPath::getParent() const {
return *(++_path.rbegin());
}
JsonParserPathNode &JsonParserPath::getCurrent() {
return _path.back();
}
JsonParserPathNode &JsonParserPath::getParent() {
return *(++_path.rbegin());
}
JsonParserPathMatcher::JsonParserPathMatcher(const std::string &filter) {
char buffer[64]; // Assume max key size is sizeof(buffer)
auto offset = 0;
auto emplace_value = [&] () {
if (offset == 0 || _elements.empty()) return ;
std::string s(buffer, offset);
if ((_elements.back().node.type == JsonParserPathNodeType::ARRAY && s == "*") ||
(_elements.back().node.type == JsonParserPathNodeType::OBJECT && s == "*")) {
_elements.emplace_back(JsonParserPathMatcherElement(
JsonParserPathMatcherFilter::WILDCARD,
JsonParserPathNode(JsonParserPathNodeType::VALUE)
));
} else if (_elements.back().node.type == JsonParserPathNodeType::ARRAY) {
auto i = boost::lexical_cast<int>(s);
_elements.emplace_back(JsonParserPathMatcherElement(
JsonParserPathMatcherFilter::EXACT,
JsonParserPathNode(JsonParserPathNodeType::VALUE, i)
));
} else if (s != "?") {
_elements.emplace_back(JsonParserPathMatcherElement(
JsonParserPathMatcherFilter::EXACT,
JsonParserPathNode(JsonParserPathNodeType::VALUE, s)
));
}
offset = 0;
};
for (auto& c : filter) {
if (_elements.size() > 0 && _elements.back().filter == JsonParserPathMatcherFilter::MATCH_ALL)
throw make_exception(api::ErrorCode::RUNTIME_ERROR, "? digit can only be put at the end of the filter string");
if (c == '?') {
_elements.emplace_back(JsonParserPathMatcherElement(
JsonParserPathMatcherFilter::MATCH_ALL,
JsonParserPathNode(JsonParserPathNodeType::VALUE)
));
} else if (c == '/') {
emplace_value();
_elements.emplace_back(JsonParserPathMatcherElement(
JsonParserPathMatcherFilter::EXACT,
JsonParserPathNode(JsonParserPathNodeType::OBJECT)
));
} else if (c == '[') {
emplace_value();
_elements.emplace_back(JsonParserPathMatcherElement(
JsonParserPathMatcherFilter::EXACT,
JsonParserPathNode(JsonParserPathNodeType::ARRAY)
));
} else if (c != ']') {
if (offset < sizeof(buffer))
buffer[offset++] = c;
}
}
emplace_value();
}
const std::list<JsonParserPathMatcherElement>& JsonParserPathMatcher::getElements() const {
return _elements;
}
std::string JsonParserPathMatcher::toString() const {
std::stringstream ss;
const JsonParserPathNode* parent = nullptr;
for (auto& elem : _elements) {
switch (elem.node.type) {
case JsonParserPathNodeType::OBJECT:
ss << "/";
break;
case JsonParserPathNodeType::ARRAY:
ss << "[";
break;
case JsonParserPathNodeType::VALUE:
if (elem.filter == JsonParserPathMatcherFilter::MATCH_ALL) {
ss << "?";
} else if (parent != nullptr && parent->type == JsonParserPathNodeType::OBJECT) {
ss << (elem.filter == JsonParserPathMatcherFilter::WILDCARD ? "*" : elem.node.key());
} else if (elem.filter != JsonParserPathMatcherFilter::WILDCARD) {
ss << elem.node.index();
}
break;
}
parent = &elem.node;
}
return ss.str();
}
bool JsonParserPathView::match(const JsonParserPathMatcher &matcher) const {
return _owner->match(matcher, _depth);
}
JsonParserPathView JsonParserPathView::view(int depth) {
return JsonParserPathView(_owner, depth + _depth);
}
std::string JsonParserPathView::toString() const {
return _owner->toString(_depth);
}
JsonParserPathView JsonParserPath::view() {
if (_path.empty()) {
throw make_exception(api::ErrorCode::RUNTIME_ERROR, "Attempt to create a view at an invalid range");
}
return {this, (int)_path.size() - 1};
}
JsonParserPathView JsonParserPath::view(int depth) {
return {this, depth};
}
}
} | 41.006969 | 131 | 0.517206 | [
"object"
] |
d82ffebb6dbfc6690b66abfff900b0836e216a19 | 8,747 | cpp | C++ | LegOOPolis/Main.cpp | DanielMagro97/LegOOPolis | 7d0441365a46ca3c6fef772d0e43740001682f30 | [
"MIT"
] | null | null | null | LegOOPolis/Main.cpp | DanielMagro97/LegOOPolis | 7d0441365a46ca3c6fef772d0e43740001682f30 | [
"MIT"
] | null | null | null | LegOOPolis/Main.cpp | DanielMagro97/LegOOPolis | 7d0441365a46ca3c6fef772d0e43740001682f30 | [
"MIT"
] | null | null | null | #include <iostream>
#include "CSVReader.h"
#include "Quarry.h"
#include "City.h"
#include "Contractors/Bob.h"
#include "Contractors/Peter.h"
#include "Contractors/Jane.h"
using namespace std;
// function which frees memory on exit
void garbageCollection(Quarry quarry, City city);
// Launcher
int main(int argc, char **argv) {
// if the input file argument is not specified, exit the program.
if (argc < 2){
cout << "Usage: lego <input filename>" << endl;
return 0;
}
// Declaring the object quarry as an instance of the Class Quarry;
Quarry quarry;
// Declaring the object city as an instance of the City class
City city;
// integer which stores how many buildings were requested to be built by the input file
int numberOfRequestedBuildings = 0;
try {
CSVReader reader(argv[1]);
vector<string> vec;
while (reader.readLine(vec)) {
if (vec.size() == 2){
// converting the user inputted number to an integer
int amount;
try {
amount = stoi(vec[1]);
} catch (std::invalid_argument&) {
std::cout << "Invalid Input! Exiting" << std::endl;
garbageCollection(quarry, city);
exit(1);
}
// determining what the current line of the input file states
if (vec[0] == "bricks") {
cout << "Adding Bricks to Quarry" << endl;
if (amount < 1){
cout << "Quantity of bricks should be between "
"1 and 100, setting number of bricks to 1" << endl;
amount = 1;
} else if (amount > 100){
cout << "Quantity of bricks should be between "
"1 and 100, setting number of bricks to 100" << endl;
amount = 100;
}
quarry.fillQuarry(PieceType::brick, amount);
} else if (vec[0] == "doors"){
cout << "Adding Doors to Quarry" << endl;
if (amount < 1){
cout << "Quantity of doors should be between "
"1 and 100, setting number of doors to 1" << endl;
amount = 1;
} else if (amount > 100){
cout << "Quantity of doors should be between "
"1 and 100, setting number of doors to 100" << endl;
amount = 100;
}
quarry.fillQuarry(PieceType::door, amount);
} else if (vec[0] == "windows"){
cout << "Adding Windows to Quarry" << endl;
if (amount < 1){
cout << "Quantity of windows should be between "
"1 and 100, setting number of doors to 1" << endl;
amount = 1;
} else if (amount > 100){
cout << "Quantity of windows should be between "
"1 and 100, setting number of doors to 100" << endl;
amount = 100;
}
quarry.fillQuarry(PieceType::window, amount);
} else if (vec[0] == "1storeyhouse"){
cout << "Building One Storey House(s)" << endl;
if (amount > 0) {
numberOfRequestedBuildings += amount;
Bob contractor;
try {
for (int i = 0; i < amount; ++i) {
city.city->insertAtEnd(contractor.buildOneStoreyHouse(&quarry));
}
} catch (exception& notEnoughPiecesException) {
std::cout << notEnoughPiecesException.what() << std::endl;
}
}
} else if (vec[0] == "2storeyhouse"){
cout << "Building Two Storey House(s)" << endl;
if (amount > 0) {
numberOfRequestedBuildings += amount;
Bob contractor;
try {
for (int i = 0; i < amount; ++i) {
city.city->insertAtEnd(contractor.buildTwoStoreyHouse(&quarry));
}
} catch (exception& notEnoughPiecesException) {
std::cout << notEnoughPiecesException.what() << std::endl;
}
}
} else if (vec[0] == "church"){
cout << "Building Church(es)" << endl;
if (amount > 0) {
numberOfRequestedBuildings += amount;
Peter contractor;
try {
for (int i = 0; i < amount; ++i) {
city.city->insertAtEnd(contractor.buildChurch(&quarry));
}
} catch (exception& notEnoughPiecesException) {
std::cout << notEnoughPiecesException.what() << std::endl;
}
}
} else if (vec[0] == "hospital"){
cout << "Building Hospital(s)" << endl;
if (amount > 0) {
numberOfRequestedBuildings += amount;
Jane contractor;
try {
for (int i = 0; i < amount; ++i) {
city.city->insertAtEnd(contractor.buildHospital(&quarry));
}
} catch (exception& notEnoughPiecesException) {
std::cout << notEnoughPiecesException.what() << std::endl;
}
}
} else if (vec[0] == "university"){
cout << "Building University(ies)" << endl;
if (amount > 0) {
numberOfRequestedBuildings += amount;
Jane contractor;
try {
for (int i = 0; i < amount; ++i) {
city.city->insertAtEnd(contractor.buildUniversity(&quarry));
}
} catch (exception& notEnoughPiecesException) {
std::cout << notEnoughPiecesException.what() << std::endl;
}
}
// In case of invalid input: perform garbage collection and exit the program
} else {
cout << "Please check the format of the input file! Exiting" << endl;
garbageCollection(quarry, city);
exit(1);
}
}
}
}
catch (ifstream::failure &e) {
cout << "Exception! " << e.what() << endl;
}
catch (...) {
cout << "Exception!" << endl;
}
// Displaying city description
cout << endl;
cout << "Number of Requested Buildings: " << numberOfRequestedBuildings << endl;
cout << "Number of Completed Buildings: " << city.city->getSize() << endl;
double percentageCompleted = ((double) (city.city->getSize()) / (double) (numberOfRequestedBuildings))*100;
cout << "Percentage Completed: " << percentageCompleted << "%" << endl;
//<< (double) ((city.city->getSize()/numberOfRequestedBuildings)*100) << "%" << endl;
cout << endl;
cout << "List of Buildings completed:" << endl;
cout << "\tHouses: " << (city.numberOfBuildingsInCity(BuildingType::onestoreyhouse)
+ city.numberOfBuildingsInCity(BuildingType::twostoreyhouse)) << endl;
cout << "\tChurches: " << city.numberOfBuildingsInCity(BuildingType::church) << endl;
cout << "\tHospitals: " << city.numberOfBuildingsInCity(BuildingType::hospital) << endl;
cout << "\tUniversities: " << city.numberOfBuildingsInCity(BuildingType::university) << endl;
// Calling the method which frees any allocated memory
garbageCollection(quarry, city);
return 0;
}
void garbageCollection(Quarry quarry, City city){
for (int i = 0; i < city.city->getSize(); i++) {
delete(city.city->getNodeAtIndex(i).data);
}
quarry.quarry->deleteLinkedList();
city.city->deleteLinkedList();
delete (quarry.quarry);
delete(city.city);
}
| 43.735 | 111 | 0.460158 | [
"object",
"vector"
] |
d8316ab2401256535aaaeef8c024deb5e1586ed4 | 2,715 | hpp | C++ | p3iv_utils_probability/include/p3iv_utils_probability/internal/approximations.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 4 | 2021-07-27T06:56:22.000Z | 2022-03-22T11:21:30.000Z | p3iv_utils_probability/include/p3iv_utils_probability/internal/approximations.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | null | null | null | p3iv_utils_probability/include/p3iv_utils_probability/internal/approximations.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 1 | 2021-10-10T01:56:44.000Z | 2021-10-10T01:56:44.000Z | /*
* This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),
* copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)
*/
#pragma once
#include <cassert>
#include <cmath>
#include <vector>
namespace util_probability {
template <class T>
static inline T abs(const T& a) {
return a < T(0.0) ? -a : a;
}
inline double abs(double x) {
return std::abs(x);
}
/// Erf implementation according to Abramowitz & Stegun
/// A polynomial approximation with a maximal error of 1.2e-7. This approximation is based on Chebyshev fitting.
/// Numerical Recipes in Fortran 77: The Art of Scientific Computing
/// (ISBN 0-521-43064-X), 1992, page 214, Cambridge University Press.
/// Implementation is based on:
/// source: http://rextester.com/discussion/FVYOC97045/std-erf-versus-erf-impl-Abramowitz-Stegun-
/// which is almost the same in the source book Fortran77 recipes.
/// See also: https://en.wikipedia.org/wiki/Error_function#Polynomial
template <typename T>
inline T erf_impl(T v) {
const T t = T(1) / (T(1) + T(0.5) * abs(v));
static const T c[] = {T(1.26551223),
T(1.00002368),
T(0.37409196),
T(0.09678418),
T(-0.18628806),
T(0.27886807),
T(-1.13520398),
T(1.48851587),
T(-0.82215223),
T(0.17087277)};
T result =
T(1) -
t * std::exp(
(-v * v) - c[0] +
t * (c[1] +
t * (c[2] +
t * (c[3] + t * (c[4] + t * (c[5] + t * (c[6] + t * (c[7] + t * (c[8] + t * (c[9]))))))))));
return (v >= T(0)) ? result : -result;
}
template <typename T>
inline T norm_cdf(const T& v, const T& mean, const T& std) {
return 0.5 * (1.0 + erf_impl((v - mean) * (M_SQRT1_2 / std)));
}
template <typename T>
inline T trnorm_cdf(T v, const double& mean, const double& std, const double& a, const double& b) {
/* a = lower truncation bound
b = upper truncation bound
*/
assert(a < b);
T zeta = T((v - mean) / std);
T alpha = T((a - mean) / std);
T beta = T((b - mean) / std);
T cdf_alpha = T(0); /* if -inf */
T cdf_beta = T(1); /* if +inf, by definition of the cdf */
if (!std::isinf(a))
cdf_alpha = norm_cdf(alpha, 0.0, 1.0);
if (!std::isinf(b))
cdf_beta = norm_cdf(beta, 0.0, 1.0);
return (norm_cdf(zeta, 0.0, 1.0) - cdf_alpha) / (cdf_beta - cdf_alpha);
}
} // namespace util_probability | 30.505618 | 119 | 0.548435 | [
"vector"
] |
d841445732349e602d3503242245635e28469617 | 6,805 | cc | C++ | math/unit_vector3d_test.cc | aprvs/robotics-common | 0ce23c2e4c09d466d918f10cd8ac0f23571d13df | [
"MIT"
] | 1 | 2021-05-30T22:37:44.000Z | 2021-05-30T22:37:44.000Z | math/unit_vector3d_test.cc | aprvs/robotics-common | 0ce23c2e4c09d466d918f10cd8ac0f23571d13df | [
"MIT"
] | null | null | null | math/unit_vector3d_test.cc | aprvs/robotics-common | 0ce23c2e4c09d466d918f10cd8ac0f23571d13df | [
"MIT"
] | null | null | null | #include "robotics-common/math/unit_vector3d.h"
#include "gtest/gtest.h"
namespace robotics_common {
namespace math {
TEST(UnitVector3dTest, ConstructDestructTest) { UnitVector3d unit_vector; }
TEST(UnitVector3dTest, NormalizeConstructTest) {
common::ErrorOr<UnitVector3d> result =
UnitVector3d::Construct(0.0, 0.5, 0.0, Epsilon::kTenMillionth);
EXPECT_FALSE(result.HasValue());
result = UnitVector3d::Construct(0.0, 0.0, 0.0, Epsilon::kTenMillionth);
EXPECT_FALSE(result.HasValue());
result =
UnitVector3d::Construct(1.0 + 0.9e-7, 0.0, 0.0, Epsilon::kTenMillionth);
ASSERT_TRUE(result.HasValue());
UnitVector3d unit_vector = result.ValueOrDie();
EXPECT_DOUBLE_EQ(unit_vector.Length(), 1.0);
EXPECT_DOUBLE_EQ(unit_vector.x(), 1.0);
EXPECT_DOUBLE_EQ(unit_vector.y(), 0.0);
EXPECT_DOUBLE_EQ(unit_vector.z(), 0.0);
}
TEST(UnitVector3dTest, CrossProductTest) {
UnitVector3d unit_vector = UnitVector3d::kXAxis.Cross(UnitVector3d::kYAxis);
EXPECT_DOUBLE_EQ(unit_vector.x(), 0.0);
EXPECT_DOUBLE_EQ(unit_vector.y(), 0.0);
EXPECT_DOUBLE_EQ(unit_vector.z(), 1.0);
unit_vector = UnitVector3d::kYAxis.Cross(UnitVector3d::kZAxis);
EXPECT_DOUBLE_EQ(unit_vector.x(), 1.0);
EXPECT_DOUBLE_EQ(unit_vector.y(), 0.0);
EXPECT_DOUBLE_EQ(unit_vector.z(), 0.0);
unit_vector = UnitVector3d::kZAxis.Cross(UnitVector3d::kXAxis);
EXPECT_DOUBLE_EQ(unit_vector.x(), 0.0);
EXPECT_DOUBLE_EQ(unit_vector.y(), 1.0);
EXPECT_DOUBLE_EQ(unit_vector.z(), 0.0);
}
TEST(UnitVector3dTest, NegationTest) {
UnitVector3d unit_vector = -UnitVector3d::kXAxis;
EXPECT_DOUBLE_EQ(unit_vector.x(), -1.0);
EXPECT_DOUBLE_EQ(unit_vector.y(), 0.0);
EXPECT_DOUBLE_EQ(unit_vector.z(), 0.0);
unit_vector.Negate();
EXPECT_TRUE(unit_vector.GeometricallyEquals(UnitVector3d::kXAxis,
Epsilon::kOneBillionth));
}
TEST(UnitVector3dTest, DotProductTest) {
EXPECT_DOUBLE_EQ(UnitVector3d::kXAxis.Dot(UnitVector3d::kXAxis), 1.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kYAxis.Dot(UnitVector3d::kYAxis), 1.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kZAxis.Dot(UnitVector3d::kZAxis), 1.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kXAxis.Dot(UnitVector3d::kYAxis), 0.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kXAxis.Dot(UnitVector3d::kZAxis), 0.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kYAxis.Dot(UnitVector3d::kXAxis), 0.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kYAxis.Dot(UnitVector3d::kZAxis), 0.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kZAxis.Dot(UnitVector3d::kXAxis), 0.0);
EXPECT_DOUBLE_EQ(UnitVector3d::kZAxis.Dot(UnitVector3d::kYAxis), 0.0);
}
TEST(UnitVector3dTest, EqualsCheckTest) {
EXPECT_TRUE(UnitVector3d::kXAxis.GeometricallyEquals(UnitVector3d::kXAxis,
Epsilon::kOneBillionth));
EXPECT_TRUE(UnitVector3d::kYAxis.GeometricallyEquals(UnitVector3d::kYAxis,
Epsilon::kOneBillionth));
EXPECT_TRUE(UnitVector3d::kZAxis.GeometricallyEquals(UnitVector3d::kZAxis,
Epsilon::kOneBillionth));
EXPECT_FALSE(UnitVector3d::kXAxis.GeometricallyEquals(
UnitVector3d::kYAxis, Epsilon::kOneBillionth));
EXPECT_FALSE(UnitVector3d::kYAxis.GeometricallyEquals(
UnitVector3d::kZAxis, Epsilon::kOneBillionth));
EXPECT_FALSE(UnitVector3d::kZAxis.GeometricallyEquals(
UnitVector3d::kXAxis, Epsilon::kOneBillionth));
}
TEST(UnitVector3dTest, ComputeAngleBetweenVectors) {
UnitVector3d v =
UnitVector3d::Construct(1, 0, 0, Epsilon::kOneBillionth).ValueOrDie();
UnitVector3d w = UnitVector3d::Construct(std::sqrt(0.5), std::sqrt(0.5), 0,
Epsilon::kOneBillionth)
.ValueOrDie();
EXPECT_DOUBLE_EQ(v.Angle(w), M_PI * 0.25);
}
TEST(UnitVector3dTest, TripleProduct) {
double triple_product = TripleProduct(
UnitVector3d::kXAxis, UnitVector3d::kYAxis, UnitVector3d::kZAxis);
EXPECT_DOUBLE_EQ(triple_product, 1.0);
triple_product = TripleProduct(UnitVector3d::kXAxis, UnitVector3d::kXAxis,
UnitVector3d::kXAxis);
EXPECT_DOUBLE_EQ(triple_product, 0.0);
}
TEST(UnitVector3dTest, RotateTest) {
UnitQuaternion q =
UnitQuaternion::Construct(0.0, 1.0, 0.0, 0.0, Epsilon::kOneBillionth)
.ValueOrDie();
UnitVector3d result = UnitVector3d::kXAxis.Rotate(q);
EXPECT_TRUE(
result.GeometricallyEquals(UnitVector3d::kXAxis, Epsilon::kOneBillionth));
q = UnitQuaternion::Construct(0.0, 0.0, 1.0, 0.0, Epsilon::kOneBillionth)
.ValueOrDie();
result = UnitVector3d::kXAxis.Rotate(q);
EXPECT_TRUE(result.GeometricallyEquals(-UnitVector3d::kXAxis,
Epsilon::kOneBillionth));
q = UnitQuaternion::Construct(std::cos(M_PI / 4), 0.0, 0.0,
std::sin(M_PI / 4), Epsilon::kOneBillionth)
.ValueOrDie();
result = UnitVector3d::kXAxis.Rotate(q);
EXPECT_TRUE(
result.GeometricallyEquals(UnitVector3d::kYAxis, Epsilon::kOneBillionth));
q = UnitQuaternion::Construct(std::cos(M_PI / 12), 0.0, 0.0,
std::sin(M_PI / 12), Epsilon::kOneBillionth)
.ValueOrDie();
result = UnitVector3d::kXAxis.Rotate(q);
EXPECT_DOUBLE_EQ(result.x(), std::cos(M_PI / 6));
EXPECT_DOUBLE_EQ(result.y(), std::sin(M_PI / 6));
EXPECT_DOUBLE_EQ(result.z(), 0.0);
q = UnitQuaternion::Construct(0.5, 0.5, 0.5, 0.5, Epsilon::kOneBillionth)
.ValueOrDie();
result = UnitVector3d::kXAxis.Rotate(q);
EXPECT_TRUE(
result.GeometricallyEquals(UnitVector3d::kYAxis, Epsilon::kOneBillionth));
}
TEST(UnitVector3dTest, ScaleTest) {
Vector3d scaled = UnitVector3d::kXAxis * 10.0;
EXPECT_DOUBLE_EQ(scaled.x(), 10.0);
EXPECT_DOUBLE_EQ(scaled.y(), 0.0);
EXPECT_DOUBLE_EQ(scaled.z(), 0.0);
scaled = 5.0 * UnitVector3d::kXAxis;
EXPECT_DOUBLE_EQ(scaled.x(), 5.0);
EXPECT_DOUBLE_EQ(scaled.y(), 0.0);
EXPECT_DOUBLE_EQ(scaled.z(), 0.0);
}
TEST(UnitVector3dTest, NormalizeTest) {
common::ErrorOr<UnitVector3d> result =
vector::Normalize(Vector3d(1.99, 0.0, 0.0), Epsilon::kOne);
ASSERT_TRUE(result.HasValue());
UnitVector3d unit = result.ValueOrDie();
EXPECT_DOUBLE_EQ(unit.x(), 1.0);
EXPECT_DOUBLE_EQ(unit.y(), 0.0);
EXPECT_DOUBLE_EQ(unit.z(), 0.0);
result = vector::Normalize(Vector3d(0.0, 0.0, 0.0), Epsilon::kOne);
EXPECT_FALSE(result.HasValue());
result = vector::Normalize(Vector3d(0.5, 0.5, 1.0), Epsilon::kOne);
ASSERT_TRUE(result.HasValue());
unit = result.ValueOrDie();
EXPECT_DOUBLE_EQ(unit.x(), std::sqrt(1.0 / 6.0));
EXPECT_DOUBLE_EQ(unit.y(), std::sqrt(1.0 / 6.0));
EXPECT_DOUBLE_EQ(unit.z(), std::sqrt(2.0 / 3.0));
}
} // namespace math
} // namespace robotics_common
| 38.664773 | 80 | 0.68626 | [
"vector"
] |
d843ebad641f630862593315b228d27fcf5be69d | 11,636 | cpp | C++ | src/sockets.cpp | jlwitthuhn/cycles-shader-editor | 0d6771801402ca7ecff006f399be90b1beea2884 | [
"MIT"
] | 11 | 2018-04-05T06:52:17.000Z | 2021-12-14T07:02:52.000Z | src/sockets.cpp | jlwitthuhn/cycles-shader-editor | 0d6771801402ca7ecff006f399be90b1beea2884 | [
"MIT"
] | 2 | 2018-01-18T04:30:58.000Z | 2020-07-25T09:49:23.000Z | src/sockets.cpp | jlwitthuhn/cycles-shader-editor | 0d6771801402ca7ecff006f399be90b1beea2884 | [
"MIT"
] | 4 | 2018-04-02T13:36:40.000Z | 2021-08-21T21:23:23.000Z | #include "sockets.h"
#include "curve.h"
#include <algorithm>
#include <cassert>
#include <memory>
static constexpr float CURVE_CREATE_POINT_IGNORE_MARGIN = 0.012f;
static constexpr float CURVE_POINT_SELECT_MARGIN = 0.05f;
static bool Float2_x_lt(const cse::Float2 a, const cse::Float2 b)
{
return a.x < b.x;
}
cse::IntSocketValue::IntSocketValue(int default_val, int min, int max)
{
this->default_val = default_val;
this->min = min;
this->max = max;
set_value(default_val);
}
cse::SocketType cse::IntSocketValue::get_type() const
{
return SocketType::INT;
}
int cse::IntSocketValue::get_value()
{
return value;
}
void cse::IntSocketValue::set_value(int value_in)
{
if (value_in < min) {
value = min;
}
else if (value_in > max) {
value = max;
}
else {
value = value_in;
}
}
cse::FloatSocketValue::FloatSocketValue(float default_val, float min, float max)
{
this->default_val = default_val;
this->min = min;
this->max = max;
set_value(default_val);
}
cse::SocketType cse::FloatSocketValue::get_type() const
{
return SocketType::FLOAT;
}
float cse::FloatSocketValue::get_value()
{
return value;
}
void cse::FloatSocketValue::set_value(float value_in)
{
if (value_in < min) {
value = min;
}
else if (value_in > max) {
value = max;
}
else {
value = value_in;
}
}
cse::Float3SocketValue::Float3SocketValue(
float default_x, float min_x, float max_x,
float default_y, float min_y, float max_y,
float default_z, float min_z, float max_z) :
x_socket_val(std::make_shared<FloatSocketValue>(default_x, min_x, max_x)),
y_socket_val(std::make_shared<FloatSocketValue>(default_y, min_y, max_y)),
z_socket_val(std::make_shared<FloatSocketValue>(default_z, min_z, max_z))
{
}
cse::SocketType cse::Float3SocketValue::get_type() const
{
return SocketType::VECTOR;
}
cse::Float3 cse::Float3SocketValue::get_value()
{
const float x = x_socket_val->get_value();
const float y = y_socket_val->get_value();
const float z = z_socket_val->get_value();
const Float3 result(x, y, z);
return result;
}
void cse::Float3SocketValue::set_x(const float x_in)
{
x_socket_val->set_value(x_in);
}
void cse::Float3SocketValue::set_y(const float y_in)
{
y_socket_val->set_value(y_in);
}
void cse::Float3SocketValue::set_z(const float z_in)
{
z_socket_val->set_value(z_in);
}
cse::ColorSocketValue::ColorSocketValue(const float default_r, const float default_g, const float default_b) :
r_socket_val(std::make_shared<FloatSocketValue>(default_r, 0.0f, 1.0f)),
g_socket_val(std::make_shared<FloatSocketValue>(default_g, 0.0f, 1.0f)),
b_socket_val(std::make_shared<FloatSocketValue>(default_b, 0.0f, 1.0f))
{
}
cse::SocketType cse::ColorSocketValue::get_type() const
{
return SocketType::COLOR;
}
cse::StringEnumPair cse::StringEnumPair::make_spacer()
{
StringEnumPair result = StringEnumPair("-", "-");
result.this_is_spacer = true;
return result;
}
cse::StringEnumPair::StringEnumPair(const std::string& display_value, const std::string& internal_value)
{
this->display_value = display_value;
this->internal_value = internal_value;
}
bool cse::StringEnumPair::is_spacer() const
{
return this_is_spacer;
}
cse::StringEnumSocketValue::StringEnumSocketValue() : value("", "")
{
}
cse::SocketType cse::StringEnumSocketValue::get_type() const
{
return SocketType::STRING_ENUM;
}
bool cse::StringEnumSocketValue::set_from_internal_name(std::string internal_name)
{
for (StringEnumPair this_pair : enum_values) {
if (this_pair.internal_value == internal_name) {
value = this_pair;
return true;
}
}
return false;
}
cse::BoolSocketValue::BoolSocketValue(bool default_val)
{
default_value = default_val;
value = default_value;
}
cse::SocketType cse::BoolSocketValue::get_type() const
{
return SocketType::BOOLEAN;
}
cse::CurveSocketValue::CurveSocketValue()
{
reset_value();
}
cse::SocketType cse::CurveSocketValue::get_type() const
{
return SocketType::CURVE;
}
void cse::CurveSocketValue::reset_value()
{
curve_points.clear();
Float2 default_0(0.0f, 0.0f);
Float2 default_1(1.0f, 1.0f);
curve_points.push_back(default_0);
curve_points.push_back(default_1);
}
void cse::CurveSocketValue::create_point(float x)
{
for (const Float2& this_point : curve_points) {
const bool is_above_with_margin = x + CURVE_CREATE_POINT_IGNORE_MARGIN > this_point.x;
const bool is_below_with_margin = x - CURVE_CREATE_POINT_IGNORE_MARGIN < this_point.x;
if (is_above_with_margin && is_below_with_margin) {
return;
}
}
// Find the current value at x
CurveEvaluator curve(this);
const float y = curve.eval(x);
curve_points.push_back(Float2(x, y));
sort_curve_points();
}
void cse::CurveSocketValue::delete_point(const Float2& target)
{
if (curve_points.size() <= 1) {
return;
}
size_t target_index;
bool target_found = get_target_index(target, target_index);
if (target_found) {
curve_points.erase(curve_points.begin() + target_index);
}
}
bool cse::CurveSocketValue::get_target_index(const Float2& target, std::size_t& index)
{
constexpr float MAX_DISTANCE_SQUARED = CURVE_POINT_SELECT_MARGIN * CURVE_POINT_SELECT_MARGIN;
bool target_found = false;
size_t target_index = 0;
float target_distance_squared = MAX_DISTANCE_SQUARED;
for (size_t i = 0; i < curve_points.size(); i++) {
const Float2& this_point = curve_points[i];
const Float2 delta = target - this_point;
const float distance_squared = delta.magnitude_squared();
if (distance_squared < target_distance_squared) {
target_distance_squared = distance_squared;
target_index = i;
target_found = true;
}
}
if (target_found) {
index = target_index;
return true;
}
return false;
}
size_t cse::CurveSocketValue::move_point(const std::size_t index, const Float2& new_point)
{
if (index >= curve_points.size()) {
// Index should always be valid
assert(false);
}
curve_points[index] = new_point;
sort_curve_points();
for (size_t i = 0; i < curve_points.size(); i++) {
const Float2 this_point = curve_points[i];
if (this_point == new_point) {
return i;
}
}
// Control should have returned already
assert(false);
return 0;
}
void cse::CurveSocketValue::sort_curve_points()
{
std::sort(curve_points.begin(), curve_points.end(), Float2_x_lt);
}
cse::ColorRampSocketValue::ColorRampSocketValue()
{
ColorRampPoint p1(0.0f, Float3(0.0f, 0.0f, 0.0f), 1.0f);
ColorRampPoint p2(1.0f, Float3(1.0f, 1.0f, 1.0f), 1.0f);
ramp_points.push_back(p1);
ramp_points.push_back(p2);
}
cse::SocketType cse::ColorRampSocketValue::get_type() const
{
return SocketType::COLOR_RAMP;
}
std::vector<cse::Float4> cse::ColorRampSocketValue::evaluate_samples(const unsigned int count) const
{
constexpr float POS_BEGIN = 0.0f;
constexpr float POS_END = 1.0f;
const float POS_INCREMENT = (POS_END - POS_BEGIN) / (count - 1);
std::vector<Float4> result;
result.reserve(count);
// Create a function-local copy of the control point vector so we can be sure it is sorted
std::vector<ColorRampPoint> ramp_points_local = this->ramp_points;
std::sort(
ramp_points_local.begin(),
ramp_points_local.end(),
[](const ColorRampPoint& lhs, const ColorRampPoint& rhs) {
return lhs.position < rhs.position;
}
);
if (ramp_points_local.size() == 0) {
// Invalid ramp, interpret as all black
result.push_back(Float4(0.0f, 0.0f, 0.0f, 1.0f));
result.push_back(Float4(0.0f, 0.0f, 0.0f, 1.0f));
}
const float pos_first_change = ramp_points_local[0].position;
const Float3 color_start = ramp_points_local[0].color;
const float alpha_start = ramp_points_local[0].alpha;
const float pos_last_change = ramp_points_local[ramp_points_local.size() - 1].position;
const Float3 color_end = ramp_points_local[ramp_points_local.size() - 1].color;
const float alpha_end = ramp_points_local[ramp_points_local.size() - 1].alpha;
{
size_t index_search_begin = 0;
for (size_t i = 0; i < count; i++) {
const float this_pos = POS_BEGIN + i * POS_INCREMENT;
if (this_pos <= pos_first_change) {
Float4 this_output(color_start.x, color_start.y, color_start.z, alpha_start);
result.push_back(this_output);
}
else if (this_pos >= pos_last_change) {
Float4 this_output(color_end.x, color_end.y, color_end.z, alpha_end);
result.push_back(this_output);
}
else {
while (ramp_points_local[index_search_begin + 1].position <= this_pos) {
index_search_begin++;
}
const ColorRampPoint low = ramp_points_local[index_search_begin];
const ColorRampPoint high = ramp_points_local[index_search_begin + 1];
const float segment_size = high.position - low.position;
const float relative_pos = this_pos - low.position;
const float lerp_val = relative_pos / segment_size;
const float out_r = low.color.x + (high.color.x - low.color.x) * lerp_val;
const float out_g = low.color.y + (high.color.y - low.color.y) * lerp_val;
const float out_b = low.color.z + (high.color.z - low.color.z) * lerp_val;
const float out_a = low.alpha + (high.alpha - low.alpha) * lerp_val;
result.push_back(Float4(out_r, out_g, out_b, out_a));
}
}
}
return result;
}
cse::Float3 cse::ColorSocketValue::get_value()
{
const float r = r_socket_val->get_value();
const float g = g_socket_val->get_value();
const float b = b_socket_val->get_value();
const Float3 result(r, g, b);
return result;
}
cse::NodeSocket::NodeSocket(EditableNode* parent, SocketIOType io_type, SocketType socket_type, std::string display_name, std::string internal_name) :
parent(parent)
{
this->io_type = io_type;
this->socket_type = socket_type;
this->display_name = display_name;
this->internal_name = internal_name;
// Set selectable flag for editable data types
if (io_type == SocketIOType::INPUT) {
if (socket_type == SocketType::FLOAT ||
socket_type == SocketType::COLOR ||
socket_type == SocketType::STRING_ENUM ||
socket_type == SocketType::INT ||
socket_type == SocketType::BOOLEAN ||
socket_type == SocketType::CURVE ||
socket_type == SocketType::COLOR_RAMP)
{
selectable = true;
}
}
// Set flag to not draw
if (socket_type == SocketType::STRING_ENUM ||
socket_type == SocketType::INT ||
socket_type == SocketType::BOOLEAN ||
socket_type == SocketType::CURVE ||
socket_type == SocketType::COLOR_RAMP)
{
draw_socket = false;
}
}
void cse::NodeSocket::set_float_val(float float_in)
{
if (socket_type != SocketType::FLOAT) {
return;
}
const std::shared_ptr<FloatSocketValue> float_val = std::dynamic_pointer_cast<FloatSocketValue>(value);
if (float_val) {
float_val->set_value(float_in);
}
}
void cse::NodeSocket::set_float3_val(float x_in, float y_in, float z_in)
{
if (socket_type != SocketType::COLOR && socket_type != SocketType::VECTOR) {
return;
}
if (socket_type == SocketType::COLOR) {
const std::shared_ptr<ColorSocketValue> color_val = std::dynamic_pointer_cast<ColorSocketValue>(value);
if (color_val) {
color_val->r_socket_val->set_value(x_in);
color_val->g_socket_val->set_value(y_in);
color_val->b_socket_val->set_value(z_in);
}
}
else if (socket_type == SocketType::VECTOR) {
const std::shared_ptr<Float3SocketValue> float3_val = std::dynamic_pointer_cast<Float3SocketValue>(value);
if (float3_val) {
float3_val->set_x(x_in);
float3_val->set_y(y_in);
float3_val->set_z(z_in);
}
}
}
void cse::NodeSocket::set_string_val(StringEnumPair string_in)
{
if (socket_type != SocketType::STRING_ENUM) {
return;
}
const std::shared_ptr<StringEnumSocketValue> string_enum_val = std::dynamic_pointer_cast<StringEnumSocketValue>(value);
if (string_enum_val) {
string_enum_val->value = string_in;
}
}
| 25.077586 | 150 | 0.728429 | [
"vector"
] |
d84a8ccf08e5d024a86e8ca5f5043d4e71f8bab8 | 7,794 | cpp | C++ | software/libvot/src/utils/io_utils.cpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 181 | 2015-09-18T13:46:17.000Z | 2022-02-15T06:14:11.000Z | software/libvot/src/utils/io_utils.cpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 23 | 2015-12-29T21:39:16.000Z | 2019-07-31T10:44:36.000Z | software/libvot/src/utils/io_utils.cpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 60 | 2015-09-18T13:46:47.000Z | 2021-11-09T03:26:07.000Z | /*
Copyright (c) 2015, Tianwei Shen
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 libvot 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.
*/
/*! \file io_utils.cpp
* \brief I/O utilities implementations
*
* This file contains some utility classes and functions to facilitate file read/write.
*/
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cassert>
#include "io_utils.h"
// defines for file IO manipulation
#if defined(__WIN32__) || defined(_MSC_VER)
#include <io.h>
#include <windows.h>
#include <sys/stat.h>
#if defined(_MSC_VER)
#include <direct.h>
#endif
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#endif
// define for GetAvailMem()
#if defined(__WIN32__) || defined(_MSC_VER)
#include <excpt.h>
#else
#include <sys/sysctl.h>
#endif
#if defined(_MSC_VER)
#include <intrin.h>
#endif
namespace tw
{
template<typename T> T* allocate_2d(T ***array, int row, int col)
{
*array = (T**) malloc(row * sizeof(T*));
T *data = (T*) malloc(row * col * sizeof(T));
for (int i = 0; i < row; i++) {
(*array)[i] = data + i * col;
}
return data;
}
template<typename T> void free_2d(T ***array, T *data)
{
free(data);
free(*array);
}
template int* allocate_2d<int>(int ***array, int row, int col);
template void free_2d<int>(int ***array, int *data);
template float* allocate_2d<float>(float***array, int row, int col);
template void free_2d<float>(float ***array, float *data);
template double* allocate_2d<double>(double ***array, int row, int col);
template void free_2d<double>(double ***array, double *data);
template <class charType>
void IO::TrimLeft(std::basic_string<charType> & str, const char* chars2remove)
{
if (!str.empty()) { //trim the characters in chars2remove from the left
std::string::size_type pos = 0;
if (chars2remove != NULL) {
pos = str.find_first_not_of(chars2remove);
if (pos != std::string::npos)
str.erase(0,pos);
else
str.erase( str.begin() , str.end() ); // make empty
}
else //trim space
{
pos = std::string::npos; //pos = -1
for (size_t i = 0; i < str.size(); ++i) {
if (!isspace(str[i])) {
pos = i;
break;
}
}
if (pos != std::string::npos) {
if (pos > 0) {
size_t length = str.size() - pos;
for (size_t i = 0; i < length; ++i)
str[i] = str[i+pos];
str.resize(length);
}
}
else
{
str.clear();
}
}
}
}
template <class charType>
void IO::TrimRight(std::basic_string<charType> & str, const char* chars2remove)
{
if (!str.empty()) { //trim the characters in chars2remove from the right
std::string::size_type pos = 0;
if (chars2remove != NULL) {
pos = str.find_last_not_of(chars2remove);
if (pos != std::string::npos)
str.erase(pos+1);
else
str.erase( str.begin() , str.end() ); // make empty
}
else { //trim space
pos = std::string::npos;
for (int i = str.size()-1; i >= 0; --i) {
if (!isspace(str[i])) {
pos = i;
break;
}
}
if (pos != std::string::npos) {
if (pos+1 != str.size())
str.resize(pos+1);
}
else {
str.clear();
}
}
}
}
template <class charType>
void IO::Trim(std::basic_string<charType> & str, const char* chars2remove)
{
TrimLeft(str, chars2remove);
TrimRight(str, chars2remove);
}
bool IO::IsEmptyString(const std::string & str)
{
if (str.empty()) { //this is true when the length of str is 0
return true;
}
for (size_t i = 0; i < str.length(); ++i) {
if (!isspace(str[i]))
return false;
}
return true;
}
int IO::ExtractLines(const char *input_file_path, std::vector<std::string> &lines)
{
int lineNum = -1;
std::ifstream fin(input_file_path);
if (!fin.is_open()) {
std::cerr << "Can't open the file " << input_file_path << "\n";
return lineNum;
}
while (!fin.eof()) {
std::string line;
getline(fin, line);
Trim(line);
if (!IsEmptyString(line)) {
lines.push_back(line);
lineNum++;
}
}
return lineNum;
}
bool IO::IsFileExist(const char *filename) //POSIX
{
struct stat buffer;
return (stat(filename, &buffer) == 0);
}
bool IO::IsFileExist(const std::string& filename)
{
std::ifstream infile(filename);
return infile.good();
}
std::string IO::JoinPath(std::string folder, std::string filename)
{
#ifdef WIN32
std::string sep = "\\";
#else
std::string sep = "/";
#endif
if (folder.length() > 0) {
if (folder[folder.size()-1] != sep[0])
return folder+sep+filename;
else
return folder+filename;
}
else
return filename;
}
std::pair<std::string, std::string> IO::SplitPath(std::string path)
{
std::pair<std::string, std::string> res;
size_t found;
found = path.find_last_of("/\\");
res.first = path.substr(0, found);
res.second = path.substr(found+1);
return res;
}
std::pair<std::string, std::string> IO::SplitPathExt(std::string path)
{
std::pair<std::string, std::string> res;
size_t found;
found = path.find_last_of(".");
res.first = path.substr(0, found);
res.second = path.substr(found+1);
return res;
}
std::string IO::GetFilename(std::string path)
{
std::string res = SplitPath(path).second;
res = SplitPathExt(res).first;
return res;
}
bool IO::Mkdir(const std::string path)
{
#ifdef _MSC_VER
int mkDirRes = _mkdir(path.c_str());
#elif __WIN32__
int mkDirRes = mkdir(path.c_str());
#else
int mkDirRes = mkdir(path.c_str(), S_IRWXU | S_IRGRP | S_IROTH);
#endif
if (0 == mkDirRes || (mkDirRes !=0 && EEXIST == errno) ) {
std::cout << "Create folder \"" << path<< "\"" << std::endl;
}
else {
std::cout << "The folder may exist \"" << path<< "\"" << std::endl;
};
return mkDirRes == 0;
}
size_t IO::GetAvailMem()
{
// get the physical memory
size_t total_mem;
#if defined(__linux__) // linux
long pages = sysconf(_SC_PHYS_PAGES);
long page_size = sysconf(_SC_PAGE_SIZE);
total_mem = pages * page_size;
#elif defined(__APPLE__) // mac
int mib[2] = { CTL_HW, HW_MEMSIZE };
u_int namelen = sizeof(mib) / sizeof(mib[0]);
size_t len = sizeof(total_mem);
if (sysctl(mib, namelen, &total_mem, &len, NULL, 0) < 0) {
assert(false && "IO::GetAvailMem() failed on MacOS");
return 0;
}
#else // windows
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
total_mem = status.ullTotalPhys;
#endif
// reserve some memory for system purpose
return total_mem * 3/4;
}
} // end of namespace tw
| 25.223301 | 87 | 0.663844 | [
"vector"
] |
d852b6ede3166c4ea1111032c19175354cd7835c | 6,193 | cpp | C++ | lab2/src/uloha2.cpp | patrotom/bez | b1c37163a85be438173c26301824756947e1c744 | [
"MIT"
] | null | null | null | lab2/src/uloha2.cpp | patrotom/bez | b1c37163a85be438173c26301824756947e1c744 | [
"MIT"
] | null | null | null | lab2/src/uloha2.cpp | patrotom/bez | b1c37163a85be438173c26301824756947e1c744 | [
"MIT"
] | null | null | null | #include <openssl/evp.h>
#include "hexa_byte_convertor.h"
using namespace std;
//Class that handles ciphering and determinating the OT from public OT, public CT and its own CT
class RC4 {
public:
//Constructor will load two open texts and type of cipher and will prepare all of the necessary variables to be used while ciphering
RC4 ( string openPub, string openPri, string cN ) {
m_Ctx = EVP_CIPHER_CTX_new();
//Convert C++ string to array of unsigned chars - this format is required by the cipher function
for ( size_t i = 0; i < openPub.length(); i++ )
m_OpenPub[i] = (unsigned char) openPub[i];
for ( size_t i = 0; i < openPri.length(); i++ )
m_OpenPri[i] = (unsigned char) openPri[i];
//Preparing necessary variables for ciphering
const char * cipherName = cN.c_str();
OpenSSL_add_all_ciphers();
m_Cipher = EVP_get_cipherbyname ( cipherName );
m_OpenPubLength = openPub.length();
m_OpenPriLength = openPri.length();
m_CiphPubLength = 0;
m_CiphPriLength = 0;
//Preparing the initial vector and secret key for ciphering
string key = "top secret key!!";
string iv = "initial vector";
for ( size_t i = 0; i < key.length(); i++ )
m_Key[i] = (unsigned char) key[i];
for ( size_t i = 0; i < iv.length(); i++ )
m_InitialVector[i] = (unsigned char) iv[i];
}
//------------
~RC4 () {
EVP_CIPHER_CTX_free ( m_Ctx );
}
//------------
//Function will check whether the cipher name is valid or not
bool checkCipher () {
return m_Cipher;
}
//------------
//Function will print loaded open texts
void printOpenTexts () {
cout << "Public OT: " << m_OpenPub << endl;
cout << "Public OT - hex: ";
for ( int i = 0; i < m_OpenPubLength; i++ )
printf ( "%02x", m_OpenPub[i] );
cout << endl;
cout << "Private OT: " << m_OpenPri << endl;
cout << "Private OT - hex: ";
for ( int i = 0; i < m_OpenPriLength; i++ )
printf ( "%02x", m_OpenPri[i] );
cout << endl;
}
//Function will print ciphered texts
void printCipherTexts () {
cout << "Public CT: " << m_CiphPub << endl;
cout << "Public CT - hex: ";
for ( int i = 0; i < m_CiphPubLength; i++ )
printf ( "%02x", m_CiphPub[i] );
cout << endl;
cout << "Private CT: " << m_CiphPri << endl;
cout << "Private CT - hex: ";
for ( int i = 0; i < m_CiphPriLength; i++ )
printf ( "%02x", m_CiphPri[i] );
cout << endl;
}
//------------
//Function will cipher text
void cipherText () {
int tmpLength = 0;
EVP_EncryptInit ( m_Ctx, m_Cipher, m_Key, m_InitialVector );
EVP_EncryptUpdate ( m_Ctx, m_CiphPri, &tmpLength, m_OpenPri, m_OpenPriLength );
m_CiphPriLength += tmpLength;
EVP_EncryptFinal ( m_Ctx, m_CiphPri + m_CiphPriLength, &tmpLength );
m_CiphPriLength += tmpLength;
EVP_EncryptInit ( m_Ctx, m_Cipher, m_Key, m_InitialVector );
EVP_EncryptUpdate ( m_Ctx, m_CiphPub, &tmpLength, m_OpenPub, m_OpenPubLength );
m_CiphPubLength += tmpLength;
EVP_EncryptFinal ( m_Ctx, m_CiphPub + m_CiphPubLength, &tmpLength );
m_CiphPubLength += tmpLength;
}
//------------
//Function will decipher text
void decipherText () {
int tmpLength = 0;
EVP_DecryptInit ( m_Ctx, m_Cipher, m_Key, m_InitialVector );
EVP_DecryptUpdate ( m_Ctx, m_OpenPri, &tmpLength, m_CiphPri, m_CiphPriLength );
m_OpenPriLength += tmpLength;
EVP_DecryptFinal ( m_Ctx, m_OpenPri + m_OpenPriLength, &tmpLength );
m_OpenPriLength += tmpLength;
EVP_DecryptInit ( m_Ctx, m_Cipher, m_Key, m_InitialVector );
EVP_DecryptUpdate ( m_Ctx, m_OpenPub, &tmpLength, m_CiphPub, m_CiphPubLength );
m_OpenPubLength += tmpLength;
EVP_DecryptFinal ( m_Ctx, m_OpenPub + m_OpenPubLength, &tmpLength );
m_OpenPubLength += tmpLength;
}
//------------
//Function will break cipher text using public OT, public CT and its own CT -> it will output needed OT
string breakCipher ( string pubOT, string pubCT, string priCT ) {
vector<uint8_t> bytePubOT = Converter::hexaToByte ( pubOT );
vector<uint8_t> bytePubCT = Converter::hexaToByte ( pubCT );
vector<uint8_t> bytePriCT = Converter::hexaToByte ( priCT );
vector<uint8_t> publicXor = Converter::byteXOR ( bytePubOT, bytePubCT );
vector<uint8_t> privateXor = Converter::byteXOR ( bytePriCT, publicXor );
return ( Converter::ByteToASCII ( privateXor ) );
}
private:
unsigned char m_OpenPub [1024];
unsigned char m_OpenPri [1024];
unsigned char m_CiphPub [1024];
unsigned char m_CiphPri [1024];
unsigned char m_Key [1024];
unsigned char m_InitialVector [1024];
const EVP_CIPHER * m_Cipher;
int m_OpenPubLength, m_OpenPriLength, m_CiphPubLength, m_CiphPriLength;
EVP_CIPHER_CTX * m_Ctx;
};
int main () {
//Handler object which will load two open texts and type of cipher
RC4 handler ( "abcdefghijklmnopqrstuvwxyz0123", "this is top secret message!!!!", "RC4" );
//Function will check whether the cipher name is valid or invalid
if ( !handler.checkCipher() ) {
cout << "Given cipher does not exist!" << endl;
return 1;
}
//Printing open texts and equivalent cipher texts
handler.printOpenTexts();
handler.cipherText ();
cout << "---------------------" << endl;
cout << "---------------------" << endl;
handler.printCipherTexts();
cout << "---------------------" << endl;
cout << "---------------------" << endl;
//Function will determinate the OT from public OT, public CT and its own CT
cout << handler.breakCipher ( "6162636465666768696a6b6c6d6e6f707172737475767778797a30313233", "e0f571ead0ad80a660263f5cd5885bf17fa3411f017306801dd1634db9f1", "f5ff7bfd95a294ee7d232410cb8357f36ba512061176029903ce725daae3" ) << endl;
return 0;
} | 40.743421 | 235 | 0.608106 | [
"object",
"vector"
] |
d85dd6013fd109cf31cb8f9df7ff60d31c971625 | 1,033 | cpp | C++ | code/wolf.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/wolf.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/wolf.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int cards;
int value;
char suit;
vector<int> c;
vector<int> s;
vector<int> h;
vector<int> d;
cin >> cards;
if (cards < 26) {
cout << "impossible";
}
else if(cards > 26){
cout << "possible";
}
else{
for (int i = 0; i < 26; i++) {
cin >> value >> suit;
if (suit == 'C') {
c.push_back(value);
}
if (suit == 'S') {
s.push_back(value);
}
if (suit == 'H') {
h.push_back(value);
}
if (suit == 'D') {
d.push_back(value);
}
}
for (int i = 0; i < c.size(); i++) {
if (c[i] != i + 1) {
cout << "possible";
return 0;
}
}
for (int i = 0; i < s.size(); i++) {
if (s[i] != i + 1) {
cout << "possible";
return 0;
}
}
for (int i = 0; i < h.size(); i++) {
if (h[i] != i + 1) {
cout << "possible";
return 0;
}
}
for (int i = 0; i < d.size(); i++) {
if (d[i] != i + 1) {
cout << "possible";
return 0;
}
}
cout << "impossible";
}
return 0;
}
| 16.140625 | 38 | 0.454017 | [
"vector"
] |
d860f5e7db0daa938d82a94c7c0049cb6bac4f86 | 9,554 | hpp | C++ | state_extract.hpp | cschreib/qphot | b71de6175088ec165876ee9369299c8c8e9d207f | [
"MIT"
] | null | null | null | state_extract.hpp | cschreib/qphot | b71de6175088ec165876ee9369299c8c8e9d207f | [
"MIT"
] | null | null | null | state_extract.hpp | cschreib/qphot | b71de6175088ec165876ee9369299c8c8e9d207f | [
"MIT"
] | null | null | null | void get_background_apertures(const vec2b& mask, double radius, vec1u& y, vec1u& x) {
y.clear();
x.clear();
// First segment the mask
segment_output sdo;
vec2u seg = segment(mask, sdo);
// Add segments at the edges
seg(0,_) = seg(seg.dims[0]-1,_) = seg(_,0) = seg(_,seg.dims[1]-1) = max(sdo.id)+1;
// Build distance from segments
vec2d dist;
vec2u dist_id;
segment_distance(seg, dist, dist_id);
// Now add circles on the largest distance point repeatedly until there is no
// space left
double radius2 = sqr(radius);
uint_t mid = max_id(dist);
while (dist[mid] >= radius2) {
vec1u muid = mult_ids(dist, mid);
y.push_back(muid[0]);
x.push_back(muid[1]);
dist[mid] = 0;
dist_id[mid] = mid;
std::vector<uint_t> oy = {muid[0]}, ox = {muid[1]};
while (!ox.empty()) {
auto toy = oy, tox = ox;
oy.clear(); ox.clear();
while (!tox.empty()) {
uint_t ty = toy.back(); toy.pop_back();
uint_t tx = tox.back(); tox.pop_back();
auto check_add = [&](uint_t tty, uint_t ttx) {
if (dist.safe(tty,ttx) == 0) return;
if (dist_id.safe(ty,tx) == mid) {
double nd = sqr(double(tty) - y.back()) + sqr(double(ttx) - x.back());
if (nd < radius2) {
// Still within the circle, move on
dist.safe(tty,ttx) = 0;
dist_id.safe(tty,ttx) = mid;
oy.push_back(tty);
ox.push_back(ttx);
} else {
// Setup new origin and continue below
dist_id.safe(ty,tx) = flat_id(dist, ty, tx);
}
}
if (dist_id.safe(ty,tx) != mid) {
double x0 = dist_id.safe(ty,tx) % dist_id.dims[1];
double y0 = dist_id.safe(ty,tx) / dist_id.dims[1];
double nd = sqr(double(tty) - y0) + sqr(double(ttx) - x0);
if (dist.safe(tty,ttx) > nd) {
dist.safe(tty,ttx) = nd;
dist_id.safe(tty,ttx) = dist_id.safe(ty,tx);
oy.push_back(tty);
ox.push_back(ttx);
}
}
};
if (ty != 0) check_add(ty-1,tx);
if (ty != dist.dims[0]-1) check_add(ty+1,tx);
if (tx != 0) check_add(ty,tx-1);
if (tx != dist.dims[1]-1) check_add(ty,tx+1);
}
}
mid = max_id(dist);
}
}
void state_t::extract_fluxes() {
if (!good) return;
for (auto& img : images) {
if (!img.covered || img.source.flux_method != "aper") continue;
auto& rdata = img.regridded_data;
auto& rpsf = img.regridded_psf;
if (opts.verbose) note("extracting ", img.source.short_name);
if (rdata.empty()) {
// Regrid, if not done in the previous stages already
if (opts.verbose) note(" regridding...");
regrid(img);
}
if (!img.source.noconvolve && !img.convolved) {
if (opts.verbose) note(" convolving for homogenization...");
convolve_to(img, worst_seeing);
}
if (opts.verbose) note(" creating background apertures (", img.aperture, " arcsec)");
// Create background regions
double aper_radius = img.aperture/det_aspix/2.0;
double threshold = opts.bg_threshold;
vec1u bx, by;
// Make sure the distance between each region is at least the aperture
// radius, and if the image has been convolved, make sure it is also larger
// than the convolution scale so that noise is not correlated.
double min_dist = aper_radius;
if (!img.source.noconvolve) {
min_dist = sqrt(sqr(min_dist) + sqr(img.conv_radius));
}
// Flag center of image where the source is, just in case it didn't make it into
// the detection image
vec2b center = circular_mask(det_img.dims, max(det_seeing, img.seeing)/2.0/det_aspix,
det_img.dims[0]/2, det_img.dims[1]/2) > 0.2;
if (opts.no_neighbor_mask_background || img.source.no_neighbor_mask_background) {
get_background_apertures(center || !is_finite(rdata), min_dist, by, bx);
} else {
segment_output sdo;
segment_params sdp;
sdp.min_area = 4;
vec2b exclude = segment(det_img > threshold, sdo, sdp) > 0;
get_background_apertures(exclude || center || !is_finite(rdata), min_dist, by, bx);
if (by.size() < opts.min_bg_aper) {
uint_t ntry = 0;
while (by.size() < opts.min_bg_aper && ntry < 4) {
++ntry;
write_warning("could place only ", by.size()," background apertures below ", threshold, " sigma");
threshold += 0.5;
exclude = segment(det_img > threshold, sdo, sdp) > 0;
write_warning("trying again with a threshold of ", threshold, " sigma");
get_background_apertures(exclude || center || !is_finite(rdata), min_dist, by, bx);
}
if (by.size() < opts.min_bg_aper) {
// Try without masking neighbors, just the central source
write_warning("could place only ", by.size()," background apertures below ", threshold, " sigma");
write_warning("trying again without masking neighbors");
get_background_apertures(center || !is_finite(rdata), min_dist, by, bx);
}
}
}
if (by.size() < opts.min_bg_aper) {
write_error("could not place enough background apertures (needed ",
opts.min_bg_aper, ", got ", by.size(), ")");
write_error("please check the detection image");
good = false;
return;
}
// Write regions
if (!opts.nocuts) {
write_ds9_region(outdir+img.source.short_name+"_bg.reg",
det_wcs, by, bx, aper_radius);
}
if (opts.verbose) note(" placed ", by.size(), " background apertures");
// Create aperture mask
vec2d aper_mask; {
uint_t y0 = det_img.dims[0]/2;
uint_t x0 = det_img.dims[1]/2;
aper_mask = circular_mask(det_img.dims, aper_radius, y0, x0);
// Write region
if (!opts.nocuts) {
write_ds9_region(outdir+img.source.short_name+"_aper.reg",
det_wcs, vec1u({y0}), vec1u({x0}), aper_radius);
}
}
if (opts.verbose) {
note("extracting aperture flux...");
}
// Compute centroid
double y0 = 0, x0 = 0, taper = 0;
for (uint_t iy : range(aper_mask.dims[0]))
for (uint_t ix : range(aper_mask.dims[1])) {
y0 += iy*aper_mask.safe(iy,ix);
x0 += ix*aper_mask.safe(iy,ix);
taper += aper_mask.safe(iy,ix);
}
y0 /= taper;
x0 /= taper;
// Find good pixels
img.mask = vec2d(is_finite(rdata));
rdata[where(img.mask < 0.5)] = 0;
img.flux_bg = replicate(dnan, bx.size());
vec1d bg_area(bx.size());
for (uint_t i : range(bx)) {
// Make background aperture mask
vec2d bg_mask = circular_mask(aper_mask.dims, aper_radius, by[i], bx[i]);
bg_area[i] = total(bg_mask);
// Compute fractional area covered inside the mask
double covcor = bg_area[i]/total(bg_mask*img.mask);
// Sum pixels and correct for coverage
img.flux_bg[i] = total(rdata*bg_mask*img.mask)*covcor;
}
// Clip strong background outliers
vec1u idgbg = where(sigma_clip(img.flux_bg, 10.0));
if (idgbg.size() < 3) {
// Still not enough, just use everything
idgbg = uindgen(img.flux_bg.size());
}
img.num_bg = idgbg.size();
// Compute and subtract background level
img.background = median(img.flux_bg[idgbg]/bg_area[idgbg]);
rdata -= img.background;
// Compute aperture flux
img.flux = total(rdata*aper_mask*img.mask);
// Compute uncertainty from background apertures
// (the second term accounts for the uncertainty on the background level)
img.flux_err = stddev(img.flux_bg[idgbg])*sqrt(1.0 + 1.0/idgbg.size());
// Compute aperture correction from this image's PSF (assumes point source!)
vec2d model = make_point_source(rpsf, rdata.dims, y0, x0);
// vec2d model = translate(rpsf, y0 - rpsf.dims[0]/2, x0 - rpsf.dims[1]/2);
img.apcor = 1.0/total(model*aper_mask*img.mask);
// Apply aperture correction
img.flux *= img.apcor;
img.flux_err *= img.apcor;
// Write regridded, convolved and background subtracted image
if (!opts.nocuts) {
rdata[where(img.mask < 0.5)] = dnan;
fits::write(outdir+img.source.short_name+"_regrid.fits",
rdata, img.regridded_hdr
);
}
}
}
| 38.369478 | 118 | 0.520934 | [
"vector",
"model"
] |
d86223d871253580c079457d898e1fe89ecb046e | 2,221 | hpp | C++ | include/lxgui/gui_rendertarget.hpp | cschreib/lxgui | b317774d9b4296dda8a70b994950987378a05678 | [
"MIT"
] | 50 | 2015-01-15T10:00:31.000Z | 2022-02-04T20:45:25.000Z | include/lxgui/gui_rendertarget.hpp | cschreib/lxgui | b317774d9b4296dda8a70b994950987378a05678 | [
"MIT"
] | 88 | 2020-03-15T17:40:04.000Z | 2022-03-15T08:21:44.000Z | include/lxgui/gui_rendertarget.hpp | cschreib/lxgui | b317774d9b4296dda8a70b994950987378a05678 | [
"MIT"
] | 19 | 2017-03-11T04:32:01.000Z | 2022-01-12T22:47:12.000Z | #ifndef LXGUI_GUI_RENDERTARGET_HPP
#define LXGUI_GUI_RENDERTARGET_HPP
#include <lxgui/lxgui.hpp>
#include <lxgui/utils.hpp>
#include "lxgui/gui_bounds2.hpp"
#include "lxgui/gui_color.hpp"
namespace lxgui {
namespace gui
{
/// A place to render things (the screen, a texture, ...)
/** \note This is an abstract class that must be inherited
* from and created by the corresponding gui::renderer.
*/
class render_target
{
public :
/// Constructor.
render_target() = default;
/// Destructor.
virtual ~render_target() = default;
/// Non-copiable
render_target(const render_target&) = delete;
/// Non-movable
render_target(render_target&&) = delete;
/// Non-copiable
render_target& operator=(const render_target&) = delete;
/// Non-movable
render_target& operator=(render_target&&) = delete;
/// Begins rendering on this target.
virtual void begin() = 0;
/// Ends rendering on this target.
virtual void end() = 0;
/// Clears the content of this render_target.
/** \param mColor The color to use as background
*/
virtual void clear(const color& mColor) = 0;
/// Returns this render target's pixel rect.
/** \return This render target's pixel rect
*/
virtual bounds2f get_rect() const = 0;
/// Sets this render target's dimensions.
/** \param mDimensions The new dimensions (in pixels)
* \return 'true' if the function had to re-create a new render target
*/
virtual bool set_dimensions(const vector2ui& mDimensions) = 0;
/// Returns this render target's canvas dimension.
/** \return This render target's canvas dimension
* \note This is the physical size of the render target.
* On some systems, abitrary dimensions are not supported:
* they can be promoted to the nearest power of two from
* for example.
*/
virtual vector2ui get_canvas_dimensions() const = 0;
};
}
}
#endif
| 30.424658 | 80 | 0.591625 | [
"render"
] |
d865162e56506432e45303356fd614d8fe517800 | 6,163 | cpp | C++ | src/generated/camera_device.cpp | kailiu-aibee/python-ricoh-camera-sdk | b84a7738e965adcb2983eac777237321aeaaf02f | [
"MIT"
] | null | null | null | src/generated/camera_device.cpp | kailiu-aibee/python-ricoh-camera-sdk | b84a7738e965adcb2983eac777237321aeaaf02f | [
"MIT"
] | 1 | 2020-08-02T15:08:16.000Z | 2020-08-03T05:31:25.000Z | src/generated/camera_device.cpp | kailiu-aibee/python-ricoh-camera-sdk | b84a7738e965adcb2983eac777237321aeaaf02f | [
"MIT"
] | 1 | 2022-01-10T07:56:36.000Z | 2022-01-10T07:56:36.000Z | // generate by pypp
// original source code: ricoh_camera_sdk/camera_device.hpp
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "ricoh_camera_sdk/camera_device_setting.hpp"
#include "ricoh_camera_sdk/camera_image_list.hpp"
#include "ricoh_camera_sdk/camera_storage_list.hpp"
#include "ricoh_camera_sdk/capture_setting.hpp"
#include "ricoh_camera_sdk/response.hpp"
#include "ricoh_camera_sdk/camera_event_listener.hpp"
#include "ricoh_camera_sdk/camera_device.hpp"
// TODO: forward declaration class Response
// TODO: forward declaration class StartCaptureResponse
// TODO: forward declaration class CameraStorageList
// TODO: forward declaration class CameraImageList
// TODO: forward declaration class CameraEventListener
// TODO: forward declaration class CameraDeviceSetting
// TODO: forward declaration class CaptureSetting
void init_ricoh_camera_sdk_camera_device_hpp(pybind11::module scope) {
pybind11::class_<Ricoh::CameraController::CameraDevice, std::shared_ptr<Ricoh::CameraController::CameraDevice>>(scope, "CameraDevice")
.def("__eq__", &Ricoh::CameraController::CameraDevice::operator==)
.def("__ne__", &Ricoh::CameraController::CameraDevice::operator!=)
.def("connect", &Ricoh::CameraController::CameraDevice::connect)
.def("disconnect", &Ricoh::CameraController::CameraDevice::disconnect)
.def("isConnected", &Ricoh::CameraController::CameraDevice::isConnected)
.def("getManufacturer", &Ricoh::CameraController::CameraDevice::getManufacturer, pybind11::return_value_policy::reference_internal)
.def("getModel", &Ricoh::CameraController::CameraDevice::getModel, pybind11::return_value_policy::reference_internal)
.def("getFirmwareVersion", &Ricoh::CameraController::CameraDevice::getFirmwareVersion, pybind11::return_value_policy::reference_internal)
.def("getSerialNumber", &Ricoh::CameraController::CameraDevice::getSerialNumber, pybind11::return_value_policy::reference_internal)
.def("getStatus", &Ricoh::CameraController::CameraDevice::getStatus, pybind11::return_value_policy::reference_internal)
.def("getStorages", &Ricoh::CameraController::CameraDevice::getStorages, pybind11::return_value_policy::reference_internal)
.def("getImages", &Ricoh::CameraController::CameraDevice::getImages, pybind11::return_value_policy::reference_internal)
.def("addEventListener", &Ricoh::CameraController::CameraDevice::addEventListener)
.def("removeEventListener", &Ricoh::CameraController::CameraDevice::removeEventListener)
.def("getEventListeners", &Ricoh::CameraController::CameraDevice::getEventListeners, pybind11::return_value_policy::reference_internal)
.def("focus", static_cast<Ricoh::CameraController::Response(Ricoh::CameraController::CameraDevice::*)()>(&Ricoh::CameraController::CameraDevice::focus))
.def("focus", static_cast<Ricoh::CameraController::Response(Ricoh::CameraController::CameraDevice::*)(const Ricoh::CameraController::Point &)>(&Ricoh::CameraController::CameraDevice::focus))
.def("focus", static_cast<Ricoh::CameraController::Response(Ricoh::CameraController::CameraDevice::*)(int)>(&Ricoh::CameraController::CameraDevice::focus))
.def("startCapture", static_cast<Ricoh::CameraController::StartCaptureResponse(Ricoh::CameraController::CameraDevice::*)(bool)>(&Ricoh::CameraController::CameraDevice::startCapture))
.def("startCapture", static_cast<Ricoh::CameraController::StartCaptureResponse(Ricoh::CameraController::CameraDevice::*)(const Ricoh::CameraController::Point &)>(&Ricoh::CameraController::CameraDevice::startCapture))
.def("stopCapture", &Ricoh::CameraController::CameraDevice::stopCapture)
.def("startLiveView", &Ricoh::CameraController::CameraDevice::startLiveView)
.def("stopLiveView", &Ricoh::CameraController::CameraDevice::stopLiveView)
.def("getCameraDeviceSettings", &Ricoh::CameraController::CameraDevice::getCameraDeviceSettings)
.def("getCameraDeviceSettings", [](Ricoh::CameraController::CameraDevice &self, const pybind11::list &list) {
std::vector<Ricoh::CameraController::CameraDeviceSetting *> settings;
for (const auto &obj : list) {
settings.push_back(obj.cast<Ricoh::CameraController::CameraDeviceSetting *>());
}
return self.getCameraDeviceSettings(settings);
})
.def("setCameraDeviceSettings", &Ricoh::CameraController::CameraDevice::setCameraDeviceSettings)
.def("setCameraDeviceSettings", [](Ricoh::CameraController::CameraDevice &self, const pybind11::list &list) {
std::vector<const Ricoh::CameraController::CameraDeviceSetting *> settings;
for (const auto &obj : list) {
settings.push_back(obj.cast<const Ricoh::CameraController::CameraDeviceSetting *>());
}
return self.setCameraDeviceSettings(settings);
})
.def("getCaptureSettings", &Ricoh::CameraController::CameraDevice::getCaptureSettings)
.def("getCaptureSettings", [](Ricoh::CameraController::CameraDevice &self, const pybind11::list &list) {
std::vector<Ricoh::CameraController::CaptureSetting *> settings;
for (const auto &obj : list) {
settings.push_back(obj.cast<Ricoh::CameraController::CaptureSetting *>());
}
return self.getCaptureSettings(settings);
})
.def("setCaptureSettings", &Ricoh::CameraController::CameraDevice::setCaptureSettings)
.def("setCaptureSettings", [](Ricoh::CameraController::CameraDevice &self, const pybind11::list &list) {
std::vector<const Ricoh::CameraController::CaptureSetting *> settings;
for (const auto &obj : list) {
settings.push_back(obj.cast<const Ricoh::CameraController::CaptureSetting *>());
}
return self.setCaptureSettings(settings);
})
;
pybind11::enum_<Ricoh::CameraController::DeviceInterface>(scope, "DeviceInterface")
.value("USB", Ricoh::CameraController::DeviceInterface::USB)
;
}
| 69.247191 | 224 | 0.72919 | [
"vector"
] |
d865e74fe660ee60581a18e5a915d6082c051c4b | 844 | cpp | C++ | src/algo/index_search.cpp | setyolegowo/ITB-IF5111-2019 | 4b53c9a69e49bb801fa65b633689670bf2edf4ff | [
"MIT"
] | null | null | null | src/algo/index_search.cpp | setyolegowo/ITB-IF5111-2019 | 4b53c9a69e49bb801fa65b633689670bf2edf4ff | [
"MIT"
] | null | null | null | src/algo/index_search.cpp | setyolegowo/ITB-IF5111-2019 | 4b53c9a69e49bb801fa65b633689670bf2edf4ff | [
"MIT"
] | null | null | null | /**
* index_search.cpp file.
* Implementation.
*
* @author Setyo Legowo <gw.tio145@gmail.com>
* @since 2019.02.26
*/
#include <string>
#include <stdexcept>
#include "index_search.hpp"
IndexSearch::IndexSearch(int _index)
{
this->index = _index;
}
IndexSearch *IndexSearch::createFromConsoleArgument(int argc, char **argv)
{
if (argc < 5) {
throw "Lack of argument for index search: <index_number>";
}
int index;
try {
index = std::stoi(argv[4]);
} catch (const std::invalid_argument& ia) {
throw "Invalid argument for <index_number>";
}
return new IndexSearch(index);
}
bool IndexSearch::find(std::vector<House> *houseList)
{
try {
houseList->at(this->index);
return true;
} catch (const std::out_of_range& oor) {
//
}
return false;
} | 18.755556 | 74 | 0.619668 | [
"vector"
] |
d86a266c2043393a528f7d4e5cc53359961b1f5e | 2,497 | cpp | C++ | src/application/views/TS_ViewTerminal.cpp | thomasschwarz96/ts-timetracker | df3a190fac0d91df31dd871edd0bcf6d3a688d2d | [
"MIT"
] | 7 | 2020-02-03T08:24:16.000Z | 2020-02-26T23:51:36.000Z | src/application/views/TS_ViewTerminal.cpp | tomschwarz/ts-timetracker | df3a190fac0d91df31dd871edd0bcf6d3a688d2d | [
"MIT"
] | null | null | null | src/application/views/TS_ViewTerminal.cpp | tomschwarz/ts-timetracker | df3a190fac0d91df31dd871edd0bcf6d3a688d2d | [
"MIT"
] | null | null | null | /**
* TS-ViewTerminal
*
* Terminal, text driven view class.
*
* @package TS-TimeTracker
* @author Thomas Schwarz
* @copyright Copyright (c) 2019, Thomas Schwarz
* @license MIT License (https://opensource.org/licenses/MIT)
* @since Version 0.1.0
* @filesource
*/
#include "TS_IView.h"
#include "TS_ViewTerminal.h"
#include <iostream>
#include <cstring>
#include "TS_ConfigReader.h"
#include "TS_Helper.h"
#include "TS_Info.h"
#include "TS_ModelFilesystem.h"
#include "TS_Command.h"
#include "TS_FactoryCommand.h"
#include "TS_Application.h"
/**
* @inherit
*/
TS_ViewTerminal::TS_ViewTerminal() : TS_IView()
{
this->model = new TS_ModelFilesystem();
}
/**
* @inherit
*/
void TS_ViewTerminal::render()
{
static char input[2048];
TS_ConfigReader config;
TS_Helper helper;
TS_Info::welcome();
if (!config.configLoaded)
{
std::cout << "No config file found!" << std::endl;
std::cout << "Please check out the documentation: " << std::endl;
std::cout << "https://raw.githubusercontent.com/thomasschwarz96/ts-timetracker/master/README.md" << std::endl;
return;
}
TS_Info::showInfo();
TS_ModelFilesystem* model = new TS_ModelFilesystem();
// Interactive shell
while (true)
{
/* Output our prompt */
std::cout << helper.color << "ts-timetracker> " << helper.noColor;
/* Read a line of user input of maximum size 2048 */
std::cin.getline(input, sizeof(input));
// Check if user want to exit
if (strcmp(input, "exit") == 0 || strcmp(input, "q") == 0)
{
std::cout << "Goodbye!" << std::endl;
return;
}
application->setCommandWithAttributes(input);
if (application->isCommandValid())
{
TS_Command *command = TS_FactoryCommand::build(
application->getCommand(),
application->getArguments(),
model
);
if (command != nullptr)
{
command->execute();
std::cout << command->getMessage().str() << std::endl;
}
}
else
{
std::cout << "You entered a wrong command! \n";
std::cout << "Type 'help' to get more informations. \n";
}
}
}
/**
* Setter for model
* @param TS_IModel* newModel
*/
void TS_ViewTerminal::setModel(TS_IModel *newModel)
{
this->model = newModel;
}
| 24.242718 | 118 | 0.575891 | [
"render",
"model"
] |
d86bcfe271be3f09b00e6a4ebe90e6bef1bdd25b | 8,654 | cpp | C++ | algorithms.cpp | snowiow/SIFT | 83364b87f60cd8c859a058fb67f4cf321e016a07 | [
"MIT"
] | 41 | 2016-04-21T21:15:37.000Z | 2021-11-12T02:46:54.000Z | algorithms.cpp | snowiow/SIFT | 83364b87f60cd8c859a058fb67f4cf321e016a07 | [
"MIT"
] | 13 | 2015-06-09T07:10:18.000Z | 2017-07-17T08:09:11.000Z | algorithms.cpp | snowiow/SIFT | 83364b87f60cd8c859a058fb67f4cf321e016a07 | [
"MIT"
] | 16 | 2017-02-28T06:11:05.000Z | 2021-08-21T04:46:53.000Z | #include "algorithms.hpp"
#include <vigra/convolution.hxx>
#include <vigra/linear_algebra.hxx>
using namespace vigra::linalg;
namespace sift {
namespace alg {
const vigra::MultiArray<2, f32_t> convolveWithGauss(const vigra::MultiArray<2, f32_t>& img,
f32_t sigma) {
vigra::Kernel1D<f32_t> filter;
filter.initGaussian(sigma);
vigra::MultiArray<2, f32_t> tmp(img.shape());
vigra::MultiArray<2, f32_t> result(img.shape());
separableConvolveX(img, tmp, filter);
separableConvolveY(tmp, result, filter);
return result;
}
const vigra::MultiArray<2, f32_t> reduceToNextLevel(const vigra::MultiArray<2, f32_t>& img,
f32_t sigma) {
// image size at current level
const vigra::Shape2 s((img.width()+ 1) / 2, (img.height() + 1) / 2);
// resize result image to appropriate size
vigra::MultiArray<2, f32_t> out(s);
// downsample smoothed image
resizeImageNoInterpolation(convolveWithGauss(img, sigma), out);
return out;
}
const vigra::MultiArray<2, f32_t> increaseToNextLevel(const vigra::MultiArray<2, f32_t>& img,
f32_t sigma) {
// image size at current level
const vigra::Shape2 s(img.width() * 2, img.height() * 2);
// resize result image to appropriate size
vigra::MultiArray<2, f32_t> out(s);
// downsample smoothed image
resizeImageNoInterpolation(convolveWithGauss(img, sigma), out);
return out;
}
const vigra::MultiArray<2, f32_t> dog(const vigra::MultiArray<2, f32_t>& lower,
const vigra::MultiArray<2, f32_t>& higher) {
vigra::MultiArray<2, f32_t> result(vigra::Shape2(lower.shape()));
for (u16_t x = 0; x < lower.shape(0); x++) {
for (u16_t y = 0; y < lower.shape(1); y++) {
const f32_t dif = higher(x, y) - lower(x, y);
// don't get negative values
result(x, y) = 128 + dif;
}
}
return result;
}
const vigra::Matrix<f32_t> foDerivative(const std::array<vigra::MultiArray<2, f32_t>, 3>& img,
const Point<u16_t, u16_t>& p) {
const f32_t dx = (img[1](p.x - 1, p.y) - img[1](p.x + 1, p.y)) / 2;
const f32_t dy = (img[1](p.x, p.y - 1) - img[1](p.x, p.y + 1)) / 2;
const f32_t ds = (img[0](p.x, p.y) - img[2](p.x, p.y)) / 2;
vigra::Matrix<f32_t> result(vigra::Shape2(3, 1));
result(0, 0) = dx;
result(1, 0) = dy;
result(2, 0) = ds;
return result;
}
const vigra::Matrix<f32_t> soDerivative(const std::array<vigra::MultiArray<2, f32_t>, 3>& img,
const Point<u16_t, u16_t>& p) {
const f32_t dxx = img[1](p.x + 1, p.y) + img[1](p.x - 1, p.y) - 2 * img[1](p.x, p.y);
const f32_t dyy = img[1](p.x, p.y + 1) + img[1](p.x, p.y - 1) - 2 * img[1](p.x, p.y);
const f32_t dss = img[2](p.x, p.y) + img[0](p.x, p.y) - 2 * img[1](p.x, p.y);
const f32_t dxy = (img[1](p.x + 1, p.y + 1) - img[1](p.x - 1, p.y + 1) - img[1](p.x + 1, p.y - 1)
+ img[1](p.x - 1, p.y - 1)) / 2;
const f32_t dxs = (img[2](p.x + 1, p.y) - img[2](p.x - 1, p.y)
- img[0](p.x + 1, p.y) + img[0](p.x - 1, p.y)) / 2;
f32_t dys = (img[2](p.x, p.y + 1) - img[2](p.x, p.y + 1)
- img[0](p.x, p.y + 1) + img[0](p.x, p.y - 1)) / 2;
vigra::MultiArray<2, f32_t> sec_deriv(vigra::Shape2(3, 3));
sec_deriv(0, 0) = dxx;
sec_deriv(1, 0) = dxy;
sec_deriv(2, 0) = dxs;
sec_deriv(0, 1) = dxy;
sec_deriv(1, 1) = dyy;
sec_deriv(2, 1) = dys;
sec_deriv(0, 2) = dxs;
sec_deriv(1, 2) = dys;
sec_deriv(2, 2) = dss;
return sec_deriv;
}
f32_t gradientMagnitude(const vigra::MultiArray<2, f32_t>& img, const Point<u16_t, u16_t>& p) {
return std::sqrt(std::pow(img(p.x + 1, p.y) - img(p.x - 1, p.y), 2) +
std::pow(img(p.x, p.y + 1) - img(p.x, p.y - 1), 2));
}
f32_t gradientOrientation(const vigra::MultiArray<2, f32_t>& img, const Point<u16_t, u16_t>& p) {
const f32_t result = std::atan2(img(p.x, p.y + 1) - img(p.x, p.y - 1), img(p.x + 1, p.y) - img(p.x - 1, p.y));
return std::fmod(result + 360, 360);
}
const std::array<f32_t, 36> orientationHistogram36(
const vigra::MultiArray<2, f32_t>& orientations,
const vigra::MultiArray<2, f32_t>& magnitudes,
const vigra::MultiArray<2, f32_t>& current_gauss) {
std::array<f32_t, 36> bins = {{0}};
for (u16_t x = 0; x < orientations.width(); x++) {
for (u16_t y = 0; y < orientations.height(); y++) {
const f32_t sum = magnitudes(x, y) * current_gauss(x, y);
u16_t i = std::floor(orientations(x, y) / 10);
i = i % 35;
bins[i] += sum;
}
}
return bins;
}
const std::vector<f32_t> orientationHistogram8(
const vigra::MultiArray<2, f32_t>& orientations,
const vigra::MultiArray<2, f32_t>& magnitudes,
const vigra::MultiArray<2, f32_t>& current_gauss) {
std::vector<f32_t> bins(8, 0);
for (u16_t x = 0; x < orientations.width(); x++) {
for (u16_t y = 0; y < orientations.height(); y++) {
const f32_t sum = magnitudes(x, y) * current_gauss(x, y);
u16_t i = std::floor(orientations(x, y) / 45);
i = i % 7;
bins[i] += sum;
}
}
return bins;
}
f32_t vertexParabola(const Point<u16_t, f32_t>& ln, const Point<u16_t, f32_t>& peak,
const Point<u16_t, f32_t>& rn) {
vigra::MultiArray<2, f32_t> a(vigra::Shape2(3, 3));
a(0, 0) = std::pow(ln.x, 2);
a(1, 0) = std::pow(peak.x, 2);
a(2, 0) = std::pow(rn.x, 2);
a(0, 1) = ln.x;
a(1, 1) = peak.x;
a(2, 1) = rn.x;
a(0, 2) = 0;
a(1, 2) = 0;
a(2, 2) = 0;
vigra::MultiArray<2, f32_t> b(vigra::Shape2(3, 1));
b(0, 0) = ln.y;
b(1, 0) = peak.y;
b(2, 0) = rn.y;
vigra::MultiArray<2, f32_t> res(vigra::Shape2(3, 1));
linearSolve(a, b, res);
return -res(1, 0) / (2 * res(0, 0));
}
std::array<Point<f32_t, f32_t>, 4> rotateShape(const Point<u16_t, u16_t>& center, f32_t angle,
const u16_t width, const u16_t height) {
//Determine upper left and bottom right point
auto ul = Point<f32_t, f32_t>(center.x - width / 2, center.y - height / 2);
auto ur = Point<f32_t, f32_t>(center.x - width / 2, center.y + height / 2);
auto bl = Point<f32_t, f32_t>(center.x + width / 2, center.y - height / 2);
auto br = Point<f32_t, f32_t>(center.x + width / 2, center.y + height / 2);
std::array<Point<f32_t, f32_t>, 4> shape{{ul, ur, bl, br}};
//Perform clockwise rotation
angle *= -1;
for (Point<f32_t, f32_t>& p : shape) {
//Transform center to 0, 0
p.x -= center.x;
p.y -= center.y;
//Perform rotation based on rotation matrix for both points
p.x = ul.x * std::cos(angle) - p.y * std::sin(angle);
p.y = ul.x * std::sin(angle) + p.y * std::cos(angle);
//Transform center back to original position
ul.x += center.x;
ul.y += center.y;
}
return shape;
}
void normalizeVector(std::vector<f32_t>& vec) {
//Get length of vector
f32_t length = 0;
std::for_each(vec.begin(), vec.end(), [&](f32_t& n) {
length += n;
});
if (length == 0) {
return;
}
std::for_each(vec.begin(), vec.end(), [&](f32_t& n) {
n /= length;
});
}
}
}
| 38.292035 | 122 | 0.471574 | [
"shape",
"vector",
"transform"
] |
d873dbd34b241b22170a63806b8a69198492db68 | 10,907 | cpp | C++ | Testing/ComparatorBlockTest.cpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 2 | 2021-01-19T02:21:48.000Z | 2022-03-26T23:05:49.000Z | Testing/ComparatorBlockTest.cpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 3 | 2020-07-26T18:48:21.000Z | 2020-10-28T00:45:42.000Z | Testing/ComparatorBlockTest.cpp | pothosware/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T06:22:20.000Z | 2022-03-24T06:22:20.000Z | // Copyright (c) 2019-2020 Nicholas Corgan
// SPDX-License-Identifier: BSD-3-Clause
#include "TestUtility.hpp"
#include "Utility.hpp"
#include <Pothos/Exception.hpp>
#include <Pothos/Framework.hpp>
#include <Pothos/Object.hpp>
#include <Pothos/Proxy.hpp>
#include <Pothos/Testing.hpp>
#include <arrayfire.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <typeinfo>
#include <vector>
static constexpr const char* arrayBlockRegistryPath = "/gpu/array/comparator";
static constexpr const char* scalarBlockRegistryPath = "/gpu/scalar/comparator";
template <typename T, typename ComparatorFcn>
static void getScalarTestValues(
ComparatorFcn comparatorFcn,
Pothos::BufferChunk* pInput,
Pothos::Object* pScalar,
Pothos::BufferChunk* pOutput)
{
const auto dtype = Pothos::DType(typeid(T));
(*pInput) = GPUTests::getTestInputs(dtype.name());
(*pScalar) = GPUTests::getRandomValue(*pInput);
(*pOutput) = Pothos::BufferChunk("int8", pInput->elements());
const T* inputBuffer = pInput->as<const T*>();
const T& scalar = pScalar->extract<T>();
char* outputBuffer = pOutput->as<char*>();
for(size_t i = 0; i < pInput->elements(); ++i)
{
outputBuffer[i] = comparatorFcn(inputBuffer[i], scalar) ? 1 : 0;
}
}
template <typename T, typename ComparatorFcn>
static void getArrayTestValues(
ComparatorFcn comparatorFcn,
Pothos::BufferChunk* pInput0,
Pothos::BufferChunk* pInput1,
Pothos::BufferChunk* pOutput)
{
const auto dtype = Pothos::DType(typeid(T));
(*pInput0) = GPUTests::getTestInputs(dtype.name());
(*pInput1) = GPUTests::getTestInputs(dtype.name());
POTHOS_TEST_EQUAL(pInput0->elements(), pInput1->elements());
(*pOutput) = Pothos::BufferChunk("int8", pInput0->elements());
const T* inputBuffer0 = pInput0->as<const T*>();
const T* inputBuffer1 = pInput1->as<const T*>();
char* outputBuffer = pOutput->as<char*>();
for(size_t i = 0; i < pInput0->elements(); ++i)
{
outputBuffer[i] = comparatorFcn(inputBuffer0[i], inputBuffer1[i]) ? 1 : 0;
}
}
static void getScalarTestValues(
const std::string& type,
const std::string& operation,
Pothos::BufferChunk* pInput,
Pothos::Object* pScalar,
Pothos::BufferChunk* pOutput)
{
static const Pothos::DType Int8DType("int8");
const Pothos::DType dtype(type);
#define GET_SCALAR_TEST_VALUES_FOR_OP(op, cType, func) \
if(operation == op) \
{ \
getScalarTestValues<cType>(func, pInput, pScalar, pOutput); \
} \
#define GET_SCALAR_TEST_VALUES(typeStr, cType) \
if(type == typeStr) \
{ \
\
GET_SCALAR_TEST_VALUES_FOR_OP(">", cType, std::greater<cType>()); \
GET_SCALAR_TEST_VALUES_FOR_OP(">=", cType, std::greater_equal<cType>()); \
GET_SCALAR_TEST_VALUES_FOR_OP("<", cType, std::less<cType>()); \
GET_SCALAR_TEST_VALUES_FOR_OP("<=", cType, std::less_equal<cType>()); \
GET_SCALAR_TEST_VALUES_FOR_OP("==", cType, std::equal_to<cType>()); \
GET_SCALAR_TEST_VALUES_FOR_OP("!=", cType, std::not_equal_to<cType>()); \
\
return; \
}
GET_SCALAR_TEST_VALUES("int8", char)
GET_SCALAR_TEST_VALUES("int16", short)
GET_SCALAR_TEST_VALUES("int32", int)
GET_SCALAR_TEST_VALUES("int64", long long)
GET_SCALAR_TEST_VALUES("uint8", unsigned char)
GET_SCALAR_TEST_VALUES("uint16", unsigned short)
GET_SCALAR_TEST_VALUES("uint32", unsigned)
GET_SCALAR_TEST_VALUES("uint64", unsigned long long)
GET_SCALAR_TEST_VALUES("float32", float)
GET_SCALAR_TEST_VALUES("float64", double)
}
static void getArrayTestValues(
const std::string& type,
const std::string& operation,
Pothos::BufferChunk* pInput0,
Pothos::BufferChunk* pInput1,
Pothos::BufferChunk* pOutput)
{
static const Pothos::DType Int8DType("int8");
const Pothos::DType dtype(type);
#define GET_ARRAY_TEST_VALUES_FOR_OP(op, cType, func) \
if(operation == op) \
{ \
getArrayTestValues<cType>(func, pInput0, pInput1, pOutput); \
} \
#define GET_ARRAY_TEST_VALUES(typeStr, cType) \
if(type == typeStr) \
{ \
\
GET_ARRAY_TEST_VALUES_FOR_OP(">", cType, std::greater<cType>()); \
GET_ARRAY_TEST_VALUES_FOR_OP(">=", cType, std::greater_equal<cType>()); \
GET_ARRAY_TEST_VALUES_FOR_OP("<", cType, std::less<cType>()); \
GET_ARRAY_TEST_VALUES_FOR_OP("<=", cType, std::less_equal<cType>()); \
GET_ARRAY_TEST_VALUES_FOR_OP("==", cType, std::equal_to<cType>()); \
GET_ARRAY_TEST_VALUES_FOR_OP("!=", cType, std::not_equal_to<cType>()); \
\
return; \
}
GET_ARRAY_TEST_VALUES("int8", char)
GET_ARRAY_TEST_VALUES("int16", short)
GET_ARRAY_TEST_VALUES("int32", int)
GET_ARRAY_TEST_VALUES("int64", long long)
GET_ARRAY_TEST_VALUES("uint8", unsigned char)
GET_ARRAY_TEST_VALUES("uint16", unsigned short)
GET_ARRAY_TEST_VALUES("uint32", unsigned)
GET_ARRAY_TEST_VALUES("uint64", unsigned long long)
GET_ARRAY_TEST_VALUES("float32", float)
GET_ARRAY_TEST_VALUES("float64", double)
}
static void testScalarComparatorBlockForTypeAndOperation(
const Pothos::DType& type,
const std::string& operation)
{
std::cout << "Testing " << scalarBlockRegistryPath
<< " (type: " << type.name()
<< ", operation: " << operation << ")" << std::endl;
if(isDTypeComplexFloat(Pothos::DType(type)))
{
POTHOS_TEST_THROWS(
Pothos::BlockRegistry::make(
scalarBlockRegistryPath,
"Auto",
operation,
type,
0),
Pothos::ProxyExceptionMessage);
}
else
{
auto afComparator = Pothos::BlockRegistry::make(
scalarBlockRegistryPath,
"Auto",
operation,
type,
0);
POTHOS_TEST_EQUAL(
type,
afComparator.call("input", 0).call("dtype").call<std::string>("name"));
POTHOS_TEST_EQUAL(
"int8",
afComparator.call("output", 0).call("dtype").call<std::string>("name"));
Pothos::BufferChunk input;
Pothos::Object scalar;
Pothos::BufferChunk output;
getScalarTestValues(
type.name(),
operation,
&input,
&scalar,
&output);
POTHOS_TEST_GT(input.elements(), 0);
POTHOS_TEST_TRUE(scalar);
POTHOS_TEST_EQUAL(input.elements(), output.elements());
afComparator.call("setScalar", scalar);
POTHOS_TEST_EQUAL(0, scalar.compareTo(afComparator.call("scalar")));
auto feederSource = Pothos::BlockRegistry::make(
"/blocks/feeder_source",
type);
auto collectorSink = Pothos::BlockRegistry::make(
"/blocks/collector_sink",
"int8");
feederSource.call("feedBuffer", input);
// Execute the topology.
{
Pothos::Topology topology;
topology.connect(feederSource, 0, afComparator, 0);
topology.connect(afComparator, 0, collectorSink, 0);
topology.commit();
POTHOS_TEST_TRUE(topology.waitInactive(0.05));
}
GPUTests::testBufferChunk(
output,
collectorSink.call<Pothos::BufferChunk>("getBuffer"));
}
}
static void testArrayComparatorBlockForTypeAndOperation(
const Pothos::DType& type,
const std::string& operation)
{
std::cout << "Testing " << arrayBlockRegistryPath
<< " (type: " << type.name()
<< ", operation: " << operation << ")" << std::endl;
if(isDTypeComplexFloat(Pothos::DType(type)))
{
POTHOS_TEST_THROWS(
Pothos::BlockRegistry::make(
arrayBlockRegistryPath,
"Auto",
operation,
type),
Pothos::ProxyExceptionMessage);
}
else
{
auto afComparator = Pothos::BlockRegistry::make(
arrayBlockRegistryPath,
"Auto",
operation,
type);
POTHOS_TEST_EQUAL(
type,
afComparator.call("input", 0).call("dtype").call<std::string>("name"));
POTHOS_TEST_EQUAL(
type,
afComparator.call("input", 1).call("dtype").call<std::string>("name"));
POTHOS_TEST_EQUAL(
"int8",
afComparator.call("output", 0).call("dtype").call<std::string>("name"));
Pothos::BufferChunk input0;
Pothos::BufferChunk input1;
Pothos::BufferChunk output;
getArrayTestValues(
type.name(),
operation,
&input0,
&input1,
&output);
POTHOS_TEST_GT(input0.elements(), 0);
POTHOS_TEST_EQUAL(input0.elements(), input1.elements());
POTHOS_TEST_EQUAL(input0.elements(), output.elements());
auto feederSource0 = Pothos::BlockRegistry::make(
"/blocks/feeder_source",
type);
auto feederSource1 = Pothos::BlockRegistry::make(
"/blocks/feeder_source",
type);
auto collectorSink = Pothos::BlockRegistry::make(
"/blocks/collector_sink",
"int8");
feederSource0.call("feedBuffer", input0);
feederSource1.call("feedBuffer", input1);
// Execute the topology.
{
Pothos::Topology topology;
topology.connect(feederSource0, 0, afComparator, 0);
topology.connect(feederSource1, 0, afComparator, 1);
topology.connect(afComparator, 0, collectorSink, 0);
topology.commit();
POTHOS_TEST_TRUE(topology.waitInactive(0.05));
}
GPUTests::testBufferChunk(
output,
collectorSink.call<Pothos::BufferChunk>("getBuffer"));
}
}
static void testComparatorBlocksForType(const Pothos::DType& type)
{
static const std::vector<std::string> operations{"<","<=",">",">=","==","!="};
for(const std::string& operation: operations)
{
testScalarComparatorBlockForTypeAndOperation(type, operation);
testArrayComparatorBlockForTypeAndOperation(type, operation);
}
}
POTHOS_TEST_BLOCK("/gpu/tests", test_comparators)
{
GPUTests::setupTestEnv();
for(const auto& type: GPUTests::getAllDTypes())
{
testComparatorBlocksForType(type);
}
}
| 32.85241 | 84 | 0.594756 | [
"object",
"vector"
] |
f22135a6ad7707c0c58957e4a76ea5aaa6a2abba | 1,242 | hpp | C++ | cpp/common.hpp | wooseokyourself/capstone_xu4 | 2aa7d4ed6ce627a749d689fce27af3c2a0a3daf1 | [
"Beerware"
] | 1 | 2020-03-17T17:55:20.000Z | 2020-03-17T17:55:20.000Z | cpp/common.hpp | wooseokyourself/capstone_xu4 | 2aa7d4ed6ce627a749d689fce27af3c2a0a3daf1 | [
"Beerware"
] | 2 | 2020-03-18T05:04:15.000Z | 2020-05-31T11:30:09.000Z | cpp/common.hpp | wooseokyourself/capstone_xu4 | 2aa7d4ed6ce627a749d689fce27af3c2a0a3daf1 | [
"Beerware"
] | 2 | 2020-05-24T00:41:04.000Z | 2020-05-31T08:04:00.000Z | #ifndef COMMON
#define COMMON
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <cstring>
#include <fstream>
#include <string>
#include <utility>
#include <vector>
#include <thread>
#include <mutex>
#include <opencv2/core/mat.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#define ASSERT assert
#define ADMIN_MODE 0
#define BASIC_MODE 1
#define TERMINATE_MODE 2
using std::string;
string
_ROOT__PATH();
string
_CONFIG__PATH();
string
_BIN__PATH();
string
_ROI__DIR__PATH();
string
_RESULT__DIR__PATH();
#define ROOT_PATH _ROOT__PATH()
#define CONFIG_PATH _CONFIG__PATH()
#define BIN_PATH _BIN__PATH()
#define ROI_DIR_PATH _ROI__DIR__PATH()
#define RESULT_DIR_PATH _RESULT__DIR__PATH()
string
getCurrTime ();
class IOdata {
public:
int cameraNum;
std::vector<cv::Mat> imgs; // output images
std::vector<int> nums; // each outp's people number
int totalPeopleNum; // all outp's total people number
double inferenceTime; // total inference time
public:
IOdata (int cameraNum);
~IOdata ();
void clear ();
};
#endif
| 17.742857 | 59 | 0.692432 | [
"vector"
] |
f2266820961296e7d3b2a56db2e1ad78fa0fdbfe | 1,638 | cpp | C++ | flint/Checks/IncludeAssociatedHeader.cpp | AaronDMarasco/FlintPlusPlus | d1e4afc99d8c0616b8574bf8edc52a92170c6e10 | [
"BSL-1.0"
] | 1 | 2020-08-11T21:58:41.000Z | 2020-08-11T21:58:41.000Z | flint/Checks/IncludeAssociatedHeader.cpp | AaronDMarasco/FlintPlusPlus | d1e4afc99d8c0616b8574bf8edc52a92170c6e10 | [
"BSL-1.0"
] | null | null | null | flint/Checks/IncludeAssociatedHeader.cpp | AaronDMarasco/FlintPlusPlus | d1e4afc99d8c0616b8574bf8edc52a92170c6e10 | [
"BSL-1.0"
] | null | null | null | #include "../Checks.hpp"
using namespace std;
namespace flint {
/**
* Ensures .cpp files include their associated header first
* (this catches #include-time dependency bugs where .h files don't
* include things they depend on)
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
*/
void checkIncludeAssociatedHeader(ErrorFile& errors, const string& path, const vector<Token>& tokens) {
if (!isSource(path)) return;
string file(path);
size_t fpos = file.find_last_of("/\\");
if (fpos != string::npos) file = file.substr(fpos + 1);
string fileBase = getFileNameBase(file);
size_t includesFound = 0;
for (size_t pos = 0, size = tokens.size(); pos < size; ++pos) {
if (!isTok(tokens[pos], TK_INCLUDE)) continue;
++pos;
if (cmpTok(tokens[pos], "PRECOMPILED")) continue;
++includesFound;
if (!isTok(tokens[pos], TK_STRING_LITERAL)) continue;
string includedFile = getIncludedPath(tokens[pos].value_);
const size_t ipos = includedFile.find_last_of("/\\");
if (ipos != string::npos) continue;
if (cmpStr(getFileNameBase(includedFile), fileBase)) {
if (includesFound > 1) {
lintError(errors,
tokens[pos - 1],
"The associated header file of .cpp "
"files should be included before any other includes.",
"This helps catch missing header file dependencies in the .h");
break;
}
}
}
};
} // namespace flint
| 29.25 | 103 | 0.633089 | [
"vector"
] |
f22ea41752b76b0a1b9d55f410fac62b1d55d052 | 2,153 | cpp | C++ | test/test_timing_elements.cpp | mahilab/mahi-experiment | 30cb500744db2df5ac32d3f8d568b5c460ffb6d7 | [
"MIT"
] | 1 | 2020-11-18T23:42:12.000Z | 2020-11-18T23:42:12.000Z | test/test_timing_elements.cpp | mahilab/mahi-experiment | 30cb500744db2df5ac32d3f8d568b5c460ffb6d7 | [
"MIT"
] | null | null | null | test/test_timing_elements.cpp | mahilab/mahi-experiment | 30cb500744db2df5ac32d3f8d568b5c460ffb6d7 | [
"MIT"
] | null | null | null | #include<Mahi/Util.hpp>
using namespace mahi::util;
// enum so that I can use training/testing instead of ambiguous 0 and 1
enum Session{
training, // 0
testing // 1
};
int main(int argc, char* argv[]) {
std::vector<std::string> session_strings = {"Training", "Testing"};
// times that we will use for the two session times
Time train_time = seconds(10);
Time test_time = seconds(15);
// make a vector so that I can access the times using session_times[current_session]
std::vector<Time> session_times = { train_time , test_time };
Session current_session = training;
Clock session_clock;
Clock trial_clock;
print("Starting Training session. You have {} seconds.\n", train_time.as_seconds());
// if the session clock expires, exit the loop and end the section. Note that if the session clock expires in training,
// it will just restart given if statement at the end of the while loop, so it must be the testing section for this to exit
while ( session_clock.get_elapsed_time() < session_times[current_session]){
print("Press \"C\" to print the current time.\nIf it is after the alotted session time, the session will end.");
// restart the trial clock so that we can get the time when someone hits "C"
trial_clock.restart();
// wait until the 'C' key is pressed
while(get_key() != 'c'){};
print("Session: {}", session_strings[current_session]);
print("Trial time: {} seconds. Session time remaining: {} seconds.\n", trial_clock.get_elapsed_time().as_seconds(), (session_times[current_session]-session_clock.get_elapsed_time()).as_seconds());
// if the session timing is up and the current session is trianing, reset session clock and change the session to "testing"
if (session_clock.get_elapsed_time() > session_times[current_session] && current_session == training){
cls();
print("Starting Testing session. You have {} seconds.\n", test_time.as_seconds());
current_session = testing;
session_clock.restart();
}
}
} | 43.06 | 204 | 0.669763 | [
"vector"
] |
f239ab8496654d430a368a0ccd7ccb79c36df7b7 | 9,940 | cpp | C++ | src/door.cpp | adct-the-experimenter/Door-To-Life-Minimal | a4a08d13443bdf21d4efc27f8509f5d5f8d57584 | [
"BSD-2-Clause"
] | null | null | null | src/door.cpp | adct-the-experimenter/Door-To-Life-Minimal | a4a08d13443bdf21d4efc27f8509f5d5f8d57584 | [
"BSD-2-Clause"
] | null | null | null | src/door.cpp | adct-the-experimenter/Door-To-Life-Minimal | a4a08d13443bdf21d4efc27f8509f5d5f8d57584 | [
"BSD-2-Clause"
] | null | null | null | #include "door.h"
bool loadDoorMedia(SDL_Renderer* gRenderer,
LTexture* doorTexture,
ALuint* source,
ALuint* doorBufferOpen,
ALuint* doorBufferFail,
std::vector <SDL_Rect> &doorClips)
{
bool success = true;
//initialize texture for door
std::string doorTexFilePath = DATADIR_STR + std::string("/Graphics/door-draw.png");
if(!doorTexture->loadFromFile(doorTexFilePath.c_str(),gRenderer) )
{
success = false;
printf("Failed to load door image! \n");
}
else
{
doorClips.resize(3);
std::int16_t width = 41;
std::int16_t height = 80;
doorClips[0] = {20,0,width,height};
doorClips[1] = {81,0,width,height};
doorClips[2] = {142,0,width,height};
}
//initialize doors sound effects
std::string path = ("/Sound/Door_Open_Fail1.wav");
if(!LoadBuffer(doorBufferFail,path))
{
printf( "Failed to load door open fail sound effect!\n");
return false;
}
path = ("/Sound/Door_Open_Success.wav");
if(!LoadBuffer(doorBufferOpen,path))
{
printf( "Failed to load door open success sound effect! %s\n");
return false;
}
//setup source of door
alGenSources(1, source); //allocate source
alSource3f(*source, AL_POSITION, 0.0f, 0.0f, 0.0f);
alSource3f(*source, AL_VELOCITY, 0.0f, 0.0f, 0.0f);
return success;
}
void freeDoorMedia(LTexture* doorTexture,
ALuint* source,
ALuint* doorBufferOpen,
ALuint* doorBufferFail)
{
//free source
alDeleteSources(1, source); // delete source
//free buffer
alDeleteBuffers(1, doorBufferOpen);
alDeleteBuffers(1,doorBufferFail);
//free tile texture map
doorTexture->free();
}
void setupNewDoorObject(Door** thisDoor,
LTexture* doorTexture,
ALuint* source,
ALuint* doorBufferOpen,
ALuint* doorBufferFail,
std::vector <SDL_Rect> *ptrDoorClips)
{
*thisDoor = new Door();
(*thisDoor)->setPointersToMedia(
doorTexture,
source,
doorBufferOpen,
doorBufferFail,
ptrDoorClips);
}
Door::Door()
{
//std::cout << "Door created! \n";
//initialize bool keyInsert
keyInsert = false;
//initialize door collision box
collisionBoxDoor1.x=0;
collisionBoxDoor1.y=0;
collisionBoxDoor1.w = DOOR_WIDTH;
collisionBoxDoor1.h = DOOR_HEIGHT;
collisionBoxDoor2.x=0;
collisionBoxDoor2.y=0;
collisionBoxDoor2.w = DOOR_WIDTH;
collisionBoxDoor2.h = DOOR_HEIGHT;
//initialize door type
Door::setDoorType(Door::Type::NO_LOCK_DOOR);
//initialize door state to closed
Door::setDoorState(Door::State::DOOR_CLOSED);
//initialize key insert status
Door::setKeyInsertStatus(false);
}
Door::~Door()
{
//set pointer to key to null
doorKey = nullptr;
Door::setSoundState(Door::SoundState::NO_SOUND);
}
void Door::setDoorType(Door::Type type){doorType = type;}
Door::Type Door::getDoorType(){return doorType;}
void Door::setLock(Key* thisKey)
{
//initialize door key pointer
doorKey = thisKey;
//set door type as locked door
Door::setDoorType(Door::Type::LOCK_DOOR);
}
void Door::handle_event(Event& thisEvent)
{
switch( thisEvent )
{
case Event::SPACE:{ Door::setKeyInsertStatus(true); break;} //make keyInsert true
case Event::SPACE_RELEASE:{ Door::setKeyInsertStatus(true); break;}
default:{ Door::setKeyInsertStatus(false); break;} //make keyInsert false
}
}
void Door::playSounds()
{
//if door is open and has lock
if(Door::getSoundState() == Door::SoundState::PLAY_DOOR_OPEN_KEY)
{
//set buffer to source that is playing sound
alSourcei(*doorSource, AL_BUFFER, *doorOpenBuffer);
alSourcePlay(*doorSource);
Door::setSoundState(Door::SoundState::NO_SOUND);
}
//if key is inserted but door doesn't open
else if( Door::getSoundState() == Door::SoundState::PLAY_DOOR_FAIL)
{
//set buffer to source that is playing sound
alSourcei(*doorSource, AL_BUFFER, *doorFailBuffer);
//play sound
alSourcePlay(*doorSource);
Door::setSoundState(Door::SoundState::NO_SOUND);
}
}
void Door::setSoundState(Door::SoundState thisState){doorSoundState = thisState;}
Door::SoundState Door::getSoundState(){return doorSoundState;}
void Door::render(SDL_Rect& camera, SDL_Renderer* gRenderer)
{
switch(Door::getDoorType())
{
case Door::Type::NO_LOCK_DOOR:{ renderRectClip = &doorClips->at(0); break;}
case Door::Type::LOCK_DOOR:{ renderRectClip = &doorClips->at(1); break;}
case Door::Type::WINNER_DOOR:{ renderRectClip = &doorClips->at(2); break;}
}
if(checkCollision(Door::getCollisionBoxDoor1(),camera) )
{
//std::cout << "Door rendered at " << "x: " << //Door::getCollisionBoxDoor1().x << " y: " << Door::getCollisionBoxDoor1().y //<< std::endl;
doorImage->render(Door::getCollisionBoxDoor1().x - camera.x,
Door::getCollisionBoxDoor1().y - camera.y, gRenderer, renderRectClip);
}
if(checkCollision(Door::getCollisionBoxDoor2(),camera) )
{
//std::cout << "Door rendered at " << "x: " << //Door::getCollisionBoxDoor2().x << " y: " << Door::getCollisionBoxDoor2().y //<< std::endl;
doorImage->render(Door::getCollisionBoxDoor2().x - camera.x,
Door::getCollisionBoxDoor2().y - camera.y, gRenderer, renderRectClip);
}
}
void Door::setPointersToMedia(LTexture* doorTexture,
ALuint* source,
ALuint* doorBufferOpen,
ALuint* doorBufferFail,
std::vector <SDL_Rect> *ptrDoorClips)
{
doorImage = doorTexture;
doorSource = source;
doorOpenBuffer = doorBufferOpen;
doorFailBuffer = doorBufferFail;
doorClips = ptrDoorClips;
}
void Door::placeDoor1(std::int16_t& x, std::int16_t& y)
{
collisionBoxDoor1.x = x;
collisionBoxDoor1.y = y;
}
void Door::placeDoor2(std::int16_t& x, std::int16_t& y)
{
collisionBoxDoor2.x = x;
collisionBoxDoor2.y = y;
}
void Door::setDoorState(Door::State state){doorState = state;}
Door::State Door::getDoorState(){return doorState;}
bool checkDotCollidesWithDoor(Door* thisDoor, Dot* mainDot)
{
if( checkCollision(thisDoor->getCollisionBoxDoor1(),
mainDot->getSpaceBox()) )
{
thisDoor->doorCollideState = Door::DoorCollided::DOT_TO_DOOR1;
return true;
}
else if( checkCollision(thisDoor->getCollisionBoxDoor2(),
mainDot->getSpaceBox()) )
{
thisDoor->doorCollideState = Door::DoorCollided::DOT_TO_DOOR2;
return true;
}
else
{
thisDoor->doorCollideState = Door::DoorCollided::NONE;
return false;
}
}
void Door::openDoorLogic()
{
//if door has lock, run open door logic with lock function
if(Door::getDoorType() == Door::Type::LOCK_DOOR){Door::openDoorLogicWithLock();}
else{Door::openDoorLogicNoLock();}
//set sound state
switch(Door::getDoorState())
{
case Door::State::DOOR_CLOSED:{ Door::setSoundState(Door::SoundState::NO_SOUND); break;}
case Door::State::DOOR_OPEN_FAIL:{ Door::setSoundState(Door::SoundState::PLAY_DOOR_FAIL); break;}
case Door::State::DOOR_OPEN:{ Door::setSoundState(Door::SoundState::PLAY_DOOR_OPEN); break;}
}
}
void Door::openDoorLogicWithLock()
{
//if key is inserted and player has the key that the door owns and player is touching door
if( Door::getKeyInsertStatus() && doorKey->getKeyBool() )
{
//if dot collides with either of doors
if(doorCollideState == Door::DoorCollided::DOT_TO_DOOR1
|| doorCollideState == Door::DoorCollided::DOT_TO_DOOR2)
{
//open door
Door::setDoorState(Door::State::DOOR_OPEN);
}
}
//if key inserted and dot is at door but has no key
else if( Door::getKeyInsertStatus() && !doorKey->getKeyBool() )
{
//if dot collides with either of doors
if(doorCollideState == Door::DoorCollided::DOT_TO_DOOR1
|| doorCollideState == Door::DoorCollided::DOT_TO_DOOR2)
{
//open door
Door::setDoorState(Door::State::DOOR_OPEN_FAIL);
}
}
else
{
Door::setDoorState(Door::State::DOOR_CLOSED);
}
//reset key insert status
Door::setKeyInsertStatus(false);
}
void Door::openDoorLogicNoLock()
{
//if dot collides with either of doors
if(doorCollideState == Door::DoorCollided::DOT_TO_DOOR1
|| doorCollideState == Door::DoorCollided::DOT_TO_DOOR2)
{
//if key is inserted
if( Door::getKeyInsertStatus() )
{
//open door
Door::setDoorState(Door::State::DOOR_OPEN);
}
else
{
//keep closed
Door::setDoorState(Door::State::DOOR_CLOSED);
}
}
else
{
//keep closed
Door::setDoorState(Door::State::DOOR_CLOSED);
}
//reset key insert status
Door::setKeyInsertStatus(false);
}
void Door::setKeyInsertStatus(bool state){keyInsert = state;}
bool Door::getKeyInsertStatus(){return keyInsert;}
SDL_Rect& Door::getCollisionBoxDoor1(){return collisionBoxDoor1;}
SDL_Rect& Door::getCollisionBoxDoor2(){return collisionBoxDoor2;}
Door::DoorCollided Door::getDoorCollidedState(){return doorCollideState;}
void Door::resetDoorsToClose()
{
Door::setDoorState(Door::State::DOOR_CLOSED);
}
| 29.064327 | 146 | 0.617103 | [
"render",
"vector"
] |
f23c6d35aefe5a317c5851a59fa29c4863e7762e | 2,940 | cpp | C++ | dependencies/thermite3d/source/scriptable/Light.cpp | paroj/voxeliens | 64322d13d1661b6d5f88032b16f410516b9690b8 | [
"MIT"
] | 2 | 2020-12-13T12:11:15.000Z | 2021-06-22T13:54:53.000Z | dependencies/thermite3d/source/scriptable/Light.cpp | paroj/voxeliens | 64322d13d1661b6d5f88032b16f410516b9690b8 | [
"MIT"
] | null | null | null | dependencies/thermite3d/source/scriptable/Light.cpp | paroj/voxeliens | 64322d13d1661b6d5f88032b16f410516b9690b8 | [
"MIT"
] | 2 | 2021-03-27T04:27:57.000Z | 2021-06-22T13:54:54.000Z | #include "Light.h"
#include "Utility.h"
#include "OgreEntity.h"
#include "OgreRoot.h"
namespace Thermite
{
Light::Light(Object* parent)
:RenderComponent(parent)
,m_colColour(255,255,255)
,mType(PointLight)
,mDirectionalFixupSceneNode(0)
,mOgreLight(0)
{
}
Light::~Light()
{
if(mDirectionalFixupSceneNode)
{
if(mOgreLight)
{
mDirectionalFixupSceneNode->detachObject(mOgreLight);
}
mSceneManager->destroyLight(mOgreLight);
mSceneManager->destroySceneNode(mDirectionalFixupSceneNode);
}
}
void Light::update(void)
{
RenderComponent::update();
std::string objAddressAsString = QString::number(reinterpret_cast<qulonglong>(mParent), 16).toStdString();
//In general Ogre considers the negative z'axis to be the forward direction. This can be seen with cameras (which point along negative z)
//and also with SceneNodes (see here: http://www.ogre3d.org/docs/api/html/classOgre_1_1SceneNode.html#a4a6e34aab331802bc836668e78a08508).
//However, when it comes to directional lights the seem to emit light along the positive Z, rather than negative. This is the observed behaviour,
//although no documents have been found. As a result we insert this fixup node to reverse the direction, so they are consistant with other types.
if(mDirectionalFixupSceneNode == 0)
{
std::string sceneNodeName(objAddressAsString + "_DirectionalFixupSceneNode");
mDirectionalFixupSceneNode = mOgreSceneNode->createChildSceneNode(sceneNodeName);
mDirectionalFixupSceneNode->yaw(Ogre::Radian(3.14159265));
}
if(!mOgreLight)
{
Ogre::SceneManager* sceneManager = Ogre::Root::getSingletonPtr()->getSceneManager("OgreSceneManager");
mOgreLight = sceneManager->createLight(objAddressAsString + "_Light");
//Ogre::Entity* ogreEntity = sceneManager->createEntity(generateUID("PointLight Marker"), "Icosphere5.mesh");
mDirectionalFixupSceneNode->attachObject(mOgreLight);
//mDirectionalFixupSceneNode->attachObject(ogreEntity);
}
switch(getType())
{
case Light::PointLight:
mOgreLight->setType(Ogre::Light::LT_POINT);
mOgreLight->setAttenuation(1000, 0.0, 0.001, 0.0);
break;
case Light::DirectionalLight:
mOgreLight->setType(Ogre::Light::LT_DIRECTIONAL);
mOgreLight->setAttenuation(1000, 1.0, 1.0, 1.0);
break;
case Light::SpotLight:
mOgreLight->setType(Ogre::Light::LT_SPOTLIGHT);
break;
}
QColor col = getColour();
mOgreLight->setDiffuseColour(col.redF(), col.greenF(), col.blueF());
mOgreLight->setSpecularColour(col.redF(), col.greenF(), col.blueF());
}
const QColor& Light::getColour(void) const
{
return m_colColour;
}
void Light::setColour(const QColor& col)
{
m_colColour = col;
}
Light::LightType Light::getType(void) const
{
return mType;
}
void Light::setType(Light::LightType type)
{
mType = type;
}
}
| 30 | 148 | 0.710544 | [
"mesh",
"object"
] |
f23fc55d9a93957aebeea2a0a75802cbc7cbf651 | 79,890 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/wifi/WifiServiceImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/wifi/WifiServiceImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/wifi/WifiServiceImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "Elastos.CoreLibrary.Utility.h"
#include "Elastos.CoreLibrary.IO.h"
#include "Elastos.CoreLibrary.Net.h"
#include "Elastos.Droid.App.h"
#include "Elastos.Droid.Bluetooth.h"
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.Internal.h"
#include "Elastos.Droid.Net.h"
#include "Elastos.Droid.Os.h"
#include "Elastos.Droid.Provider.h"
#include "Elastos.Droid.Wifi.h"
#include "elastos/droid/R.h"
#include "elastos/droid/os/Binder.h"
#include "elastos/droid/os/Process.h"
#include "elastos/droid/os/UserHandle.h"
#include "elastos/droid/provider/Settings.h"
#include "elastos/droid/Manifest.h"
#include "elastos/droid/server/wifi/WifiServiceImpl.h"
#include "elastos/droid/server/am/BatteryStatsService.h"
#include "elastos/core/StringUtils.h"
#include "elastos/core/CoreUtils.h"
#include <elastos/core/AutoLock.h>
#include <elastos/utility/logging/Slogger.h>
using Elastos::Droid::App::IActivityManagerHelper;
using Elastos::Droid::App::CActivityManagerHelper;
using Elastos::Droid::Bluetooth::IBluetoothAdapter;
using Elastos::Droid::Content::IIntentFilter;
using Elastos::Droid::Content::CIntentFilter;
using Elastos::Droid::Content::Pm::IUserInfo;
using Elastos::Droid::Content::Res::IResources;
using Elastos::Droid::Internal::Telephony::ITelephonyIntents;
using Elastos::Droid::Internal::Utility::CAsyncChannel;
using Elastos::Droid::Os::Binder;
using Elastos::Droid::Os::EIID_IBinder;
using Elastos::Droid::Os::CWorkSource;
using Elastos::Droid::Os::IMessageHelper;
using Elastos::Droid::Os::CMessageHelper;
using Elastos::Droid::Os::CMessenger;
using Elastos::Droid::Os::ISystemProperties;
using Elastos::Droid::Os::CSystemProperties;
using Elastos::Droid::Os::IHandlerThread;
using Elastos::Droid::Os::CHandlerThread;
using Elastos::Droid::Os::UserHandle;
using Elastos::Droid::Os::IUserHandle;
using Elastos::Droid::Os::IUserManager;
using Elastos::Droid::Os::IUserManagerHelper;
using Elastos::Droid::Os::CUserManagerHelper;
using Elastos::Droid::Os::Process;
using Elastos::Droid::Provider::Settings;
using Elastos::Droid::Provider::ISettingsGlobal;
using Elastos::Droid::Net::CDhcpInfo;
using Elastos::Droid::Net::ILinkAddress;
using Elastos::Droid::Net::INetworkUtils;
using Elastos::Droid::Net::CNetworkUtils;
using Elastos::Droid::Net::IStaticIpConfiguration;
using Elastos::Droid::Net::IConnectivityManagerHelper;
using Elastos::Droid::Net::CConnectivityManagerHelper;
using Elastos::Droid::Manifest;
using Elastos::Droid::Server::Am::BatteryStatsService;
using Elastos::Droid::Utility::CParcelableList;
using Elastos::Droid::Wifi::CScanSettings;
using Elastos::Droid::Wifi::EIID_IIWifiManager;
using Elastos::Droid::Wifi::IWifiManager;
using Elastos::Droid::Wifi::CBatchedScanSettings;
using Elastos::Droid::Wifi::CWifiActivityEnergyInfo;
using Elastos::Droid::R;
using Elastos::Core::AutoLock;
using Elastos::Core::CoreUtils;
using Elastos::Core::StringUtils;
using Elastos::IO::ICloseable;
using Elastos::IO::IReader;
using Elastos::IO::IFileReader;
using Elastos::IO::CFileReader;
using Elastos::IO::IBufferedReader;
using Elastos::IO::CBufferedReader;
using Elastos::Net::IInetAddress;
using Elastos::Net::IInet4Address;
using Elastos::Utility::CArrayList;
using Elastos::Utility::Logging::Slogger;
namespace Elastos {
namespace Droid {
namespace Server {
namespace Wifi {
//=====================================================================
// WifiServiceImpl::TdlsTask
//=====================================================================
ECode WifiServiceImpl::TdlsTask::DoInBackground(
/* [in] */ ArrayOf<IInterface*>* params,
/* [out] */ IInterface** result)
{
VALIDATE_NOT_NULL(result);
// Retrieve parameters for the call
AutoPtr<TdlsTaskParams> param = (TdlsTaskParams*)(IObject::Probe((*params)[0]));
String remoteIpAddress = param->remoteIpAddress.Trim();
Boolean enable = param->enable;
// Get MAC address of Remote IP
String macAddress;
AutoPtr<IBufferedReader> reader;
//try {
AutoPtr<IFileReader> fileReader;
ECode ec = CFileReader::New(String("/proc/net/arp"), (IFileReader**)&fileReader);
if (FAILED(ec)) {
Slogger::E(WifiServiceImpl::TAG, "Could not open /proc/net/arp to lookup mac address");
AutoPtr<IInteger32> res = CoreUtils::Convert(0);
*result = TO_IINTERFACE(res);
REFCOUNT_ADD(*result);
return NOERROR;
}
ec = CBufferedReader::New(IReader::Probe(fileReader), (IBufferedReader**)&reader);
if (FAILED(ec)) {
Slogger::E(WifiServiceImpl::TAG, "Could not open /proc/net/arp to lookup mac address");
AutoPtr<IInteger32> res = CoreUtils::Convert(0);
*result = TO_IINTERFACE(res);
REFCOUNT_ADD(*result);
return NOERROR;
}
// Skip over the line bearing colum titles
String line;
reader->ReadLine(&line);
while ((reader->ReadLine(&line), !line.IsNull())) {
AutoPtr<ArrayOf<String> > tokens;
StringUtils::Split(line, String("[ ]+"), (ArrayOf<String>**)&tokens);
if (tokens->GetLength() < 6) {
continue;
}
// ARP column format is
// Address HWType HWAddress Flags Mask IFace
String ip = (*tokens)[0];
String mac = (*tokens)[3];
if (remoteIpAddress.Equals(ip)) {
macAddress = mac;
break;
}
}
if (macAddress.IsNull()) {
Slogger::W(WifiServiceImpl::TAG, "Did not find remoteAddress {%s} in /proc/net/arp", remoteIpAddress.string());
} else {
mOwner->EnableTdlsWithMacAddress(macAddress, enable);
}
//} catch (FileNotFoundException e) {
// Slog.e(TAG, "Could not open /proc/net/arp to lookup mac address");
//} catch (IOException e) {
// Slog.e(TAG, "Could not read /proc/net/arp to lookup mac address");
//} finally {
// try {
if (reader != NULL) {
ICloseable::Probe(reader)->Close();
}
// }
// catch (IOException e) {
// // Do nothing
// }
//}
AutoPtr<IInteger32> res = CoreUtils::Convert(0);
*result = TO_IINTERFACE(res);
REFCOUNT_ADD(*result);
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::LockList
//=====================================================================
// synchronized
ECode WifiServiceImpl::LockList::HasLocks(
/* [out] */ Boolean* result)
{
AutoLock lock(this);
VALIDATE_NOT_NULL(result);
Boolean isEmpty;
mList->IsEmpty(&isEmpty);
*result = !isEmpty;
return NOERROR;
}
// synchronized
ECode WifiServiceImpl::LockList::GetStrongestLockMode(
/* [out] */ Int32* result)
{
AutoLock lock(this);
VALIDATE_NOT_NULL(result);
Boolean isEmpty;
if (mList->IsEmpty(&isEmpty), isEmpty) {
*result = IWifiManager::WIFI_MODE_FULL;
return NOERROR;
}
if (mOwner->mFullHighPerfLocksAcquired > mOwner->mFullHighPerfLocksReleased) {
*result = IWifiManager::WIFI_MODE_FULL_HIGH_PERF;
return NOERROR;
}
if (mOwner->mFullLocksAcquired > mOwner->mFullLocksReleased) {
*result = IWifiManager::WIFI_MODE_FULL;
return NOERROR;
}
*result = IWifiManager::WIFI_MODE_SCAN_ONLY;
return NOERROR;
}
// synchronized
ECode WifiServiceImpl::LockList::UpdateWorkSource(
/* [in] */ IWorkSource* ws)
{
AutoLock lock(this);
VALIDATE_NOT_NULL(ws);
Int32 size;
mOwner->mLocks->mList->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
mOwner->mLocks->mList->Get(i, (IInterface**)&obj);
WifiLock* wifiLock = (WifiLock*)(IObject::Probe(obj));
Boolean added;
ws->Add(wifiLock->mWorkSource, &added);
}
return NOERROR;
}
WifiServiceImpl::LockList::LockList(
/* [in] */ WifiServiceImpl* owner)
: mOwner(owner)
{
CArrayList::New((IList**)&mList);
}
void WifiServiceImpl::LockList::AddLock(
/* [in] */ WifiLock* lock)
{
if (FindLockByBinder(lock->mBinder) < 0) {
mList->Add(TO_IINTERFACE(lock));
}
}
AutoPtr<WifiServiceImpl::WifiLock> WifiServiceImpl::LockList::RemoveLock(
/* [in] */ IBinder* binder)
{
Int32 index = FindLockByBinder(binder);
if (index >= 0) {
AutoPtr<IInterface> obj;
mList->Remove(index, (IInterface**)&obj);
AutoPtr<WifiLock> ret = (WifiLock*)(IObject::Probe(obj));
ret->UnlinkDeathRecipient();
return ret;
} else {
return NULL;
}
return NULL;
}
Int32 WifiServiceImpl::LockList::FindLockByBinder(
/* [in] */ IBinder* binder)
{
Int32 size;
mList->GetSize(&size);
for (Int32 i = size - 1; i >= 0; --i) {
AutoPtr<IInterface> obj;
mList->Get(i, (IInterface**)&obj);
AutoPtr<WifiLock> ret = (WifiLock*)(IObject::Probe(obj));
if (ret->mBinder.Get() == binder)
return i;
}
return -1;
}
void WifiServiceImpl::LockList::Dump(
/* [in] */ IPrintWriter* pw)
{
Int32 size;
mList->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
mList->Get(i, (IInterface**)&obj);
AutoPtr<WifiLock> ret = (WifiLock*)(IObject::Probe(obj));
pw->Print(String(" "));
String str;
ret->ToString(&str);
pw->Println(str);
}
}
//=====================================================================
// WifiServiceImpl::ClientHandler
//=====================================================================
WifiServiceImpl::ClientHandler::ClientHandler(
/* [in] */ WifiServiceImpl* owner,
/* [in] */ ILooper* looper)
: Handler(looper)
, mOwner(owner)
{
}
ECode WifiServiceImpl::ClientHandler::HandleMessage(
/* [in] */ IMessage* msg)
{
Int32 what;
msg->GetWhat(&what);
switch (what) {
case IAsyncChannel::CMD_CHANNEL_HALF_CONNECTED: {
Int32 arg1;
msg->GetArg1(&arg1);
if (arg1 == IAsyncChannel::STATUS_SUCCESSFUL) {
// We track the clients by the Messenger
// since it is expected to be always available
AutoPtr<IMessenger> replyTo;
msg->GetReplyTo((IMessenger**)&replyTo);
if (WifiServiceImpl::DBG) Slogger::D(WifiServiceImpl::TAG, "New client listening to asynchronous messages, IMessenger:%p", replyTo.Get());
mOwner->mTrafficPoller->AddClient(replyTo);
} else {
Slogger::E(TAG, "Client connection failure, error=%d", arg1);
}
break;
}
case IAsyncChannel::CMD_CHANNEL_DISCONNECTED: {
Int32 arg1;
msg->GetArg1(&arg1);
AutoPtr<IMessenger> replyTo;
msg->GetReplyTo((IMessenger**)&replyTo);
if (arg1 == IAsyncChannel::STATUS_SEND_UNSUCCESSFUL) {
if (WifiServiceImpl::DBG) Slogger::D(WifiServiceImpl::TAG, "Send failed, client connection lost, IMessenger:%p", replyTo.Get());
} else {
if (WifiServiceImpl::DBG) Slogger::D(WifiServiceImpl::TAG, "Client connection lost with reason: %d, IMessenger:%p", arg1, replyTo.Get());
}
mOwner->mTrafficPoller->RemoveClient(replyTo);
break;
}
case IAsyncChannel::CMD_CHANNEL_FULL_CONNECTION: {
AutoPtr<IAsyncChannel> ac;
CAsyncChannel::New((IAsyncChannel**)&ac);
AutoPtr<IMessenger> replyTo;
msg->GetReplyTo((IMessenger**)&replyTo);
ac->Connect(mOwner->mContext, this, replyTo);
break;
}
/* Client commands are forwarded to state machine */
case IWifiManager::CONNECT_NETWORK:
case IWifiManager::SAVE_NETWORK: {
AutoPtr<IInterface> obj;
msg->GetObj((IInterface**)&obj);
AutoPtr<IWifiConfiguration> config = IWifiConfiguration::Probe(obj);
Int32 networkId;
msg->GetArg1(&networkId);
if (what == IWifiManager::SAVE_NETWORK) {
if (config != NULL) {
Int32 confignwId;
config->GetNetworkId(&confignwId);
Int32 uid = Binder::GetCallingUid();
if (confignwId == IWifiConfiguration::INVALID_NETWORK_ID) {
config->SetCreatorUid(uid);
} else {
config->SetLastUpdateUid(uid);
}
}
Slogger::E("WiFiServiceImpl ", "SAVE nid=%d", networkId);
//+ " uid=" + Integer.toString(config.creatorUid)
//+ "/" + Integer.toString(config.lastUpdateUid);
}
if (what == IWifiManager::CONNECT_NETWORK) {
if (config != NULL) {
Int32 uid = Binder::GetCallingUid();
Int32 confignwId;
config->GetNetworkId(&confignwId);
if (confignwId == IWifiConfiguration::INVALID_NETWORK_ID) {
config->SetCreatorUid(uid);
} else {
config->SetLastUpdateUid(uid);
}
}
Slogger::E("WiFiServiceImpl ", "CONNECT nid=%d", networkId);
//+ " uid=" + Binder.getCallingUid();
}
Boolean isValid;
if (config != NULL && (config->IsValid(&isValid), isValid)) {
if (WifiServiceImpl::DBG) Slogger::D(WifiServiceImpl::TAG, "Connect with config");// + config);
AutoPtr<IMessage> message;
AutoPtr<IMessageHelper> helper;
CMessageHelper::AcquireSingleton((IMessageHelper**)&helper);
helper->Obtain(msg, (IMessage**)&message);
mOwner->mWifiStateMachine->SendMessage(message);
} else if (config == NULL
&& networkId != IWifiConfiguration::INVALID_NETWORK_ID) {
if (WifiServiceImpl::DBG) Slogger::D(TAG, "Connect with networkId %d", networkId);
AutoPtr<IMessage> message;
AutoPtr<IMessageHelper> helper;
CMessageHelper::AcquireSingleton((IMessageHelper**)&helper);
helper->Obtain(msg, (IMessage**)&message);
mOwner->mWifiStateMachine->SendMessage(message);
} else {
Slogger::E(WifiServiceImpl::TAG, "ClientHandler.handleMessage ignoring invalid msg=");// + msg);
if (what == IWifiManager::CONNECT_NETWORK) {
ReplyFailed(msg, IWifiManager::CONNECT_NETWORK_FAILED, IWifiManager::INVALID_ARGS);
} else {
ReplyFailed(msg, IWifiManager::SAVE_NETWORK_FAILED, IWifiManager::INVALID_ARGS);
}
}
break;
}
case IWifiManager::FORGET_NETWORK:
Int32 sendingUid;
msg->GetSendingUid(&sendingUid);
if (mOwner->IsOwner(sendingUid)) {
AutoPtr<IMessage> message;
AutoPtr<IMessageHelper> helper;
CMessageHelper::AcquireSingleton((IMessageHelper**)&helper);
helper->Obtain(msg, (IMessage**)&message);
mOwner->mWifiStateMachine->SendMessage(message);
} else {
Slogger::E(TAG, "Forget is not authorized for user");
ReplyFailed(msg, IWifiManager::FORGET_NETWORK_FAILED, IWifiManager::NOT_AUTHORIZED);
}
break;
case IWifiManager::START_WPS:
case IWifiManager::CANCEL_WPS:
case IWifiManager::DISABLE_NETWORK:
case IWifiManager::RSSI_PKTCNT_FETCH: {
AutoPtr<IMessage> message;
AutoPtr<IMessageHelper> helper;
CMessageHelper::AcquireSingleton((IMessageHelper**)&helper);
helper->Obtain(msg, (IMessage**)&message);
mOwner->mWifiStateMachine->SendMessage(message);
break;
}
default: {
Slogger::D(TAG, "ClientHandler.handleMessage ignoring msg=");// + msg);
break;
}
}
return NOERROR;
}
void WifiServiceImpl::ClientHandler::ReplyFailed(
/* [in] */ IMessage* msg,
/* [in] */ Int32 what,
/* [in] */ Int32 why)
{
AutoPtr<IMessage> reply;
AutoPtr<IMessageHelper> helper;
CMessageHelper::AcquireSingleton((IMessageHelper**)&helper);
helper->Obtain((IMessage**)&reply);
reply->SetWhat(what);
reply->SetArg1(why);
//try {
AutoPtr<IMessenger> messenger;
msg->GetReplyTo((IMessenger**)&messenger);
messenger->Send(reply);
//} catch (RemoteException e) {
// // There's not much we can do if reply can't be sent!
//}
}
//=====================================================================
// WifiServiceImpl::WifiStateMachineHandler
//=====================================================================
WifiServiceImpl::WifiStateMachineHandler::WifiStateMachineHandler(
/* [in] */ WifiServiceImpl* owner,
/* [in] */ ILooper* looper)
: Handler(looper)
, mOwner(owner)
{
CAsyncChannel::New((IAsyncChannel**)&mWsmChannel);
AutoPtr<IHandler> handler;
mOwner->mWifiStateMachine->GetHandler((IHandler**)&handler);
mWsmChannel->Connect(mOwner->mContext, this, handler);
}
ECode WifiServiceImpl::WifiStateMachineHandler::HandleMessage(
/* [in] */ IMessage* msg)
{
Int32 what;
msg->GetWhat(&what);
switch (what) {
case IAsyncChannel::CMD_CHANNEL_HALF_CONNECTED: {
Int32 arg1;
msg->GetArg1(&arg1);
if (arg1 == IAsyncChannel::STATUS_SUCCESSFUL) {
mOwner->mWifiStateMachineChannel = mWsmChannel;
} else {
Slogger::E(TAG, "WifiStateMachine connection failure, error=%d", arg1);
mOwner->mWifiStateMachineChannel = NULL;
}
break;
}
case IAsyncChannel::CMD_CHANNEL_DISCONNECTED: {
Int32 arg1;
msg->GetArg1(&arg1);
Slogger::E(TAG, "WifiStateMachine channel lost, msg.arg1 =%d", arg1);
mOwner->mWifiStateMachineChannel = NULL;
//Re-establish connection to state machine
AutoPtr<IHandler> handler;
mOwner->mWifiStateMachine->GetHandler((IHandler**)&handler);
mWsmChannel->Connect(mOwner->mContext, this, handler);
break;
}
default: {
Slogger::D(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=");// + msg);
break;
}
}
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::InnerBroadcastReceiver1
//=====================================================================
WifiServiceImpl::InnerBroadcastReceiver1::InnerBroadcastReceiver1(
/* [in] */ WifiServiceImpl* owner)
: mOwner(owner)
{
}
ECode WifiServiceImpl::InnerBroadcastReceiver1::OnReceive(
/* [in] */ IContext* context,
/* [in] */ IIntent* intent)
{
Boolean result;
if (mOwner->mSettingsStore->HandleAirplaneModeToggled(&result), result) {
mOwner->mWifiController->SendMessage(WifiController::CMD_AIRPLANE_TOGGLED);
}
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::BatchedScanRequest
//=====================================================================
WifiServiceImpl::BatchedScanRequest::BatchedScanRequest(
/* [in] */ WifiServiceImpl* owner,
/* [in] */ IBatchedScanSettings* settings,
/* [in] */ IBinder* binder,
/* [in] */ IWorkSource* ws)
: DeathRecipient(owner, 0, String(NULL), binder, NULL)
{
this->settings = settings;
uid = Binder::GetCallingUid();
pid = Binder::GetCallingPid();
workSource = ws;
}
ECode WifiServiceImpl::BatchedScanRequest::ProxyDied()
{
mOwner->StopBatchedScan(settings, uid, pid);
return NOERROR;
}
ECode WifiServiceImpl::BatchedScanRequest::ToString(
/* [out] */ String* result)
{
VALIDATE_NOT_NULL(result);
*result = String("BatchedScanRequest{settings=TODO") + /*settings +*/ String(", binder=TODO");// + mBinder + "}";
return NOERROR;
}
ECode WifiServiceImpl::BatchedScanRequest::IsSameApp(
/* [in] */ Int32 uid,
/* [in] */ Int32 pid,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = (this->uid == uid && this->pid == pid);
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::InnerBroadcastReceiver2
//=====================================================================
WifiServiceImpl::InnerBroadcastReceiver2::InnerBroadcastReceiver2(
/* [in] */ WifiServiceImpl* owner)
: mOwner(owner)
{
}
ECode WifiServiceImpl::InnerBroadcastReceiver2::OnReceive(
/* [in] */ IContext* context,
/* [in] */ IIntent* intent)
{
String action;
intent->GetAction(&action);
if (action.Equals(IIntent::ACTION_SCREEN_ON)) {
mOwner->mWifiController->SendMessage(WifiController::CMD_SCREEN_ON);
} else if (action.Equals(IIntent::ACTION_USER_PRESENT)) {
mOwner->mWifiController->SendMessage(WifiController::CMD_USER_PRESENT);
} else if (action.Equals(IIntent::ACTION_SCREEN_OFF)) {
mOwner->mWifiController->SendMessage(WifiController::CMD_SCREEN_OFF);
} else if (action.Equals(IIntent::ACTION_BATTERY_CHANGED)) {
Int32 pluggedType;
intent->GetInt32Extra(String("plugged"), 0, &pluggedType);
mOwner->mWifiController->SendMessage(WifiController::CMD_BATTERY_CHANGED, pluggedType, 0, NULL);
} else if (action.Equals(IBluetoothAdapter::ACTION_CONNECTION_STATE_CHANGED)) {
Int32 state;
intent->GetInt32Extra(IBluetoothAdapter::EXTRA_CONNECTION_STATE,
IBluetoothAdapter::STATE_DISCONNECTED, &state);
mOwner->mWifiStateMachine->SendBluetoothAdapterStateChange(state);
} else if (action.Equals(ITelephonyIntents::ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
Boolean emergencyMode;
intent->GetBooleanExtra(String("phoneinECMState"), FALSE, &emergencyMode);
mOwner->mWifiController->SendMessage(WifiController::CMD_EMERGENCY_MODE_CHANGED, emergencyMode ? 1 : 0, 0);
} else if (action.Equals(IWifiManager::WIFI_AP_STATE_CHANGED_ACTION)) {
Int32 wifiApState;
intent->GetInt32Extra(IWifiManager::EXTRA_WIFI_AP_STATE,
IWifiManager::WIFI_AP_STATE_FAILED, &wifiApState);
Slogger::D(TAG, "wifiApState=%d", wifiApState);
/*
* If start SoftAp fails, WifiStateMachine would transition to InitialState,
* but WifiController is left stuck in ApEnabledState, which in turn
* fails to turn on WLAN again.
*
* Register WifiService to receive WIFI_AP_STATE_CHANGED_ACTION intent
* from WifiStateMachine, and if wifiApState is failed, inform WifiController
* to transtion to ApStaDisabledState.
*/
if (wifiApState == IWifiManager::WIFI_AP_STATE_FAILED) {
mOwner->SetWifiApEnabled(NULL, FALSE);
}
}
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::InnerContentObserver1
//=====================================================================
ECode WifiServiceImpl::InnerContentObserver1::constructor(
/* [in] */ WifiServiceImpl* owner)
{
mOwner = owner;
return ContentObserver::constructor();
}
ECode WifiServiceImpl::InnerContentObserver1::OnChange(
/* [in] */ Boolean selfChange)
{
mOwner->mSettingsStore->HandleWifiScanAlwaysAvailableToggled();
mOwner->mWifiController->SendMessage(WifiController::CMD_SCAN_ALWAYS_MODE_CHANGED);
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::WifiLock
//=====================================================================
WifiServiceImpl::WifiLock::WifiLock(
/* [in] */ WifiServiceImpl* owner,
/* [in] */ Int32 lockMode,
/* [in] */ const String& tag,
/* [in] */ IBinder* binder,
/* [in] */ IWorkSource* ws)
: DeathRecipient(owner, lockMode, tag, binder, ws)
{
}
ECode WifiServiceImpl::WifiLock::ProxyDied()
{
{
AutoLock lock(mOwner->mLocks);
mOwner->ReleaseWifiLockLocked(mBinder);
}
return NOERROR;
}
ECode WifiServiceImpl::WifiLock::ToString(
/* [out] */ String* result)
{
VALIDATE_NOT_NULL(result);
*result = String("WifiLock{") + mTag + String(" type=") + StringUtils::ToString(mMode) + String(" binder=TODO ");// + mBinder + "}";
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::DeathRecipient
//=====================================================================
CAR_INTERFACE_IMPL(WifiServiceImpl::DeathRecipient, Object, IProxyDeathRecipient)
WifiServiceImpl::DeathRecipient::DeathRecipient(
/* [in] */ WifiServiceImpl* owner,
/* [in] */ Int32 mode,
/* [in] */ const String& tag,
/* [in] */ IBinder* binder,
/* [in] */ IWorkSource* ws)
: mOwner(owner)
{
mTag = tag;
mMode = mode;
mBinder = binder;
mWorkSource = ws;
//try {
AutoPtr<IProxy> proxy = (IProxy*)mBinder->Probe(EIID_IProxy);//IProxy::Probe(mBinder);
if (proxy != NULL) {
proxy->LinkToDeath(this, 0);
// //if (FAILED(ec))
// // ProxyDied();
}
//} catch (RemoteException e) {
//binderDied();
//}
}
ECode WifiServiceImpl::DeathRecipient::UnlinkDeathRecipient()
{
AutoPtr<IProxy> proxy = (IProxy*)mBinder->Probe(EIID_IProxy);//IProxy::Probe(mBinder);
if (proxy != NULL) {
Boolean b;
proxy->UnlinkToDeath(this, 0, &b);
}
return NOERROR;
}
//=====================================================================
// WifiServiceImpl::Multicaster
//=====================================================================
WifiServiceImpl::Multicaster::Multicaster(
/* [in] */ WifiServiceImpl* owner,
/* [in] */ const String& tag,
/* [in] */ IBinder* binder)
: DeathRecipient(owner, 0, tag, binder, NULL)
{
mMode = Binder::GetCallingUid();
}
ECode WifiServiceImpl::Multicaster::ProxyDied()
{
Slogger::E(TAG, "Multicaster binderDied");
{
AutoLock lock(mOwner->mMulticasters);
Int32 i;
mOwner->mMulticasters->IndexOf(TO_IINTERFACE(this), &i);
if (i != -1) {
mOwner->RemoveMulticasterLocked(i, mMode);
}
}
return NOERROR;
}
ECode WifiServiceImpl::Multicaster::ToString(
/* [out] */ String* result)
{
VALIDATE_NOT_NULL(result);
*result = String("Multicaster{") + mTag + String(" binder=TOOD");// + mBinder + "}";
return NOERROR;
}
ECode WifiServiceImpl::Multicaster::GetUid(
/* [out] */ Int32* result)
{
VALIDATE_NOT_NULL(result);
*result = mMode;
return NOERROR;
}
//=====================================================================
// WifiServiceImpl
//=====================================================================
const String WifiServiceImpl::TAG("WifiService");
const Boolean WifiServiceImpl::DBG = true;
CAR_INTERFACE_IMPL_2(WifiServiceImpl, Object, IIWifiManager, IBinder);
WifiServiceImpl::WifiServiceImpl()
{
CArrayList::New((IList**)&mMulticasters);
CArrayList::New((IList**)&mBatchedScanners);
mLocks = new LockList(this);
}
ECode WifiServiceImpl::constructor(
/* [in] */ IContext* context)
{
mContext = context;
AutoPtr<ISystemProperties> syspro;
CSystemProperties::AcquireSingleton((ISystemProperties**)&syspro);
syspro->Get(String("wifi.interface"), String("wlan0"), &mInterfaceName);
mTrafficPoller = new WifiTrafficPoller(mContext, mInterfaceName);
mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName, mTrafficPoller);
mWifiStateMachine->EnableRssiPolling(TRUE);
mBatteryStats = BatteryStatsService::GetService();
AutoPtr<IInterface> appOpsObj;
mContext->GetSystemService(IContext::APP_OPS_SERVICE, (IInterface**)&appOpsObj);
mAppOps = IAppOpsManager::Probe(appOpsObj);
mNotificationController = new WifiNotificationController(mContext, mWifiStateMachine);
mSettingsStore = new WifiSettingsStore(mContext);
AutoPtr<IHandlerThread> wifiThread;
CHandlerThread::New(String("WifiService"), (IHandlerThread**)&wifiThread);
IThread::Probe(wifiThread)->Start();
AutoPtr<ILooper> looper;
wifiThread->GetLooper((ILooper**)&looper);
mClientHandler = new ClientHandler(this, looper);
mWifiStateMachineHandler = new WifiStateMachineHandler(this, looper);
mWifiController = new WifiController(mContext, this, looper);
AutoPtr<IResources> resources;
mContext->GetResources((IResources**)&resources);
resources->GetBoolean(R::bool_::config_wifi_batched_scan_supported, &mBatchedScanSupported);
return NOERROR;
}
ECode WifiServiceImpl::CheckAndStartWifi()
{
/* Check if wi-fi needs to be enabled */
Boolean wifiEnabled;
mSettingsStore->IsWifiToggleEnabled(&wifiEnabled);
Slogger::I(TAG, "WifiService starting up with Wi-Fi %s", (wifiEnabled ? "enabled" : "disabled"));
RegisterForScanModeChange();
AutoPtr<IBroadcastReceiver> receiver = new InnerBroadcastReceiver1(this);
AutoPtr<IIntentFilter> intentFilter;
CIntentFilter::New(IIntent::ACTION_AIRPLANE_MODE_CHANGED, (IIntentFilter**)&intentFilter);
AutoPtr<IIntent> intent;
mContext->RegisterReceiver(receiver, intentFilter, (IIntent**)&intent);
// Adding optimizations of only receiving broadcasts when wifi is enabled
// can result in race conditions when apps toggle wifi in the background
// without active user involvement. Always receive broadcasts.
RegisterForBroadcasts();
mWifiController->Start();
mIsControllerStarted = TRUE;
// If we are already disabled (could be due to airplane mode), avoid changing persist
// state here
Boolean bTemp;
if (wifiEnabled) SetWifiEnabled(wifiEnabled, &bTemp);
AutoPtr<IMessenger> messenger;
mWifiStateMachine->GetMessenger((IMessenger**)&messenger);
mWifiWatchdogStateMachine = WifiWatchdogStateMachine::MakeWifiWatchdogStateMachine(mContext, messenger);
return NOERROR;
}
ECode WifiServiceImpl::PingSupplicant(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
if (mWifiStateMachineChannel != NULL) {
mWifiStateMachine->SyncPingSupplicant(mWifiStateMachineChannel, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = FALSE;
}
return NOERROR;
}
ECode WifiServiceImpl::GetChannelList(
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
if (mWifiStateMachineChannel != NULL) {
mWifiStateMachine->SyncGetChannelList(mWifiStateMachineChannel, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = NULL;
}
return NOERROR;
}
ECode WifiServiceImpl::StartScan(
/* [in] */ IScanSettings* settings,
/* [in] */ IWorkSource* workSource)
{
AutoPtr<IScanSettings> scanSettings = settings;
EnforceChangePermission();
if (settings != NULL) {
// TODO: should be removed once the startCustomizedScan API is opened up
mContext->EnforceCallingOrSelfPermission(Manifest::permission::LOCATION_HARDWARE,
String("LocationHardware"));
scanSettings = NULL;
CScanSettings::New(settings, (IScanSettings**)&scanSettings);
Boolean isValid;
if (scanSettings->IsValid(&isValid), !isValid) {
Slogger::E(TAG, "invalid scan setting");
return NOERROR;
}
}
if (workSource != NULL) {
EnforceWorkSourcePermission();
// WifiManager currently doesn't use names, so need to clear names out of the
// supplied WorkSource to allow future WorkSource combining.
workSource->ClearNames();
}
Int32 uid = Binder::GetCallingUid();
mWifiStateMachine->StartScan(uid, scanRequestCounter++, scanSettings, workSource);
return NOERROR;
}
ECode WifiServiceImpl::IsBatchedScanSupported(
/* [out] */ Boolean* result)
{
*result = mBatchedScanSupported;
return NOERROR;
}
ECode WifiServiceImpl::PollBatchedScan()
{
EnforceChangePermission();
if (mBatchedScanSupported == FALSE) return NOERROR;
return mWifiStateMachine->RequestBatchedScanPoll();
}
ECode WifiServiceImpl::GetWpsNfcConfigurationToken(
/* [in] */ Int32 netId,
/* [out] */ String* result)
{
VALIDATE_NOT_NULL(result);
EnforceConnectivityInternalPermission();
return mWifiStateMachine->SyncGetWpsNfcConfigurationToken(netId, result);
}
ECode WifiServiceImpl::RequestBatchedScan(
/* [in] */ IBatchedScanSettings* requested,
/* [in] */ IBinder* binder,
/* [in] */ IWorkSource* workSource,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceChangePermission();
if (workSource != NULL) {
EnforceWorkSourcePermission();
// WifiManager currently doesn't use names, so need to clear names out of the
// supplied WorkSource to allow future WorkSource combining.
workSource->ClearNames();
}
if (mBatchedScanSupported == FALSE) {
*result = FALSE;
return NOERROR;
}
AutoPtr<IBatchedScanSettings> batchedScanSettings;
CBatchedScanSettings::New(requested, (IBatchedScanSettings**)&batchedScanSettings);
Boolean isInvalid;
if (batchedScanSettings->IsInvalid(&isInvalid), isInvalid) {
*result = FALSE;
return NOERROR;
}
AutoPtr<BatchedScanRequest> r = new BatchedScanRequest(this, batchedScanSettings, binder, workSource);
{ AutoLock syncLock(mBatchedScanners);
mBatchedScanners->Add(TO_IINTERFACE(r));
ResolveBatchedScannersLocked();
}
*result = TRUE;
return NOERROR;
}
ECode WifiServiceImpl::GetBatchedScanResults(
/* [in] */ const String& callingPackage,
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
if (mBatchedScanSupported == FALSE) {
CArrayList::New(result);
return NOERROR;
}
Int32 uid = Binder::GetCallingUid();
Int32 userId = UserHandle::GetCallingUserId();
Int64 ident = Binder::ClearCallingIdentity();
//try {
Int32 noteOp;
if ((mAppOps->NoteOp(IAppOpsManager::OP_WIFI_SCAN, uid, callingPackage, ¬eOp), noteOp)
!= IAppOpsManager::MODE_ALLOWED) {
CArrayList::New(result);
return NOERROR;
}
if (!IsCurrentProfile(userId)) {
CArrayList::New(result);
return NOERROR;
}
mWifiStateMachine->SyncGetBatchedScanResultsList(result);
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
return NOERROR;
}
ECode WifiServiceImpl::StopBatchedScan(
/* [in] */ IBatchedScanSettings* settings)
{
EnforceChangePermission();
if (mBatchedScanSupported == FALSE) return NOERROR;
Int32 uid = Binder::GetCallingUid();
Int32 pid = Binder::GetCallingPid();
StopBatchedScan(settings, uid, pid);
return NOERROR;
}
// synchronized
ECode WifiServiceImpl::SetWifiEnabled(
/* [in] */ Boolean enable,
/* [out] */ Boolean* result)
{
AutoLock lock(this);
VALIDATE_NOT_NULL(result);
EnforceChangePermission();
Int32 uid = Binder::GetCallingUid();
Int32 pid = Binder::GetCallingPid();
Slogger::D(TAG, "setWifiEnabled: %d, pid = %d, uid = %d", enable, pid, uid);
if (DBG) {
Slogger::E(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
}
/*
* Caller might not have WRITE_SECURE_SETTINGS,
* only CHANGE_WIFI_STATE is enforced
*/
Int64 ident = Binder::ClearCallingIdentity();
//try {
Boolean bTemp;
if (!(mSettingsStore->HandleWifiToggled(enable, &bTemp), bTemp)) {
// Nothing to do if wifi cannot be toggled
*result = TRUE;
return NOERROR;
}
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
if (!mIsControllerStarted) {
Slogger::E(TAG,"WifiController is not yet started, abort setWifiEnabled");
*result = FALSE;
return NOERROR;
}
mWifiController->SendMessage(WifiController::CMD_WIFI_TOGGLED);
*result = TRUE;
return NOERROR;
}
ECode WifiServiceImpl::GetWifiEnabledState(
/* [out] */ Int32* result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
return mWifiStateMachine->SyncGetWifiState(result);
}
ECode WifiServiceImpl::SetWifiApEnabled(
/* [in] */ IWifiConfiguration* wifiConfig,
/* [in] */ Boolean enabled)
{
EnforceChangePermission();
AutoPtr<IConnectivityManagerHelper> cmHelper;
CConnectivityManagerHelper::AcquireSingleton((IConnectivityManagerHelper**)&cmHelper);
cmHelper->EnforceTetherChangePermission(mContext);
AutoPtr<IUserManager> um;
AutoPtr<IUserManagerHelper> umHelper;
CUserManagerHelper::AcquireSingleton((IUserManagerHelper**)&umHelper);
umHelper->Get(mContext, (IUserManager**)&um);
Boolean restriction;
if (um->HasUserRestriction(IUserManager::DISALLOW_CONFIG_TETHERING, &restriction), restriction) {
//throw new SecurityException("DISALLOW_CONFIG_TETHERING is enabled for this user.");
Slogger::E(TAG, "DISALLOW_CONFIG_TETHERING is enabled for this user.");
return E_SECURITY_EXCEPTION;
}
// null wifiConfig is a meaningful input for CMD_SET_AP
Boolean isValid;
if (wifiConfig == NULL || (wifiConfig->IsValid(&isValid), isValid)) {
AutoPtr<IMessage> msg;
mWifiController->ObtainMessage(WifiController::CMD_SET_AP, enabled ? 1 : 0, 0, TO_IINTERFACE(wifiConfig), (IMessage**)&msg);
msg->SendToTarget();
} else {
Slogger::E(TAG, "Invalid WifiConfiguration");
}
return NOERROR;
}
ECode WifiServiceImpl::GetWifiApEnabledState(
/* [out] */ Int32* result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
return mWifiStateMachine->SyncGetWifiApState(result);
}
ECode WifiServiceImpl::GetWifiApConfiguration(
/* [out] */ IWifiConfiguration** result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
return mWifiStateMachine->SyncGetWifiApConfiguration(result);
}
ECode WifiServiceImpl::SetWifiApConfiguration(
/* [in] */ IWifiConfiguration* wifiConfig)
{
EnforceChangePermission();
if (wifiConfig == NULL)
return NOERROR;
Boolean isValid;
if (wifiConfig->IsValid(&isValid), isValid) {
return mWifiStateMachine->SetWifiApConfiguration(wifiConfig);
} else {
Slogger::E(TAG, "Invalid WifiConfiguration");
}
return NOERROR;
}
ECode WifiServiceImpl::IsScanAlwaysAvailable(
/* [out] */ Boolean* result)
{
EnforceAccessPermission();
return mSettingsStore->IsScanAlwaysAvailable(result);
}
ECode WifiServiceImpl::Disconnect()
{
EnforceChangePermission();
return mWifiStateMachine->DisconnectCommand();
}
ECode WifiServiceImpl::Reconnect()
{
EnforceChangePermission();
return mWifiStateMachine->ReconnectCommand();
}
ECode WifiServiceImpl::Reassociate()
{
EnforceChangePermission();
return mWifiStateMachine->ReassociateCommand();
}
ECode WifiServiceImpl::GetSupportedFeatures(
/* [out] */ Int32* result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncGetSupportedFeatures(mWifiStateMachineChannel, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = 0;
}
return NOERROR;
}
ECode WifiServiceImpl::ReportActivityInfo(
/* [out] */ IWifiActivityEnergyInfo** result)
{
EnforceAccessPermission();
AutoPtr<IWifiLinkLayerStats> stats;
AutoPtr<IWifiActivityEnergyInfo> energyInfo;
if (mWifiStateMachineChannel != NULL) {
mWifiStateMachine->SyncGetLinkLayerStats(mWifiStateMachineChannel, (IWifiLinkLayerStats**)&stats);
if (stats != NULL) {
// Convert the LinkLayerStats into EnergyActivity
Int32 on_time, tx_time, rx_time;
stats->GetOn_time(&on_time);
stats->GetTx_time(&tx_time);
stats->GetRx_time(&rx_time);
CWifiActivityEnergyInfo::New(
IWifiActivityEnergyInfo::STACK_STATE_STATE_IDLE, tx_time,
rx_time, on_time - tx_time - rx_time,
0 /* TBD */, (IWifiActivityEnergyInfo**)&energyInfo);
}
*result = energyInfo;
REFCOUNT_ADD(*result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = NULL;
}
return NOERROR;
}
ECode WifiServiceImpl::GetConfiguredNetworks(
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result)
EnforceAccessPermission();
if (mWifiStateMachineChannel != NULL) {
Int32 uid = Binder::GetCallingUid();
return mWifiStateMachine->SyncGetConfiguredNetworks(uid,
mWifiStateMachineChannel, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = NULL;
}
return NOERROR;
}
ECode WifiServiceImpl::GetPrivilegedConfiguredNetworks(
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result);
EnforceReadCredentialPermission();
EnforceAccessPermission();
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncGetPrivilegedConfiguredNetwork(mWifiStateMachineChannel, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = NULL;
return NOERROR;
}
return NOERROR;
}
ECode WifiServiceImpl::AddOrUpdateNetwork(
/* [in] */ IWifiConfiguration* config,
/* [out] */ Int32* result)
{
VALIDATE_NOT_NULL(result);
EnforceChangePermission();
Boolean isValid;
if (config->IsValid(&isValid), isValid) {
//TODO: pass the Uid the WifiStateMachine as a message parameter
Int32 uid = Binder::GetCallingUid();
String SSID;
config->GetSSID(&SSID);
Int32 networkId;
config->GetNetworkId(&networkId);
Slogger::E("WifiServiceImpl", "addOrUpdateNetwork uid = %d, SSID=%s, nid=%d", uid,SSID.string(), networkId);
if (networkId == IWifiConfiguration::INVALID_NETWORK_ID) {
config->SetCreatorUid(uid);
} else {
config->SetLastUpdateUid(uid);
}
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncAddOrUpdateNetwork(mWifiStateMachineChannel, config, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = -1;
}
} else {
Slogger::E(TAG, "bad network configuration");
*result = -1;
}
return NOERROR;
}
ECode WifiServiceImpl::RemoveNetwork(
/* [in] */ Int32 netId,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceChangePermission();
Int32 uid = Binder::GetCallingUid();
if (!IsOwner(uid)) {
Slogger::E(TAG, "Remove is not authorized for user");
*result = FALSE;
return NOERROR;
}
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncRemoveNetwork(mWifiStateMachineChannel, netId, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = FALSE;
}
return NOERROR;
}
ECode WifiServiceImpl::EnableNetwork(
/* [in] */ Int32 netId,
/* [in] */ Boolean disableOthers,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceChangePermission();
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncEnableNetwork(mWifiStateMachineChannel, netId,
disableOthers, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
return false;
}
return NOERROR;
}
ECode WifiServiceImpl::DisableNetwork(
/* [in] */ Int32 netId,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceChangePermission();
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncDisableNetwork(mWifiStateMachineChannel, netId, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = FALSE;
}
return NOERROR;
}
ECode WifiServiceImpl::GetConnectionInfo(
/* [out] */ IWifiInfo** result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
/*
* Make sure we have the latest information, by sending
* a status request to the supplicant.
*/
return mWifiStateMachine->SyncRequestConnectionInfo(result);
}
ECode WifiServiceImpl::GetScanResults(
/* [in] */ const String& callingPackage,
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result);
*result = NULL;
EnforceAccessPermission();
Int32 userId = UserHandle::GetCallingUserId();
Int32 uid = Binder::GetCallingUid();
Int64 ident = Binder::ClearCallingIdentity();
//try {
Int32 noteOp;
if ((mAppOps->NoteOp(IAppOpsManager::OP_WIFI_SCAN, uid, callingPackage, ¬eOp), noteOp)
!= IAppOpsManager::MODE_ALLOWED) {
CParcelableList::New(result);
Binder::RestoreCallingIdentity(ident);
return NOERROR;
}
if (!IsCurrentProfile(userId)) {
CParcelableList::New(result);
Binder::RestoreCallingIdentity(ident);
return NOERROR;
}
mWifiStateMachine->SyncGetScanResultsList(result);
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
return NOERROR;
}
ECode WifiServiceImpl::SaveConfiguration(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceChangePermission();
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncSaveConfig(mWifiStateMachineChannel, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = FALSE;
return NOERROR;
}
return NOERROR;
}
ECode WifiServiceImpl::SetCountryCode(
/* [in] */ const String& countryCode,
/* [in] */ Boolean persist)
{
Slogger::I(TAG, "WifiService trying to set country code to %s with persist set to %d", countryCode.string(), persist);
EnforceConnectivityInternalPermission();
Int64 token = Binder::ClearCallingIdentity();
//try {
mWifiStateMachine->SetCountryCode(countryCode, persist);
//} finally {
Binder::RestoreCallingIdentity(token);
//}
return NOERROR;
}
ECode WifiServiceImpl::SetFrequencyBand(
/* [in] */ Int32 band,
/* [in] */ Boolean persist)
{
EnforceChangePermission();
Boolean bTemp;
if (!(IsDualBandSupported(&bTemp), bTemp)) return NOERROR;
Slogger::I(TAG, "WifiService trying to set frequency band to %d with persist set to %d", band, persist);
Int64 token = Binder::ClearCallingIdentity();
//try {
mWifiStateMachine->SetFrequencyBand(band, persist);
//} finally {
Binder::RestoreCallingIdentity(token);
//}
return NOERROR;
}
ECode WifiServiceImpl::GetFrequencyBand(
/* [out] */ Int32* result)
{
EnforceAccessPermission();
return mWifiStateMachine->GetFrequencyBand(result);
}
ECode WifiServiceImpl::IsDualBandSupported(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
//TODO: Should move towards adding a driver API that checks at runtime
AutoPtr<IResources> resources;
mContext->GetResources((IResources**)&resources);
resources->GetBoolean(
R::bool_::config_wifi_dual_band_support, result);
return NOERROR;
}
ECode WifiServiceImpl::IsIbssSupported(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
if (mWifiStateMachineChannel != NULL) {
Int32 supported;
*result = ((mWifiStateMachine->SyncIsIbssSupported(mWifiStateMachineChannel, &supported), supported) == 1);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = FALSE;
}
return NOERROR;
}
ECode WifiServiceImpl::GetDhcpInfo(
/* [out] */ IDhcpInfo** result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
AutoPtr<IDhcpResults> dhcpResults;
mWifiStateMachine->SyncGetDhcpResults((IDhcpResults**)&dhcpResults);
AutoPtr<IDhcpInfo> info;
CDhcpInfo::New((IDhcpInfo**)&info);
AutoPtr<ILinkAddress> ipAddress;
IStaticIpConfiguration::Probe(dhcpResults)->GetIpAddress((ILinkAddress**)&ipAddress);
AutoPtr<INetworkUtils> networkUtils;
CNetworkUtils::AcquireSingleton((INetworkUtils**)&networkUtils);
if (ipAddress != NULL) {
AutoPtr<IInetAddress> address;
ipAddress->GetAddress((IInetAddress**)&address);
IInet4Address* ip4 = IInet4Address::Probe(address);
if(ip4 != NULL) {
Int32 intInetAddress;
networkUtils->InetAddressToInt(ip4, &intInetAddress);
info->SetIpAddress(intInetAddress);
Int32 preFixLength;
ipAddress->GetNetworkPrefixLength(&preFixLength);
Int32 netmaskInt;
networkUtils->PrefixLengthToNetmaskInt(preFixLength, &netmaskInt);
info->SetNetmask(netmaskInt);
}
}
AutoPtr<IInetAddress> gatewayAddress;
IStaticIpConfiguration::Probe(dhcpResults)->GetGateway((IInetAddress**)&gatewayAddress);
if (gatewayAddress != NULL) {
Int32 gateway;
networkUtils->InetAddressToInt(IInet4Address::Probe(gatewayAddress), &gateway);
info->SetGateway(gateway);
}
Int32 dnsFound = 0;
AutoPtr<IArrayList> servers;
IStaticIpConfiguration::Probe(dhcpResults)->GetDnsServers((IArrayList**)&servers);
Int32 size;
servers->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
servers->Get(i, (IInterface**)&obj);
IInetAddress* dns = IInetAddress::Probe(obj);
IInet4Address* ip4 = IInet4Address::Probe(dns);
if (ip4 != NULL) {
if (dnsFound == 0) {
Int32 dns1;
networkUtils->InetAddressToInt(ip4, &dns1);
info->SetDns1(dns1);
} else {
Int32 dns2;
networkUtils->InetAddressToInt(ip4, &dns2);
info->SetDns2(dns2);
}
if (++dnsFound > 1) break;
}
}
AutoPtr<IInetAddress> serverAddress;
dhcpResults->GetServerAddress((IInetAddress**)&serverAddress);
IInet4Address* ip4SA = IInet4Address::Probe(serverAddress);
if (ip4SA != NULL) {
Int32 intSA;
networkUtils->InetAddressToInt(ip4SA, &intSA);
info->SetServerAddress(intSA);
}
Int32 duration;
dhcpResults->GetLeaseDuration(&duration);
info->SetLeaseDuration(duration);;
*result = info;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode WifiServiceImpl::StartWifi()
{
EnforceConnectivityInternalPermission();
/* TODO: may be add permissions for access only to connectivity service
* TODO: if a start issued, keep wifi alive until a stop issued irrespective
* of WifiLock & device idle status unless wifi enabled status is toggled
*/
mWifiStateMachine->SetDriverStart(TRUE);
mWifiStateMachine->ReconnectCommand();
return NOERROR;
}
ECode WifiServiceImpl::StopWifi()
{
EnforceConnectivityInternalPermission();
/*
* TODO: if a stop is issued, wifi is brought up only by startWifi
* unless wifi enabled status is toggled
*/
mWifiStateMachine->SetDriverStart(FALSE);
return NOERROR;
}
ECode WifiServiceImpl::AddToBlacklist(
/* [in] */ const String& bssid)
{
EnforceChangePermission();
mWifiStateMachine->AddToBlacklist(bssid);
return NOERROR;
}
ECode WifiServiceImpl::ClearBlacklist()
{
EnforceChangePermission();
mWifiStateMachine->ClearBlacklist();
return NOERROR;
}
ECode WifiServiceImpl::EnableTdls(
/* [in] */ const String& remoteAddress,
/* [in] */ Boolean enable)
{
if (remoteAddress.IsNull()) {
//throw new IllegalArgumentException("remoteAddress cannot be null");
Slogger::E(TAG, "remoteAddress cannot be null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<TdlsTaskParams> params = new TdlsTaskParams();
params->remoteIpAddress = remoteAddress;
params->enable = enable;
AutoPtr<TdlsTask> tdlsTask = new TdlsTask(this);
AutoPtr<ArrayOf<IInterface*> > arrayParams = ArrayOf<IInterface*>::Alloc(1);
arrayParams->Set(0, TO_IINTERFACE(params));
tdlsTask->Execute(arrayParams);
return NOERROR;
}
ECode WifiServiceImpl::EnableTdlsWithMacAddress(
/* [in] */ const String& remoteMacAddress,
/* [in] */ Boolean enable)
{
if (remoteMacAddress.IsNull()) {
//throw new IllegalArgumentException("remoteMacAddress cannot be null");
Slogger::E(TAG, "remoteMacAddress cannot be null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
return mWifiStateMachine->EnableTdls(remoteMacAddress, enable);
}
ECode WifiServiceImpl::GetWifiServiceMessenger(
/* [out] */ IMessenger** result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
EnforceChangePermission();
AutoPtr<IMessenger> messenger;
CMessenger::New(mClientHandler, (IMessenger**)&messenger);
*result = messenger;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode WifiServiceImpl::GetConfigFile(
/* [out] */ String* result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
return mWifiStateMachine->GetConfigFile(result);
}
ECode WifiServiceImpl::EnforceWakeSourcePermission(
/* [in] */ Int32 uid,
/* [in] */ Int32 pid)
{
if (uid == Process::MyUid()) {
return NOERROR;
}
return mContext->EnforcePermission(Manifest::permission::UPDATE_DEVICE_STATS, pid, uid, String(NULL));
}
ECode WifiServiceImpl::AcquireWifiLock(
/* [in] */ IBinder* binder,
/* [in] */ Int32 lockMode,
/* [in] */ const String& tag,
/* [in] */ IWorkSource* _ws,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
AutoPtr<IWorkSource> ws = _ws;
mContext->EnforceCallingOrSelfPermission(Manifest::permission::WAKE_LOCK, String(NULL));
if (lockMode != IWifiManager::WIFI_MODE_FULL &&
lockMode != IWifiManager::WIFI_MODE_SCAN_ONLY &&
lockMode != IWifiManager::WIFI_MODE_FULL_HIGH_PERF) {
Slogger::E(TAG, "Illegal argument, lockMode= %d", lockMode);
*result = FALSE;
if (DBG) {
//throw new IllegalArgumentException("lockMode=" + lockMode);
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
return NOERROR;
}
if (ws != NULL) {
Int32 size;
ws->GetSize(&size);
if(size == 0) {
ws = NULL;
}
}
Int32 uid = Binder::GetCallingUid();
Int32 pid = Binder::GetCallingPid();
if (ws != NULL) {
EnforceWakeSourcePermission(uid, pid);
}
if (ws == NULL) {
CWorkSource::New(uid, (IWorkSource**)&ws);
}
AutoPtr<WifiLock> wifiLock = new WifiLock(this, lockMode, tag, binder, ws);
{ AutoLock syncLock(mLocks);
return AcquireWifiLockLocked(wifiLock);
}
return NOERROR;
}
ECode WifiServiceImpl::UpdateWifiLockWorkSource(
/* [in] */ IBinder* lock,
/* [in] */ IWorkSource* ws)
{
Int32 uid = Binder::GetCallingUid();
Int32 pid = Binder::GetCallingPid();
if (ws != NULL) {
Int32 size;
ws->GetSize(&size);
if(size == 0) {
ws = NULL;
}
}
if (ws != NULL) {
EnforceWakeSourcePermission(uid, pid);
}
Int64 ident = Binder::ClearCallingIdentity();
//try {
{ AutoLock syncLock(mLocks);
Int32 index = mLocks->FindLockByBinder(lock);
if (index < 0) {
//throw new IllegalArgumentException("Wifi lock not active");
Slogger::E(TAG, "Wifi lock not active");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<IInterface> obj;
mLocks->mList->Get(index, (IInterface**)&obj);
AutoPtr<WifiLock> wl = (WifiLock*)(IObject::Probe(obj));
NoteReleaseWifiLock(wl);
AutoPtr<IWorkSource> nws;
(ws != NULL) ? CWorkSource::New(ws, (IWorkSource**)&nws): CWorkSource::New(uid, (IWorkSource**)&nws);
wl->mWorkSource = nws;
NoteAcquireWifiLock(wl);
}
//} catch (RemoteException e) {
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
return NOERROR;
}
ECode WifiServiceImpl::ReleaseWifiLock(
/* [in] */ IBinder* lock,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
mContext->EnforceCallingOrSelfPermission(Manifest::permission::WAKE_LOCK, String(NULL));
{ AutoLock syncLock(mLocks);
*result = ReleaseWifiLockLocked(lock);
}
return NOERROR;
}
ECode WifiServiceImpl::InitializeMulticastFiltering()
{
EnforceMulticastChangePermission();
{ AutoLock syncLock(mMulticasters);
// if anybody had requested filters be off, leave off
Int32 size;
mMulticasters->GetSize(&size);
if (size != 0) {
return NOERROR;
} else {
mWifiStateMachine->StartFilteringMulticastV4Packets();
}
}
return NOERROR;
}
ECode WifiServiceImpl::AcquireMulticastLock(
/* [in] */ IBinder* binder,
/* [in] */ const String& tag)
{
VALIDATE_NOT_NULL(binder);
EnforceMulticastChangePermission();
{ AutoLock syncLock(mMulticasters);
mMulticastEnabled++;
AutoPtr<Multicaster> multicaster = new Multicaster(this, tag, binder);
mMulticasters->Add(TO_IINTERFACE(multicaster));
// Note that we could call stopFilteringMulticastV4Packets only when
// our new size == 1 (first call), but this function won't
// be called often and by making the stopPacket call each
// time we're less fragile and self-healing.
mWifiStateMachine->StopFilteringMulticastV4Packets();
}
Int32 uid = Binder::GetCallingUid();
Int64 ident = Binder::ClearCallingIdentity();
//try {
mBatteryStats->NoteWifiMulticastEnabled(uid);
//} catch (RemoteException e) {
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
return NOERROR;
}
ECode WifiServiceImpl::ReleaseMulticastLock()
{
EnforceMulticastChangePermission();
Int32 uid = Binder::GetCallingUid();
{
AutoLock syncLock(mMulticasters);
mMulticastDisabled++;
Int32 size;
mMulticasters->GetSize(&size);
for (Int32 i = size - 1; i >= 0; i--) {
AutoPtr<IInterface> obj;
mMulticasters->Get(i, (IInterface**)&obj);
Multicaster* m = (Multicaster*)(IObject::Probe(obj));
if (m != NULL) {
Int32 mcUid;
if((m->GetUid(&mcUid), mcUid) == uid) {
RemoveMulticasterLocked(i, uid);
}
}
}
}
return NOERROR;
}
ECode WifiServiceImpl::IsMulticastEnabled(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
{ AutoLock syncLock(mMulticasters);
Int32 size;
mMulticasters->GetSize(&size);
*result = (size > 0);
}
return NOERROR;
}
ECode WifiServiceImpl::GetWifiMonitor(
/* [out] */ WifiMonitor** result)
{
return mWifiStateMachine->GetWifiMonitor(result);
}
ECode WifiServiceImpl::EnableVerboseLogging(
/* [in] */ Int32 verbose)
{
EnforceAccessPermission();
return mWifiStateMachine->EnableVerboseLogging(verbose);
}
ECode WifiServiceImpl::GetVerboseLoggingLevel(
/* [out] */ Int32* result)
{
EnforceAccessPermission();
return mWifiStateMachine->GetVerboseLoggingLevel(result);
}
ECode WifiServiceImpl::EnableAggressiveHandover(
/* [in] */ Int32 enabled)
{
EnforceAccessPermission();
return mWifiStateMachine->EnableAggressiveHandover(enabled);
}
ECode WifiServiceImpl::GetAggressiveHandover(
/* [out] */ Int32* result)
{
EnforceAccessPermission();
return mWifiStateMachine->GetAggressiveHandover(result);
}
ECode WifiServiceImpl::SetAllowScansWithTraffic(
/* [in] */ Int32 enabled)
{
EnforceAccessPermission();
return mWifiStateMachine->SetAllowScansWithTraffic(enabled);
}
ECode WifiServiceImpl::GetAllowScansWithTraffic(
/* [out] */ Int32* result)
{
EnforceAccessPermission();
return mWifiStateMachine->GetAllowScansWithTraffic(result);
}
ECode WifiServiceImpl::GetConnectionStatistics(
/* [out] */ IWifiConnectionStatistics** result)
{
VALIDATE_NOT_NULL(result);
EnforceAccessPermission();
EnforceReadCredentialPermission();
if (mWifiStateMachineChannel != NULL) {
return mWifiStateMachine->SyncGetConnectionStatistics(mWifiStateMachineChannel, result);
} else {
Slogger::E(TAG, "mWifiStateMachineChannel is not initialized");
*result = NULL;
return NOERROR;
}
return NOERROR;
}
void WifiServiceImpl::Dump(
/* [in] */ IFileDescriptor* fd,
/* [in] */ IPrintWriter* pw,
/* [in] */ ArrayOf<String>* args)
{
Slogger::E(TAG, "WifiServiceImpl::Dump TODO");
// ==================before translated======================
// if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
// != PackageManager.PERMISSION_GRANTED) {
// pw.println("Permission Denial: can't dump WifiService from from pid="
// + Binder.getCallingPid()
// + ", uid=" + Binder.getCallingUid());
// return;
// }
// pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
// pw.println("Stay-awake conditions: " +
// Settings.Global.getInt(mContext.getContentResolver(),
// Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0));
// pw.println("mMulticastEnabled " + mMulticastEnabled);
// pw.println("mMulticastDisabled " + mMulticastDisabled);
// mWifiController.dump(fd, pw, args);
// mSettingsStore.dump(fd, pw, args);
// mNotificationController.dump(fd, pw, args);
// mTrafficPoller.dump(fd, pw, args);
//
// pw.println("Latest scan results:");
// List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
// long nowMs = System.currentTimeMillis();
// if (scanResults != null && scanResults.size() != 0) {
// pw.println(" BSSID Frequency RSSI Age SSID " +
// " Flags");
// for (ScanResult r : scanResults) {
// long ageSec = 0;
// long ageMilli = 0;
// if (nowMs > r.seen && r.seen > 0) {
// ageSec = (nowMs - r.seen) / 1000;
// ageMilli = (nowMs - r.seen) % 1000;
// }
// String candidate = " ";
// if (r.isAutoJoinCandidate > 0) candidate = "+";
// pw.printf(" %17s %9d %5d %3d.%03d%s %-32s %s\n",
// r.BSSID,
// r.frequency,
// r.level,
// ageSec, ageMilli,
// candidate,
// r.SSID == null ? "" : r.SSID,
// r.capabilities);
// }
// }
// pw.println();
// pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
// mFullHighPerfLocksAcquired + " full high perf, " +
// mScanLocksAcquired + " scan");
// pw.println("Locks released: " + mFullLocksReleased + " full, " +
// mFullHighPerfLocksReleased + " full high perf, " +
// mScanLocksReleased + " scan");
// pw.println();
// pw.println("Locks held:");
// mLocks.dump(pw);
//
// mWifiWatchdogStateMachine.dump(fd, pw, args);
// pw.println();
// mWifiStateMachine.dump(fd, pw, args);
// pw.println();
assert(0);
}
void WifiServiceImpl::StopBatchedScan(
/* [in] */ IBatchedScanSettings* settings,
/* [in] */ Int32 uid,
/* [in] */ Int32 pid)
{
AutoPtr<IArrayList> found;
CArrayList::New((IArrayList**)&found);
{ AutoLock syncLock(mBatchedScanners);
Int32 size;
mBatchedScanners->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
mBatchedScanners->Get(i, (IInterface**)&obj);
BatchedScanRequest* r = (BatchedScanRequest*)(IObject::Probe(obj));
Boolean sameApp = FALSE;
if (r->IsSameApp(uid, pid, &sameApp), sameApp) {
Boolean equals;
if (settings == NULL || (IObject::Probe(settings)->Equals(r->settings.Get(), &equals), equals)) {
found->Add(TO_IINTERFACE(r));
if (settings != NULL) break;
}
}
}
Int32 foundSize;
found->GetSize(&foundSize);
for (Int32 i = 0; i < foundSize; ++i) {
AutoPtr<IInterface> obj;
found->Get(i, (IInterface**)&obj);
mBatchedScanners->Remove(obj);
}
if (foundSize != 0) {
ResolveBatchedScannersLocked();
}
}
}
void WifiServiceImpl::ResolveBatchedScannersLocked()
{
AutoPtr<IBatchedScanSettings> setting;
CBatchedScanSettings::New((IBatchedScanSettings**)&setting);
AutoPtr<IWorkSource> responsibleWorkSource;
Int32 responsibleUid = 0;
Double responsibleCsph = 0; // Channel Scans Per Hour
Int32 size;
if ((mBatchedScanners->GetSize(&size), size) == 0) {
mWifiStateMachine->SetBatchedScanSettings(NULL, 0, 0, NULL);
return;
}
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
mBatchedScanners->Get(i, (IInterface**)&obj);
BatchedScanRequest* r = (BatchedScanRequest*)(IObject::Probe(obj));
AutoPtr<IBatchedScanSettings> s = r->settings;
// evaluate responsibility
Int32 currentChannelCount;
Int32 currentScanInterval;
Double currentCsph;
AutoPtr<ICollection> channelSet;
s->GetChannelSet((ICollection**)&channelSet);
Boolean isEmpty;
if (channelSet == NULL || (channelSet->IsEmpty(&isEmpty), isEmpty)) {
// all channels - 11 B and 9 A channels roughly.
currentChannelCount = 9 + 11;
} else {
channelSet->GetSize(¤tChannelCount);
// these are rough est - no real need to correct for reg-domain;
Boolean contains;
if (channelSet->Contains(CoreUtils::Convert("A"), &contains), contains) currentChannelCount += (9 - 1);
if (channelSet->Contains(CoreUtils::Convert("B"), &contains), contains) currentChannelCount += (11 - 1);
}
Int32 scanIntervalSec;
s->GetScanIntervalSec(&scanIntervalSec);
if (scanIntervalSec == IBatchedScanSettings::UNSPECIFIED) {
currentScanInterval = IBatchedScanSettings::DEFAULT_INTERVAL_SEC;
} else {
currentScanInterval = scanIntervalSec;
}
currentCsph = 60 * 60 * currentChannelCount / currentScanInterval;
if (currentCsph > responsibleCsph) {
responsibleUid = r->uid;
responsibleWorkSource = r->workSource;
responsibleCsph = currentCsph;
}
Int32 maxScansPerBatch;
s->GetMaxScansPerBatch(&maxScansPerBatch);
Int32 settingsMaxScansPerBatch;
setting->GetMaxScansPerBatch(&settingsMaxScansPerBatch);
if (maxScansPerBatch != IBatchedScanSettings::UNSPECIFIED &&
maxScansPerBatch < settingsMaxScansPerBatch) {
setting->SetMaxScansPerBatch(maxScansPerBatch);
}
Int32 maxApPerScan;
s->GetMaxApPerScan(&maxApPerScan);
Int32 settingMaxApPerScan;
setting->GetMaxApPerScan(&settingMaxApPerScan);
if (maxApPerScan != IBatchedScanSettings::UNSPECIFIED &&
(settingMaxApPerScan == IBatchedScanSettings::UNSPECIFIED ||
maxApPerScan > settingMaxApPerScan)) {
setting->SetMaxApPerScan(maxApPerScan);
}
Int32 settingScanIntervalSec;
setting->GetScanIntervalSec(&settingScanIntervalSec);
if (scanIntervalSec != IBatchedScanSettings::UNSPECIFIED &&
scanIntervalSec < settingScanIntervalSec) {
setting->SetScanIntervalSec(scanIntervalSec);
}
Int32 maxApForDistance;
s->GetMaxApForDistance(&maxApForDistance);
Int32 settingMaxApForDistance;
setting->GetMaxApForDistance(&settingMaxApForDistance);
if (maxApForDistance != IBatchedScanSettings::UNSPECIFIED &&
(settingMaxApForDistance == IBatchedScanSettings::UNSPECIFIED ||
maxApForDistance > settingMaxApForDistance)) {
setting->SetMaxApForDistance(maxApForDistance);
}
Int32 channelSetSize = 0;
AutoPtr<ICollection> settingChannelSet;
setting->GetChannelSet((ICollection**)&settingChannelSet);
Int32 settingChannelSetSize = 0;
if (channelSet != NULL && (channelSet->GetSize(&channelSetSize), channelSetSize) != 0) {
if (settingChannelSet == NULL ||
(settingChannelSet->GetSize(&settingChannelSetSize), settingChannelSetSize) != 0) {
if (settingChannelSet == NULL) {
CArrayList::New((ICollection**)&settingChannelSet);
setting->SetChannelSet(settingChannelSet);
}
AutoPtr<ArrayOf<IInterface*> > array;
channelSet->ToArray((ArrayOf<IInterface*>**)&array);
for (Int32 i = 0; i < array->GetLength(); ++i) {
AutoPtr<IInterface> obj = (*array)[i];
//ICharSequence* cs = ICharSequence::Probe(obj);
//String str;
//cs->ToString(&str);
Boolean contains;
if ((settingChannelSet->Contains(obj, &contains), contains) == FALSE)
settingChannelSet->Add(obj);
}
} // else, ignore the constraint - we already use all channels
} else {
if (settingChannelSet == NULL || (settingChannelSet->GetSize(&channelSetSize), channelSetSize) != 0) {
settingChannelSet = NULL;
CArrayList::New((ICollection**)&settingChannelSet);
setting->SetChannelSet(settingChannelSet);
}
}
}
setting->Constrain();
mWifiStateMachine->SetBatchedScanSettings(setting, responsibleUid, (Int32)responsibleCsph,
responsibleWorkSource);
}
void WifiServiceImpl::EnforceAccessPermission()
{
mContext->EnforceCallingOrSelfPermission(Manifest::permission::ACCESS_WIFI_STATE, String("WifiService"));
}
void WifiServiceImpl::EnforceChangePermission()
{
mContext->EnforceCallingOrSelfPermission(Manifest::permission::CHANGE_WIFI_STATE, String("WifiService"));
}
void WifiServiceImpl::EnforceReadCredentialPermission()
{
mContext->EnforceCallingOrSelfPermission(Manifest::permission::READ_WIFI_CREDENTIAL, String("WifiService"));
}
void WifiServiceImpl::EnforceWorkSourcePermission()
{
mContext->EnforceCallingPermission(Manifest::permission::UPDATE_DEVICE_STATS, String("WifiService"));
}
void WifiServiceImpl::EnforceMulticastChangePermission()
{
mContext->EnforceCallingOrSelfPermission(
Manifest::permission::CHANGE_WIFI_MULTICAST_STATE,
String("WifiService"));
}
void WifiServiceImpl::EnforceConnectivityInternalPermission()
{
mContext->EnforceCallingOrSelfPermission(
Manifest::permission::CONNECTIVITY_INTERNAL,
String("ConnectivityService"));
}
Boolean WifiServiceImpl::IsCurrentProfile(
/* [in] */ Int32 userId)
{
AutoPtr<IActivityManagerHelper> cmHelper;
CActivityManagerHelper::AcquireSingleton((IActivityManagerHelper**)&cmHelper);
Int32 currentUser;
cmHelper->GetCurrentUser(¤tUser);
if (userId == currentUser) {
return TRUE;
}
AutoPtr<IUserManager> um;
AutoPtr<IUserManagerHelper> umHelper;
CUserManagerHelper::AcquireSingleton((IUserManagerHelper**)&umHelper);
umHelper->Get(mContext, (IUserManager**)&um);
AutoPtr<IList> profiles;//UserInfo
um->GetProfiles(currentUser, (IList**)&profiles);
Int32 size;
profiles->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
profiles->Get(i, (IInterface**)&obj);
IUserInfo* profile = IUserInfo::Probe(obj);
Int32 id;
profile->GetId(&id);
if (userId == id) {
return TRUE;
}
}
return FALSE;
}
Boolean WifiServiceImpl::IsOwner(
/* [in] */ Int32 uid)
{
Int64 ident = Binder::ClearCallingIdentity();
Int32 userId = UserHandle::GetUserId(uid);
//try {
Int32 ownerUser = IUserHandle::USER_OWNER;
if (userId == ownerUser) {
return TRUE;
}
AutoPtr<IUserManager> um;
AutoPtr<IUserManagerHelper> umHelper;
CUserManagerHelper::AcquireSingleton((IUserManagerHelper**)&umHelper);
umHelper->Get(mContext, (IUserManager**)&um);
AutoPtr<IList> profiles;//UserInfo
um->GetProfiles(ownerUser, (IList**)&profiles);
Int32 size;
profiles->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
profiles->Get(i, (IInterface**)&obj);
IUserInfo* profile = IUserInfo::Probe(obj);
Int32 id;
profile->GetId(&id);
if (userId == id) {
return TRUE;
}
}
//}
//finally {
Binder::RestoreCallingIdentity(ident);
//}
return FALSE;
}
void WifiServiceImpl::RegisterForScanModeChange()
{
AutoPtr<InnerContentObserver1> contentObserver = new InnerContentObserver1();
contentObserver->constructor(this);
AutoPtr<IContentResolver> cr;
mContext->GetContentResolver((IContentResolver**)&cr);
AutoPtr<IUri> uri;
Settings::Global::GetUriFor(ISettingsGlobal::WIFI_SCAN_ALWAYS_AVAILABLE, (IUri**)&uri);
cr->RegisterContentObserver( uri, FALSE, contentObserver);
}
void WifiServiceImpl::RegisterForBroadcasts()
{
AutoPtr<IIntentFilter> intentFilter;
CIntentFilter::New((IIntentFilter**)&intentFilter);
intentFilter->AddAction(IIntent::ACTION_SCREEN_ON);
intentFilter->AddAction(IIntent::ACTION_USER_PRESENT);
intentFilter->AddAction(IIntent::ACTION_SCREEN_OFF);
intentFilter->AddAction(IIntent::ACTION_BATTERY_CHANGED);
intentFilter->AddAction(IWifiManager::NETWORK_STATE_CHANGED_ACTION);
intentFilter->AddAction(IWifiManager::WIFI_AP_STATE_CHANGED_ACTION);
intentFilter->AddAction(IBluetoothAdapter::ACTION_CONNECTION_STATE_CHANGED);
intentFilter->AddAction(ITelephonyIntents::ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
AutoPtr<IIntent> tmp;
mContext->RegisterReceiver(mReceiver, intentFilter, (IIntent**)&tmp);
}
void WifiServiceImpl::NoteAcquireWifiLock(
/* [in] */ WifiLock* wifiLock)
{
switch(wifiLock->mMode) {
case IWifiManager::WIFI_MODE_FULL:
case IWifiManager::WIFI_MODE_FULL_HIGH_PERF:
case IWifiManager::WIFI_MODE_SCAN_ONLY:
mBatteryStats->NoteFullWifiLockAcquiredFromSource(wifiLock->mWorkSource);
break;
}
}
void WifiServiceImpl::NoteReleaseWifiLock(
/* [in] */ WifiLock* wifiLock)
{
switch(wifiLock->mMode) {
case IWifiManager::WIFI_MODE_FULL:
case IWifiManager::WIFI_MODE_FULL_HIGH_PERF:
case IWifiManager::WIFI_MODE_SCAN_ONLY:
mBatteryStats->NoteFullWifiLockReleasedFromSource(wifiLock->mWorkSource);
break;
}
}
Boolean WifiServiceImpl::AcquireWifiLockLocked(
/* [in] */ WifiLock* wifiLock)
{
if (DBG) Slogger::D(TAG, "acquireWifiLockLocked: ");// + wifiLock);
mLocks->AddLock(wifiLock);
Int64 ident = Binder::ClearCallingIdentity();
//try {
NoteAcquireWifiLock(wifiLock);
switch(wifiLock->mMode) {
case IWifiManager::WIFI_MODE_FULL:
++mFullLocksAcquired;
break;
case IWifiManager::WIFI_MODE_FULL_HIGH_PERF:
++mFullHighPerfLocksAcquired;
break;
case IWifiManager::WIFI_MODE_SCAN_ONLY:
++mScanLocksAcquired;
break;
}
mWifiController->SendMessage(WifiController::CMD_LOCKS_CHANGED);
//} catch (RemoteException e) {
// return false;
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
return TRUE;
}
Boolean WifiServiceImpl::ReleaseWifiLockLocked(
/* [in] */ IBinder* lock)
{
Boolean hadLock;
AutoPtr<WifiLock> wifiLock = mLocks->RemoveLock(lock);
if (DBG) Slogger::D(TAG, "releaseWifiLockLocked: ");// + wifiLock);
hadLock = (wifiLock != NULL);
Int64 ident = Binder::ClearCallingIdentity();
//try {
if (hadLock) {
NoteReleaseWifiLock(wifiLock);
switch(wifiLock->mMode) {
case IWifiManager::WIFI_MODE_FULL:
++mFullLocksReleased;
break;
case IWifiManager::WIFI_MODE_FULL_HIGH_PERF:
++mFullHighPerfLocksReleased;
break;
case IWifiManager::WIFI_MODE_SCAN_ONLY:
++mScanLocksReleased;
break;
}
mWifiController->SendMessage(WifiController::CMD_LOCKS_CHANGED);
}
//} catch (RemoteException e) {
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
return hadLock;
}
void WifiServiceImpl::RemoveMulticasterLocked(
/* [in] */ Int32 i,
/* [in] */ Int32 uid)
{
AutoPtr<IInterface> obj;
mMulticasters->Remove(i, (IInterface**)&obj);
AutoPtr<Multicaster> removed = (Multicaster*)(IObject::Probe(obj));
if (removed != NULL) {
removed->UnlinkDeathRecipient();
}
Int32 size;
if ((mMulticasters->GetSize(&size), size) == 0) {
mWifiStateMachine->StartFilteringMulticastV4Packets();
}
Int64 ident = Binder::ClearCallingIdentity();
//try {
mBatteryStats->NoteWifiMulticastDisabled(uid);
//} catch (RemoteException e) {
//} finally {
Binder::RestoreCallingIdentity(ident);
//}
}
} // namespace Wifi
} // namespace Server
} // namespace Droid
} // namespace Elastos
| 33.937978 | 154 | 0.626399 | [
"object",
"3d"
] |
f25f3599902e9df75b487acaa9a39c7e3cd65d39 | 678 | cc | C++ | ui/display/chromeos/ozone/touchscreen_delegate_ozone.cc | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-16T03:57:28.000Z | 2021-01-23T15:29:45.000Z | ui/display/chromeos/ozone/touchscreen_delegate_ozone.cc | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/display/chromeos/ozone/touchscreen_delegate_ozone.cc | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-03-15T13:21:38.000Z | 2017-03-15T13:21:38.000Z | // 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 "ui/display/chromeos/ozone/touchscreen_delegate_ozone.h"
namespace ui {
TouchscreenDelegateOzone::TouchscreenDelegateOzone() {}
TouchscreenDelegateOzone::~TouchscreenDelegateOzone() {}
void TouchscreenDelegateOzone::AssociateTouchscreens(
std::vector<OutputConfigurator::DisplayState>* outputs) {
NOTIMPLEMENTED();
}
void TouchscreenDelegateOzone::ConfigureCTM(
int touch_device_id,
const OutputConfigurator::CoordinateTransformation& ctm) {
NOTIMPLEMENTED();
}
} // namespace ui
| 27.12 | 73 | 0.781711 | [
"vector"
] |
f26344a483d3c710a0779b3a46e04d3d7d5816de | 4,348 | hpp | C++ | lib/utils.hpp | c-vigo/mudirac | 86c71f6ec25c8328ac7c32abde21c240f41f73e2 | [
"MIT"
] | 3 | 2021-03-04T09:17:20.000Z | 2022-03-03T04:13:16.000Z | lib/utils.hpp | c-vigo/mudirac | 86c71f6ec25c8328ac7c32abde21c240f41f73e2 | [
"MIT"
] | null | null | null | lib/utils.hpp | c-vigo/mudirac | 86c71f6ec25c8328ac7c32abde21c240f41f73e2 | [
"MIT"
] | 2 | 2022-03-11T10:29:16.000Z | 2022-03-25T16:05:47.000Z | /**
* MuDirac - A muonic atom Dirac equation solver
* by Simone Sturniolo (2019-2020)
*
* utils.hpp
*
* Utility functions of various sorts - header file
*
* @author Simone Sturniolo
* @version 1.0 20/03/2020
*/
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <functional>
#include "../vendor/aixlog/aixlog.hpp"
using namespace std;
#ifndef MUDIRAC_UTILS
#define MUDIRAC_UTILS
double effectiveMass(double m1, double m2);
int factorial(int n);
double sinc(double x);
double lerp(double a, double b, double t);
template <typename T>
vector<T> vectorOperation(vector<T> v1, vector<T> v2, char op);
template <typename T>
vector<T> vectorOperation(vector<T> v, T x, char op);
vector<double> linGrid(double x0, double x1, int n = 100);
vector<vector<double>> logGrid(double x0, double x1, int n = 100);
vector<vector<double>> logGrid(double xc, double dx, int i0, int i1);
double genLaguerrePoly(double x, int n, double alpha);
vector<double> genLaguerrePoly(vector<double> x, int n, int alpha);
int countNodes(vector<double> v, double tol = 1e-8);
void qnumSchro2Dirac(int l, bool s, int &k);
void qnumDirac2Schro(int k, int &l, bool &s);
void qnumNodes2Principal(int nodes, int l, int &n);
void qnumPrincipal2Nodes(int n, int l, int &nodes);
double cgCoeff(int k, double m, bool s);
void parseIupacState(string istate, int &n, int &l, bool &s);
string printIupacState(int n, int l, bool s);
void parseIupacRange(string irange, vector<int> &nrange, vector<int> &lrange, vector<bool> &srange);
vector<string> splitString(string s, string sep = " ", bool merge = false, int maxn = -1);
string stripString(string s, string strip = " \t\n");
string upperString(string s);
// Functions useful for debugging
void writeTabulated2ColFile(vector<double> col1, vector<double> col2, string fname);
// Templated function declarations
/**
* @brief Search if a vector contains an element
*
* @tparam T Type of the vectors' elements
* @param v Vector
* @param e Element
* @retval True if e is in v
*/
template <typename T>
bool vectorContains(vector<T> v, T e)
{
return find(v.begin(), v.end(), e) != v.end();
}
/**
* @brief Perform an element-wise operation on two vectors
*
* @tparam T Type of the vectors' elements
* @param v1 First vector
* @param v2 Second vector
* @param op Operator (can be +, -, *, / or ^)
* @retval vector<T>
*/
template <typename T>
vector<T> vectorOperation(vector<T> v1, vector<T> v2, char op)
{
if (v1.size() != v2.size())
{
throw runtime_error("Vectors don't match in size");
}
vector<T> ans(v1.size());
T(*opfunc)
(T, T);
switch (op)
{
case '+':
opfunc = [](T a, T b) { return a + b; };
break;
case '-':
opfunc = [](T a, T b) { return a - b; };
break;
case '*':
opfunc = [](T a, T b) { return a * b; };
break;
case '/':
opfunc = [](T a, T b) { return a / b; };
break;
case '^':
opfunc = pow;
break;
default:
throw invalid_argument("Invalid operator code for vectorOperation");
break;
}
for (int i = 0; i < v1.size(); ++i)
{
ans[i] = opfunc(v1[i], v2[i]);
}
return ans;
}
/**
* @brief Perform an element-wise operation on a vector
* and a scalar
*
* @tparam T Type of the vectors' elements
* @param v Vector
* @param x Scalar
* @param op Operator (can be +, -, *, / or ^)
* @retval vector<T>
*/
template <typename T>
vector<T> vectorOperation(vector<T> v, T x, char op)
{
vector<T> ans(v.size());
T(*opfunc)
(T, T);
switch (op)
{
case '+':
opfunc = [](T a, T b) { return a + b; };
break;
case '-':
opfunc = [](T a, T b) { return a - b; };
break;
case '*':
opfunc = [](T a, T b) { return a * b; };
break;
case '/':
opfunc = [](T a, T b) { return a / b; };
break;
case '^':
opfunc = pow;
break;
default:
throw invalid_argument("Invalid operator code for vectorOperation");
break;
}
for (int i = 0; i < v.size(); ++i)
{
ans[i] = opfunc(v[i], x);
}
return ans;
}
#endif | 24.022099 | 100 | 0.589926 | [
"vector"
] |
f2656c6f87bcfa6a4427f40f658f9a8ef1dac935 | 1,287 | cpp | C++ | core/src/Scripting/ScriptingEngine.cpp | tokongs/yage | 14c9411d8efce08b89c0deb134b5c3023a32c577 | [
"MIT"
] | null | null | null | core/src/Scripting/ScriptingEngine.cpp | tokongs/yage | 14c9411d8efce08b89c0deb134b5c3023a32c577 | [
"MIT"
] | null | null | null | core/src/Scripting/ScriptingEngine.cpp | tokongs/yage | 14c9411d8efce08b89c0deb134b5c3023a32c577 | [
"MIT"
] | null | null | null | #include "ScriptingEngine.h"
namespace yage {
sol::state ScriptingEngine::mLuaState = sol::state();
void ScriptingEngine::Init() {
OpenLuaLibs(&mLuaState);
SetupInputAPI(&mLuaState);
SetupGameObjectsAPI(&mLuaState);
SetupSceneAPI(&mLuaState);
SetupMathAPI(&mLuaState);
}
void ScriptingEngine::ExecuteScript(GameObject *object, yage::Script *script) {
if (!object) {
YAGE_ERROR("Trying to bin null object to script! Skipping...");
return;
}
mLuaState["this"] = object;
ExecuteScript(script);
}
void ScriptingEngine::ExecuteOnUpdate(yage::GameObject *object, yage::Script *script) {
if (!object) {
YAGE_ERROR("Trying to bin null object to script! Skipping...");
return;
}
if (!script) {
YAGE_ERROR("Trying to exexute null script! Skipping...");
return;
}
(*script->getLuaState())["this"] = object;
script->onUpdate();
}
void ScriptingEngine::ExecuteScript(yage::Script *script) {
if (!script) {
YAGE_ERROR("Trying to exexute null script! Skipping...");
return;
}
mLuaState.script(script->getContent());
}
} | 28.6 | 91 | 0.574981 | [
"object"
] |
f268eb277c51f0cc0df300e0de60bd1a6fcb7abd | 130,217 | cpp | C++ | Source/SystemQOR/MSWindows/WinQL/System/FileSystem/WinQLStream.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/SystemQOR/MSWindows/WinQL/System/FileSystem/WinQLStream.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/SystemQOR/MSWindows/WinQL/System/FileSystem/WinQLStream.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //WinQLStream.cpp
// Copyright Querysoft Limited 2016
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include <assert.h>
#include "WinQL/Application/ErrorSystem/WinQLError.h"
#include "WinQL/Application/ErrorSystem/WinQLErrDomain.h"
#include "WinQL/Application/WinQLApplication.h"
#include "WinQL/CodeServices/Locale/WinQLLocale.h"
#include "WinQL/Application/Subsystems/WinQLStandardIO.h"
#include "WinQL/Application/SubSystems/WinQLTerminal.h"
#include "WinQL/Application/Comms/IPC/Pipe/WinQLPipe.h"
#include "WinQL/System/FileSystem/WinQLStream.h"
#include "WinQL/System/FileSystem/WinQLStreamFormatter.h"
#include "WinQAPI/Kernel32.h"
//--------------------------------------------------------------------------------
namespace nsWin32
{
using namespace nsWinQAPI;
//--------------------------------------------------------------------------------
__QOR_INTERFACE(__WINQL) char CStream::sachLookupTrailBytes[ 256 ] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0
};
//----------------------------------------------------------------------------------------
int CStream::utf8_no_of_trailbytes(char c)
{
return CStream::sachLookupTrailBytes[(unsigned char)c];
}
//------------------------------------------------------------------------------
void* CStream::_stdbuf[ 2 ] = { NULL, NULL };
//------------------------------------------------------------------------------
CStream::CStream() : CIOStream()
{
Reset();
}
//------------------------------------------------------------------------------
CStream::CStream( const CStream& src )
{
*this = src;
}
//------------------------------------------------------------------------------
CStream& CStream:: operator = ( const CStream& src )
{
if( &src != this )
{
CIOStream::operator=( src );
m_lRefCount = src.m_lRefCount;
m_pStreamDevice = src.m_pStreamDevice;
}
return *this;
}
//------------------------------------------------------------------------------
//fopen constructor
CStream::CStream( const char* filename, const char* mode ) : CIOStream()
{
Reset();
if( *filename == '\0' )
{
errno = EINVAL;
}
else
{
_fsopen( filename, mode, _SH_DENYNO );
}
}
//------------------------------------------------------------------------------
CStream::~CStream()
{
fclose();
}
//------------------------------------------------------------------------------
void CStream::Reset( void )
{
CIOStream::Reset();
m_lRefCount = 0; //Count of external references
m_pStreamDevice = nullptr; //File, Pipe or Device
}
//------------------------------------------------------------------------------
CStream* CStream::_stdin( void )
{
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO != 0 )
{
return pStandardIO->StreamFromID( 0 );
}
return nullptr;
}
//------------------------------------------------------------------------------
CStream* CStream::_stdout( void )
{
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO )
{
return pStandardIO->StreamFromID( 1 );
}
return nullptr;
}
//------------------------------------------------------------------------------
CStream* CStream::_stderr( void )
{
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO )
{
return pStandardIO->StreamFromID( 2 );
}
return nullptr;
}
//------------------------------------------------------------------------------
CStream* CStream::fdopen( int fd, const char* mode )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::_fdopen(int fd, const char* mode)
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::fmemopen( void* __QCMP_RESTRICT, size_t, const char * )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::freopen( const char* filename, const char* mode )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::open_memstream( char**, size_t* )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::popen( const char*, const char* )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::_popen( const char* command, const char* mode )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::tmpfile( void )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::open_wmemstream( wchar_t**, size_t* )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::_wpopen( const wchar_t* pCommand, const wchar_t* pMode )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::_wfsopen( const wchar_t* pFilename, const wchar_t* pMode )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::_wfreopen( const wchar_t* pFilename, const wchar_t* pMode )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
CStream* CStream::_wfopen( const wchar_t* pFilename, const wchar_t* pMode )
{
return 0;//TODO:
}
//------------------------------------------------------------------------------
long CStream::AddRef( void )
{
return ++m_lRefCount;
}
//------------------------------------------------------------------------------
long CStream::Release( void )
{
long lResult = --m_lRefCount;
if( lResult <= 0 )
{
fclose();
delete this;
}
return lResult;
}
//------------------------------------------------------------------------------
void CStream::clearerr()
{
clearerr_s();
}
//------------------------------------------------------------------------------
errno_t CStream::clearerr_s( void )
{
if( this == NULL )
{
errno = EINVAL;
return EINVAL;
}
CIOStream::Lock();
__try
{
CIOStream::ClearErrorFlags();
}
__finally
{
CIOStream::Unlock();
}
return 0;
}
//------------------------------------------------------------------------------
int CStream::feof( void )
{
if( this == 0 )
{
errno = EINVAL;
return 0;
}
return CIOStream::IsBufferEOF();
}
//------------------------------------------------------------------------------
int CStream::ferror( void )
{
if( this == 0 )
{
errno = EINVAL;
return 0;
}
return CIOStream::IsBufferError();
}
//------------------------------------------------------------------------------
int CStream::fileno( void )
{
return CIOStream::GetFileNumber();
}
//------------------------------------------------------------------------------
int CStream::_fileno( void )
{
return CIOStream::GetFileNumber();
}
//------------------------------------------------------------------------------
//file://D:\Develop\susv4\functions\pclose.html
int CStream::pclose( void )//- close a pipe stream to or from a process
{
return 0;
}
//------------------------------------------------------------------------------
//file://D:\Develop\susv4\functions\fwide.html
int CStream::fwide( int mode )
{
return 0;
}
//------------------------------------------------------------------------------
void CStream::flockfile( void )
{
CIOStream::Lock();
}
//------------------------------------------------------------------------------
int CStream::ftrylockfile( void )
{
return CIOStream::TryLock();
}
//------------------------------------------------------------------------------
void CStream::funlockfile( void )
{
CIOStream::Unlock();
}
//------------------------------------------------------------------------------
CStream* CStream::fopen( const char* file, const char* mode )
{
return( CStream::_fsopen( file, mode, _SH_DENYNO ) );
}
//------------------------------------------------------------------------------
CStream* CStream::_fsopen( const char* file, const char* mode, int shflag )
{
CStream* stream = 0;
if( file == NULL || mode == NULL || *mode == '\0' )
{
errno = EINVAL;
return 0;
}
// Get a free stream
// [NOTE: _getstream() returns a locked stream.]
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO )
{
stream = pStandardIO->_getstream();
}
if( stream == NULL )
{
errno = EMFILE;
return NULL;
}
return _fsopenEx( file, mode, shflag, stream );
}
//------------------------------------------------------------------------------
CStream* CStream::_fsopenEx( const char* file, const char* mode, int shflag, CStream* stream )
{
__try
{
if( *file == '\0' )
{
errno = EINVAL;
return nullptr;
}
else if( stream != nullptr )
{
stream->_openfile(file, mode, shflag, stream);
}
}
__finally
{
if( stream != nullptr )
{
stream->funlockfile();
}
}
return stream;
}
// set default file commit mode to commit
//this must move to the StandardIO Subsystem object
int _commode = CStream::_IOCOMMIT;
//------------------------------------------------------------------------------
void CStream::_openfile( const char* filename, const char* mode, int shflag, CStream* str )
{
int modeflag = 0;
int streamflag = _commode;
//int commodeset = 0;
//int scanset = 0;
//int filedes = -2;
//bool encodingFlag = false;
assert( filename != NULL );
assert( mode != NULL );
assert( str != NULL );
/* Parse the user's specification string as set flags in
(1) modeflag - system call flags word
(2) streamflag - stream handle flags word. */
ParseMode( mode, modeflag, streamflag );
// Try to open the file. Note that if neither 't' nor 'b' is specified, _sopen will use the default.
if( _sopen_s( filename, modeflag, shflag, _S_IREAD | _S_IWRITE ) != 0 )
{
return;
}
// Init pointers
CIOStream::OpenBuffer( GetFileNumber(), streamflag );
}
//------------------------------------------------------------------------------
errno_t CStream::_sopen_s( const char* path, int oflag, int shflag, int pmode )
{
// Last parameter passed as 1 because we want to validate pmode from the secure open_s
return _sopen_helper( path, oflag, shflag, pmode, 1 );
}
//------------------------------------------------------------------------------
errno_t CStream::_sopen_helper( const char* path, int oflag, int shflag, int pmode, int bSecure )
{
errno_t retval = 0;
int unlock_flag = 0;
if( path == NULL )
{
errno = EINVAL;
return EINVAL;
}
if( bSecure )
{
if( !( ( pmode & ( ~( _S_IREAD | _S_IWRITE ) ) ) == 0 ) )
{
errno = EINVAL;
return EINVAL;
}
}
__try
{
retval = _sopen_nolock( &unlock_flag, path, oflag, shflag, pmode, bSecure );
}
__finally
{
if( unlock_flag )
{
if( retval )
{
CIOStream::SetIsOpen( false );
}
funlockfile();
}
}
// in error case, ensure *pfh is -1
if( retval != 0 )
{
SetFileNumber(-1);
}
return retval;
}
//------------------------------------------------------------------------------
errno_t CStream::_sopen_nolock( int* punlock_flag, const char* path, int oflag, int shflag, int pmode, int bSecure )
{
wchar_t* pathw = 0;
int retval;
// At this point we know path is not null
if( !__copy_path_to_wide_string( path, &pathw ) )
{
return -1;
}
// call the wide-char variant
retval = _wsopen_nolock( punlock_flag, pathw, oflag, shflag, pmode, bSecure );
free( pathw ); // _free_crt leaves errno alone if everything completes as expected
return retval;
}
//------------------------------------------------------------------------------
bool CStream::__copy_path_to_wide_string( const char* path, wchar_t** outPath )
{
int len;
unsigned int codePage = CCodePage::ACP;
if( path == NULL || outPath == NULL )
{
errno = EINVAL;
return false;
}
#if !defined (_CORESYS) && !defined (_CRT_APP)
/*
if( !true/__crtIsPackagedApp()/ && !m_FileHelper.AreApisANSI() )
{
codePage = CCodePage::OEMCP;
}*/
#endif /* !defined (_CORESYS) && !defined (_CRT_APP) */
*outPath = NULL;
// get the buffer size needed for conversion
if( ( len = m_StringHelper.MultiByteToWideChar( codePage, 0 /* Use default flags */, path, -1, 0, 0 ) ) == 0 )
{
CDOSError::MapError( m_ErrorHelper.GetLastError() );
return false;
}
// allocate enough space for path wide char
if( ( *outPath = (wchar_t*)malloc( len * sizeof( wchar_t ) ) ) == NULL )
{
// malloc should set the errno
return false;
}
// now do the conversion
if( m_StringHelper.MultiByteToWideChar( codePage, 0 /* Use default flags */, path, -1, *outPath, len ) == 0 )
{
CDOSError::MapError( m_ErrorHelper.GetLastError() );
free( *outPath );
*outPath = NULL;
return false;
}
return true;
}
//------------------------------------------------------------------------------
errno_t CStream::_wsopen_nolock( int* punlock_flag, const wchar_t* path, int oflag, int shflag, int pmode, int bSecure )
{
Cmp__int64 filepos; // length of file - 1
wchar_t ch; // character at end of file
char fileflags; // _osfile flags
int fmode = 0;
//void* osfh; // OS handle of opened file
unsigned long fileaccess; // OS file access (requested)
unsigned long fileshare; // OS file sharing mode
unsigned long filecreate = 0; // OS method of opening/creating
unsigned long fileattrib; // OS file attributes
unsigned long fileattribflags; // OS file flags
SECURITY_ATTRIBUTES SecurityAttributes;
char tmode = __IOINFO_TM_ANSI; // textmode - ANSI/UTF-8/UTF-16
errno_t retvalue = 0;
SecurityAttributes.nLength = sizeof( SecurityAttributes );
SecurityAttributes.lpSecurityDescriptor = NULL;
if( oflag & ONoInherit )
{
SecurityAttributes.bInheritHandle = false;
fileflags = FNOINHERIT;
}
else
{
SecurityAttributes.bInheritHandle = true;
fileflags = 0;
}
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO )
{
errno = pStandardIO->_get_fmode( &fmode );
}
if( errno != Success )
{
return errno;
}
// figure out binary/text mode
if( ( oflag & OBinary ) == 0 )
{
if( oflag & ( OText | OWText | OU16Text | OU8Text ) )
{
fileflags |= FTEXT;
}
else if( fmode != OBinary ) // check default mode
{
fileflags |= FTEXT;
}
}
//decode the access flags
switch( oflag & ( OReadOnly | OWriteOnly | OReadWrite ) )
{
case OReadOnly: // read access
fileaccess = Generic_Read;
break;
case OWriteOnly: // write access
// giving it read access as well because in append (a, not a+), we need to read the BOM to determine the encoding (ie. ANSI, UTF8, UTF16)
if( ( oflag & OAppend ) && ( oflag & ( OWText | OU16Text | OU8Text ) ) != 0 )
{
fileaccess = Generic_Read | Generic_Write;
}
else
{
fileaccess = Generic_Write;
}
break;
case OReadWrite: // read and write access
fileaccess = Generic_Read | Generic_Write;
break;
default: // error, bad oflag
_set_doserrno( 0 ); // not an OS error
SetFileNumber(-1);
return EINVAL;
//_VALIDATE_RETURN_ERRCODE(( "Invalid open flag" , 0 ), EINVAL);
}
//decode sharing flags
switch( shflag )
{
case _SH_DENYRW: // exclusive access
fileshare = 0L;
break;
case _SH_DENYWR: // share read access
fileshare = File_Share_Read;
break;
case _SH_DENYRD: // share write access
fileshare = File_Share_Write;
break;
case _SH_DENYNO: // share read and write access
fileshare = File_Share_Read | File_Share_Write;
break;
case _SH_SECURE: // share read access only if read-only
if( fileaccess == Generic_Read )
fileshare = File_Share_Read;
else
fileshare = 0L;
break;
default: // error, bad shflag
_set_doserrno( 0 ); // not an OS error
SetFileNumber(-1);
return EINVAL;
//_VALIDATE_RETURN_ERRCODE(( "Invalid sharing flag" , 0 ), EINVAL);
}
//decode open/create method flags
switch( oflag & ( OCreate | OExclusive | OTruncate ) )
{
case 0:
case OExclusive: // ignore EXCL w/o CREAT
filecreate = Open_Existing;
break;
case OCreate:
filecreate = Open_Always;
break;
case OCreate | OExclusive:
case OCreate | OTruncate | OExclusive:
filecreate = Create_New;
break;
case OTruncate:
case OTruncate | OExclusive: // ignore EXCL w/o CREAT
filecreate = Truncate_Existing;
break;
case OCreate | OTruncate:
filecreate = Create_Always;
break;
default:
// this can't happen ... all cases are covered
_set_doserrno( 0 );
SetFileNumber(-1);
return EINVAL;
//_VALIDATE_RETURN_ERRCODE(( "Invalid open flag" , 0 ), EINVAL);
}
//decode file attribute flags if _O_CREAT was specified
fileattrib = File_Attribute_Normal; // default
fileattribflags = 0;
int iuMaskVal = 0;
if( pStandardIO )
{
iuMaskVal = pStandardIO->_umaskval();
}
if( oflag & OCreate )
{
if( !( ( pmode & ~( iuMaskVal ) ) & _S_IWRITE ) )
{
fileattrib = File_Attribute_ReadOnly;
}
}
//Set temporary file (delete-on-close) attribute if requested.
if( oflag & OTemporary )
{
fileattribflags |= File_Flag_Delete_On_Close;//FILE_FLAG_DELETE_ON_CLOSE;
fileaccess |= Delete;//DELETE;
fileshare |= File_Share_Delete;//FILE_SHARE_DELETE;
}
//Set temporary file (delay-flush-to-disk) attribute if requested.
if( oflag & OShortLived )
{
fileattrib |= File_Attribute_Temporary;//FILE_ATTRIBUTE_TEMPORARY;
}
//Set directory access attribute if requested.
if( oflag & OObtainDir )
{
fileattribflags |= File_Flag_Backup_Semantics;//FILE_FLAG_BACKUP_SEMANTICS;
}
//Set sequential or random access attribute if requested.
if( oflag & OSequential )
{
fileattribflags |= File_Flag_Sequential_Scan;//FILE_FLAG_SEQUENTIAL_SCAN;
}
else if( oflag & ORandom )
{
fileattribflags |= File_Flag_Random_Access;//FILE_FLAG_RANDOM_ACCESS;
}
/*get an available handle.
*
* multi-thread note: the returned handle is locked!
*/
/*
if( ( *pfh = _alloc_osfhnd() ) == -1 )
{
_doserrno = 0L; // not an OS error
*pfh = -1;
errno = EMFILE;
return errno; // return error to caller
}
*/
/* Beyond this do not set *pfh = -1 on errors for MT.
Because the caller needs to release the lock on the
handle */
*punlock_flag = 1;
//try to open/create the file
m_pStreamDevice = CreateDeviceFile( path, fileaccess, fileshare, &SecurityAttributes, filecreate, fileattrib | fileattribflags, 0, oflag );
if( m_pStreamDevice == 0 )
{
CIOStream::SetIsOpen( false );
CDOSError::MapError( m_ErrorHelper.GetLastError() );
retvalue = errno;
goto exit;
}
if( m_pStreamDevice->GetType() == File_Type_Char )
{
fileflags |= FDEV;
}
else if( m_pStreamDevice->GetType() == File_Type_Pipe )
{
fileflags |= FPIPE;
}
fileflags |= FOPEN;
CIOStream::SetFlags( fileflags );
CIOStream::SetTextMode( __IOINFO_TM_ANSI );// TextMode set to ANSI by default, if we find a BOM, then we reset it to the appropriate type below
if( !( fileflags & ( FDEV | FPIPE ) ) && ( fileflags & FTEXT ) && ( oflag & OReadWrite ) )
{
/* We have a text mode file. If it ends in CTRL-Z, we wish to remove the CTRL-Z character, so that appending will work.
We do this by seeking to the end of file, reading the last byte, and shortening the file if it is a CTRL-Z. */
if( ( filepos = _lseeki64_nolock(GetFileNumber(), -1, SEEK_END ) ) == -1 )
{
// OS error -- should ignore negative seek error, since that means we had a zero-length file.
int err;
_get_doserrno( &err );
if( err != ErrorNegativeSeek )
{
_close_nolock(GetFileNumber());
retvalue = errno;
goto exit;
}
}
else
{
// Seek was OK, read the last char in file. The last char is a CTRL-Z if and only if _read returns 0 and ch ends up with a CTRL-Z.
ch = 0;
if( _read_nolock(GetFileNumber(), &ch, 1 ) == 0 && ch == 26 )
{
// read was OK and we got CTRL-Z! Wipe it out!
if( _chsize_nolock(GetFileNumber(), filepos ) == -1 )
{
_close_nolock(GetFileNumber());
retvalue = errno;
goto exit;
}
}
// now rewind the file to the beginning
if( ( filepos = _lseeki64_nolock(GetFileNumber(), 0, SEEK_SET ) ) == -1 )
{
_close_nolock( GetFileNumber() );
retvalue = errno;
goto exit;
}
}
}
if( fileflags & FTEXT )
{
int count;
// Set default tmode per oflag. BOM will change the default.
// If oflag does not specify file type get type from _fmode
if( ( oflag & ( OText | OWText | OU16Text | OU8Text ) ) == 0 )
{
// Type specified in default mode?
if( ( fmode & ( OText | OWText | OU16Text | OU8Text ) ) == 0 )
{
oflag |= OText; // default to ANSI
}
else
{
oflag |= fmode & ( OText | OWText | OU16Text | OU8Text );
}
}
// Now oflags should be set to one of the text modes
assert( ( oflag & ( OText | OWText | OU16Text | OU8Text ) ) != 0 );
switch( oflag & ( OText | OWText | OU16Text | OU8Text ) )
{
case OText:
tmode = __IOINFO_TM_ANSI;
break;
case OWText:
case OWText | OText:
if( ( oflag & ( OWriteOnly | OCreate | OTruncate ) ) == ( OWriteOnly | OCreate | OTruncate ) )
{
tmode = __IOINFO_TM_UTF16LE;
}
break;
case OU16Text:
case OU16Text | OText:
tmode = __IOINFO_TM_UTF16LE;
break;
case OU8Text:
case OU8Text | OText:
tmode = __IOINFO_TM_UTF8;
break;
}
/* If the file hasn't been opened with the UNICODE flags then we
have nothing to do - textmode's already set to default specified in oflag */
if( ( oflag & ( OWText | OU16Text | OU8Text ) ) != 0 )
{
int bom = 0;
int bWriteBom = 0;
int bCheckBom = 0;
if( !( fileflags & FDEV ) )
{
switch( fileaccess & ( Generic_Read | Generic_Write ) )
{
case Generic_Read:
{
bCheckBom = 1;
break;
}
case Generic_Write:
{
switch( filecreate )
{
// Write BOM if empty file
case Open_Existing:
case Open_Always:
{
/* Check if the file contains at least one byte */
/* Fall through otherwise */
if( _lseeki64_nolock(GetFileNumber(), 0, SEEK_END ) != 0 )
{
if( _lseeki64_nolock(GetFileNumber(), 0, SEEK_SET ) == -1 )
{
_close_nolock(GetFileNumber());
retvalue = errno;
goto exit;
}
break;
}
}
/* New or truncated file. Always write BOM */
case Create_New:
case Create_Always:
case Truncate_Existing:
{
bWriteBom = 1;
break;
}
}
break;
}
case Generic_Read | Generic_Write:
{
switch( filecreate )
{
// Check for existing BOM, Write BOM if empty file
case Open_Existing:
case Open_Always:
{
// Check if the file contains at least one byte
// Fall through otherwise
if( _lseeki64_nolock(GetFileNumber(), 0, SEEK_END ) != 0 )
{
if( _lseeki64_nolock(GetFileNumber(), 0, SEEK_SET ) == -1 )
{
_close_nolock(GetFileNumber());
retvalue = errno;
goto exit;
}
bCheckBom = 1;
}
else
{
bWriteBom = 1; // reset if file is not zero size
}
break;
}
// New or truncated file. Always write BOM
case Create_New:
case Truncate_Existing:
case Create_Always:
{
bWriteBom = 1;
break;
}
}
break;
}
}
}
if( bCheckBom )
{
count = _read_nolock(GetFileNumber(), &bom, UTF8_BOMLEN );
//Internal Validation. This branch should never be taken if bWriteBom is 1 and count > 0
if( count > 0 && bWriteBom == 1 )
{
assert( 0 && "Internal Error" );
bWriteBom = 0;
}
switch( count )
{
case -1:
_close_nolock(GetFileNumber());
retvalue = errno;
goto exit;
case UTF8_BOMLEN:
if( bom == UTF8_BOM ) {
tmode = __IOINFO_TM_UTF8;
break;
}
case UTF16_BOMLEN:
if( ( bom & BOM_MASK ) == UTF16BE_BOM )
{
_close_nolock(GetFileNumber());
assert( 0 && "Only UTF-16 little endian & UTF-8 is supported for reads" );
retvalue = errno = EINVAL;
goto exit;
}
if( ( bom & BOM_MASK ) == UTF16LE_BOM )
{
/* We have read 3 bytes, so we should seek back 1 byte */
if( ( filepos = _lseeki64_nolock(GetFileNumber(), UTF16_BOMLEN, SEEK_SET ) ) == -1 )
{
_close_nolock(GetFileNumber());
retvalue = errno;
goto exit;
}
tmode = __IOINFO_TM_UTF16LE;
break;
}
// Fall through to default case to lseek to beginning of file
default:
if( ( filepos = _lseeki64_nolock(GetFileNumber(), 0, SEEK_SET ) ) == -1 )
{
// No BOM, so we should seek back to the beginning of the file
_close_nolock(GetFileNumber());
retvalue = errno;
goto exit;
}
break;
}
}
if( bWriteBom )
{
int written = 0;
int bomlen = 0;
bom = 0;
// If we are creating a new file, we write a UTF-16LE or UTF8 BOM
switch( tmode )
{
case __IOINFO_TM_UTF16LE:
{
bom = UTF16LE_BOM;
bomlen = UTF16_BOMLEN;
break;
}
case __IOINFO_TM_UTF8:
{
bom = UTF8_BOM;
bomlen = UTF8_BOMLEN;
break;
}
}
while( bomlen > written )
{
int tmp = 0;
// Note that write may write less than bomlen characters, but not really fail. Retry till write fails or till we wrote all the characters.
if( ( tmp = _write(GetFileNumber(), ( (char *)( &bom ) ) + written, bomlen - written ) ) == -1 )
{
_close_nolock( GetFileNumber() );
retvalue = errno;
goto exit;
}
written += tmp;
}
}
}
}
CIOStream::SetTextMode( tmode );
CIOStream::SetIsUnicode( ( ( oflag & OWText ) == 0 ) ? false : true );
//Set FAPPEND flag if appropriate. Don't do this for devices or pipes.
if( !( fileflags & ( FDEV | FPIPE ) ) && ( oflag & OAppend ) )
{
CIOStream::SetIsAppend( true );
}
//re-open the file with write access only if we opened the file with read access to read the BOM before
if( ( fileaccess & ( Generic_Read | Generic_Write ) ) == ( Generic_Read | Generic_Write ) && ( oflag & OWriteOnly ) )
{
// we will have to reopen the file again with the write access (but not read)
delete m_pStreamDevice;
m_pStreamDevice = 0;
fileaccess &= ~Generic_Read;
// we want to use OPEN_EXISTING here, because the user can open the an non-existing
// file for append with _O_EXCL flag
filecreate = Open_Existing;
m_pStreamDevice = CreateDeviceFile( path, fileaccess, fileshare, &SecurityAttributes, filecreate, fileattrib | fileattribflags, 0, oflag );
if( m_pStreamDevice == nullptr )
{
/* OS call to open/create file failed! map the error, release
* the lock, and return -1. Note that it's *necessary* to
* call _free_osfhnd (unlike the situation before), because we have
* already set the file handle in the _ioinfo structure
*/
CDOSError::MapError( m_ErrorHelper.GetLastError() );
CIOStream::SetIsOpen( false );
retvalue = errno;
goto exit;
}
else
{
// We were able to open the file successfully, set the file
// handle in the _ioinfo structure, then we are done. All
// the fileflags should have been set properly already.
//*pfh = (intptr_t)osfh;
}
}
exit:
return retvalue;
}
//------------------------------------------------------------------------------
CDeviceFile* CStream::CreateDeviceFile( const wchar_t* lpFileName, unsigned long& dwDesiredAccess, unsigned long dwShareMode, nsWin32::LPSECURITY_ATTRIBUTES lpSecurityAttributes, unsigned long dwCreationDisposition, unsigned long dwFlagsAndAttributes, void* hTemplateFile, int oflag )
{
CDeviceFile* pDeviceFile = 0;
CErrorHelper ErrorHelper;
CDeviceHandle::ref_type Handle = new_shared_ref<CDeviceHandle>( CKernel32::CreateFileW( lpFileName, dwDesiredAccess, dwShareMode, reinterpret_cast< ::LPSECURITY_ATTRIBUTES >( lpSecurityAttributes ), dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ) );
if( Handle().IsInvalid() )
{
if( ( dwDesiredAccess & ( Generic_Read | Generic_Write ) ) == ( Generic_Read | Generic_Write ) && ( oflag & OWriteOnly ) )
{
//We just failed on CreateFile(), because we might be trying open something for read while it cannot be read (eg. pipes or devices).
//So try again with GENERIC_WRITE and we will have to use the default encoding. We won't be able to determine the encoding from reading the BOM.
dwDesiredAccess &= ~Generic_Read;
Handle = new_shared_ref<CDeviceHandle>( CKernel32::CreateFileW( lpFileName, dwDesiredAccess, dwShareMode, reinterpret_cast<::LPSECURITY_ATTRIBUTES>( lpSecurityAttributes ), dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ) );
if( Handle().IsInvalid() )
{
return pDeviceFile;
}
}
else
{
return pDeviceFile;
}
}
switch( CKernel32::GetFileType( Handle().Use() ) )
{
case File_Type_Unknown:
{
unsigned long dwLastError = ErrorHelper.GetLastError();
if( dwLastError == Success )
{
pDeviceFile = new CDeviceFile( Handle );
}
}
break;
case File_Type_Char:
pDeviceFile = new CDeviceFile( Handle );
break;
case File_Type_Pipe:
pDeviceFile = new CPipe( Handle );
break;
case File_Type_Disk:
pDeviceFile = new CFile( Handle );
break;
default:
pDeviceFile = new CDeviceFile( Handle );
break;
}
return pDeviceFile;
}
//------------------------------------------------------------------------------
errno_t CStream::_chsize_s( int filedes, Cmp__int64 size )
{
int r = 0; // return value
//_CHECK_FH_CLEAR_OSSERR_RETURN_ERRCODE( filedes, EBADF );
//_VALIDATE_CLEAR_OSSERR_RETURN_ERRCODE((filedes >= 0 && (unsigned)filedes < (unsigned)_nhandle), EBADF);
//_VALIDATE_CLEAR_OSSERR_RETURN_ERRCODE((_osfile(filedes) & FOPEN), EBADF);
//_VALIDATE_CLEAR_OSSERR_RETURN_ERRCODE((size >= 0), EINVAL);
flockfile();
__try
{
if( CIOStream::IsOpen() )
{
r = _chsize_nolock( filedes, size );
}
else
{
//assert(("Invalid file descriptor. File possibly closed by a different thread",0));
r = errno = EBADF;
}
}
__finally
{
funlockfile();
}
return r;
}
//------------------------------------------------------------------------------
errno_t CStream::_chsize_nolock( int filedes, Cmp__int64 size )
{
Cmp__int64 filend;
Cmp__int64 extend;
Cmp__int64 place;
int cnt;
int oldmode;
Cmp__int64 retval = 0; // assume good return
errno_t err = 0;
// Get current file position and seek to end
if( ( ( place = _lseeki64_nolock( filedes, 0i64, SEEK_CUR ) ) == -1i64 ) || ( ( filend = _lseeki64_nolock( filedes, 0i64, SEEK_END ) ) == -1i64 ) )
{
return errno;
}
extend = size - filend;
// Grow or shrink the file as necessary
if( extend > 0i64 )
{
// extending the file
CHeap ProcessHeap;
char *bl = reinterpret_cast< char* >( ProcessHeap.Alloc( CHeap::Zero_Memory, _INTERNAL_BUFSIZ ) );
if( !bl )
{
err = errno = ENOMEM;
retval = -1i64;
}
else
{
oldmode = _setmode_nolock( filedes, OBinary );
// pad out with nulls
do
{
cnt = ( extend >= (__int64)_INTERNAL_BUFSIZ ) ? _INTERNAL_BUFSIZ : (int)extend;
if( ( cnt = _write_nolock( filedes, bl, ( extend >= (__int64)_INTERNAL_BUFSIZ ) ? _INTERNAL_BUFSIZ : (int)extend ) ) == -1 )
{
// Error on write
err = 0;
_get_doserrno( &err );
if( err == ErrorAccessDenied )
{
err = errno = EACCES;
}
retval = cnt;
break; // leave write loop
}
} while( ( extend -= (__int64)cnt ) > 0i64 );
_setmode_nolock( filedes, oldmode );
ProcessHeap.Free( 0, bl );
}
// retval set correctly
}
else if( extend < 0i64 )
{
// shortening the file
//Set file pointer to new eof...and truncate it there.
retval = _lseeki64_nolock( filedes, size, SEEK_SET );
if( retval != -1i64 )
{
if( ( retval = m_pStreamDevice->SetEOF() ? 0 : -1 ) == -1 )
{
err = errno = EACCES;
_set_doserrno( m_ErrorHelper.GetLastError() );
}
}
}
// else
// no file change needed
// retval = 0;
if( retval == -1 || ( _lseeki64_nolock( filedes, place, SEEK_SET ) == -1i64 ) )
{
return errno;
}
return 0;
}
//------------------------------------------------------------------------------
int CStream::_chsize( int filedes, long size )
{
errno_t e;
e = _chsize_s( filedes, (Cmp__int64)size );
return e == 0 ? 0 : -1;
}
//------------------------------------------------------------------------------
int CStream::_setmode( int fh, int mode )
{
int retval = 0;
if( !( ( mode == OText ) || ( mode == OBinary ) || ( mode == OWText ) || ( mode == OU8Text ) || ( mode == OU16Text ) ) )
{
errno = EINVAL;
return -1;
}
//_CHECK_FH_RETURN( fh, EBADF, -1 );
//_VALIDATE_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, -1);
//_VALIDATE_RETURN((_osfile(fh) & FOPEN), EBADF, -1);
flockfile();
__try
{
if( CIOStream::IsOpen() )
{
// set the text/binary mode
retval = _setmode_nolock( fh, mode );
}
else
{
errno = EBADF;
//_ASSERTE(("Invalid file descriptor. File possibly closed by a different thread",0));
retval = -1;
}
}
__finally
{
// unlock the file
funlockfile();
}
// Return to user (_setmode_nolock sets errno, if needed)
return retval;
}
//------------------------------------------------------------------------------
int CStream::_setmode_nolock( int fh, int mode )
{
return CIOStream::SetMode( mode );
}
//------------------------------------------------------------------------------
bool CStream::ParseMode( const char* szMode, int& iModeFlags, int& iStreamFlags )
{
bool bResult = false;
bool bComModeSet = false;
bool bScanSet = false;
bool bEncodingFlag = false;
char* pszMode = const_cast< char* >( szMode );
if( pszMode )
{
while( *pszMode == ' ' )// Skip leading spaces
{
++pszMode;
}
switch( *pszMode )
{
case 'r':
iModeFlags = OReadOnly;
iStreamFlags |= _IOREAD;
break;
case 'w':
iModeFlags = OWriteOnly | OCreate | OTruncate;
iStreamFlags |= _IOWRT;
break;
case 'a':
iModeFlags = OWriteOnly | OCreate | OAppend;
iStreamFlags |= _IOWRT;
break;
default:
return bResult;
}
bResult = true;
bool bContinue = true;
while( *pszMode && bContinue )
{
switch( *pszMode )
{
case ' ':
break;
case '+':
if( iModeFlags & OReadWrite )
{
bContinue = false;
}
else
{
iModeFlags |= OReadWrite;
iModeFlags &= ~( OReadOnly | OWriteOnly );
iStreamFlags |= _IORW;
iStreamFlags &= ~( _IOREAD | _IOWRT );
}
break;
case 'b':
if( iModeFlags & ( OText | OBinary ) )
{
bContinue = false;
}
else
{
iModeFlags |= OBinary;
}
break;
case 't':
if( iModeFlags & ( OText | OBinary ) )
{
bContinue = false;
}
else
{
iModeFlags |= OText;
}
break;
case 'c':
if( bComModeSet )
{
bContinue = false;
}
else
{
bComModeSet = true;
iStreamFlags |= _IOCOMMIT;
}
break;
case 'n':
if( bComModeSet )
{
bContinue = false;
}
else
{
bComModeSet = true;
iStreamFlags &= ~_IOCOMMIT;
}
break;
case 'S':
if( bScanSet )
{
bContinue = false;
}
else
{
bScanSet = true;
iModeFlags |= OSequential;
}
break;
case 'R':
if( bScanSet )
{
bContinue = false;
}
else
{
bScanSet = true;
iModeFlags |= ORandom;
}
break;
case 'T':
if( iModeFlags & OShortLived )
{
bContinue = false;
}
else
{
iModeFlags |= OShortLived;
}
break;
case 'D':
if( iModeFlags & OTemporary )
{
bContinue = false;
}
else
{
iModeFlags |= OTemporary;
}
break;
case 'N':
iModeFlags |= ONoInherit;
break;
case ',':
bEncodingFlag = 1;
bContinue = false;
break;
default:
//_VALIDATE_RETURN(("Invalid file open mode",0), EINVAL, NULL);
return bResult;
}
}
}
if( bEncodingFlag )
{
static const char ccsField[ ] = "ccs=";
static const char utf8encoding[ ] = "UTF-8";
static const char utf16encoding[ ] = "UTF-16LE";
static const char unicodeencoding[ ] = "UNICODE";
// Skip spaces
while( *pszMode == ' ' )
{
++pszMode;
}
//The length that we want to compare is numbers of elements in csField -1 since this number also contains NULL terminator
if( strncmp( ccsField, pszMode, ( _countof( ccsField ) ) - 1 ) != 0 )
{
//_VALIDATE_RETURN(("Invalid file open mode",0), EINVAL, NULL);
bResult = false;
return bResult;
}
pszMode += _countof( ccsField ) - 1;
if( stricmp( pszMode, utf8encoding ) == 0 )
{
pszMode += _countof( utf8encoding ) - 1;
iModeFlags |= OU8Text;
}
else if( stricmp( pszMode, utf16encoding ) == 0 )
{
pszMode += _countof( utf16encoding ) - 1;
iModeFlags |= OU16Text;
}
else if( stricmp( szMode, unicodeencoding ) == 0 )
{
pszMode += _countof( unicodeencoding ) - 1;
iModeFlags |= OWText;
}
else
{
//_VALIDATE_RETURN(("Invalid file open mode",0), EINVAL, NULL);
bResult = false;
return bResult;
}
}
while( *pszMode == ' ' )// Skip trailing spaces
{
++pszMode;
}
return bResult;
}
//------------------------------------------------------------------------------
int CStream::_stbuf()
{
int index;
assert( this != NULL );
// do nothing if not a tty device
if( !_isatty( _fileno() ) )
{
return 0;
}
// Make sure stream is stdout/stderr and init _stdbuf index
if( this == stdout )
{
index = 0;
}
else if( this == stderr )
{
index = 1;
}
else
{
return 0;
}
// Make sure the stream is not already buffered.
if( IsAnyBuffer() )
{
return 0;
}
// Allocate a buffer for this stream if we haven't done so yet.
if( ( _stdbuf[ index ] == NULL ) && ( ( _stdbuf[ index ] = malloc( _INTERNAL_BUFSIZ ) ) == NULL ) )
{
SetNoBuffering();// Cannot allocate buffer. Use _charbuf this time
}
else
{
SetYourBuffering( reinterpret_cast<char*>( _stdbuf[ index ] ), m_scuiInternalBufferSize );
}
StartTempBuffering();
return 1;
}
//------------------------------------------------------------------------------
void CStream::_ftbuf( int flag )
{
assert( flag == 0 || flag == 1 );
if( flag )
{
if( IsTempBuffering() )
{
// Flush the stream and tear down temp buffering.
_flush();
EndTempBuffering();
}
}
}
//------------------------------------------------------------------------------
int CStream::fflush( void )
{
int rc = 0;
if( this == NULL )//if stream is NULL, flush all streams
{
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO )
{
pStandardIO->flsall( CStandardIO::FlushNULL );
}
}
else
{
rc = fflushEx();
}
return( rc );
}
//------------------------------------------------------------------------------
int CStream::fflushEx()
{
int rc = 0;
flockfile();
__try
{
rc = _fflush_nolock();
}
__finally
{
funlockfile();
}
return rc;
}
//------------------------------------------------------------------------------
int CStream::_fflush_nolock()
{
if( this == NULL ) // if stream is NULL, flush all streams
{
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO )
{
pStandardIO->flsall( CStandardIO::FlushNULL );
}
}
else
{
if( _flush() != 0 )
{
return( EOF );// _flush failed, don't attempt to commit
}
if( IsCommit() )
{
return( _commit( _fileno() ) ? EOF : 0 );// commit to ensure data is written to disk
}
}
return 0;
}
//------------------------------------------------------------------------------
int CStream::_flush()
{
int rc = 0; // assume good return
int nchar;
if( BufferNeedsFlushing( nchar ) )
{
if( _write( _fileno(), GetBufferBasePointer(), nchar ) == nchar )
{
// if this is a read/write file, clear _IOWRT so that next operation can be a read
if( IsBufferReadWrite() )
{
EndWrite();
}
}
else
{
SetError();
rc = EOF;
}
}
BufferFlushed();
return rc;
}
//------------------------------------------------------------------------------
int CStream::_commit( int filedes )
{
int retval = 0;
// if filedes out of range, complain
//_CHECK_FH_RETURN( filedes, EBADF, -1 );
//_VALIDATE_RETURN((filedes >= 0 && (unsigned)filedes < (unsigned)_nhandle), EBADF, -1);
if( !IsOpen() )
{
errno = EBADF;
return -1;
}
flockfile();
__try
{
if( IsOpen() )
{
if( !m_pStreamDevice->FlushBuffers() )
{
retval = m_ErrorHelper.GetLastError();
}
else
{
retval = 0; // return success
}
// map the OS return code to C errno value and return code
if( retval == 0 )
{
goto good;
}
_set_doserrno( retval );
}
errno = EBADF;
retval = -1;
//assert(("Invalid file descriptor. File possibly closed by a different thread",0));
good:
;
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
void CStream::setbuf( char* buffer )
{
assert( this != NULL );
if( buffer == NULL )
{
setvbuf( NULL, m_scusIONoBuffering, 0 );
}
else
{
setvbuf( buffer, m_scusIOFullBuffering, m_scuiBufferSize );
}
}
//------------------------------------------------------------------------------
int CStream::setvbuf( char* buffer, int type, size_t size )
{
int retval = 0; // assume good return
if( this == 0 )
{
errno = EINVAL;
return -1;
}
//(1) Make sure type is one of the three legal values.
//(2) If we are buffering, make sure size is between 2 and INT_MAX.
if( !( ( type == m_scusIONoBuffering ) || ( type == m_scusIOFullBuffering ) || ( type == m_scusIOLineBuffering ) ) )
{
errno = EINVAL;
return -1;
}
if( ( type == m_scusIOFullBuffering ) || ( type == m_scusIOLineBuffering ) )
{
if( !( ( 2 <= size ) && ( size <= INT_MAX ) ) )
{
errno = EINVAL;
return -1;
}
}
size &= (size_t)~1;//force size to be even by masking down to the nearest multiple of 2
flockfile();//Lock the file
__try
{
_flush();//Flush the current buffer and free it, if it is ours.
_freebuf();
retval = SetVBuffering( buffer, type, size );
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
void CStream::_getbuf()
{
GetBuffer();
}
//------------------------------------------------------------------------------
void CStream::_freebuf()
{
FreeBuffer();
}
//------------------------------------------------------------------------------
int CStream::fclose( void )
{
int result = EOF;
if( this == 0 )
{
errno = EINVAL;
return EOF;
}
if( IsBufferString() )// If stream is a string, simply clear flag and return EOF
{
SetBufferFlags( 0 );
}
else // Stream is a real file.
{
flockfile();
__try
{
result = _fclose_nolock();
}
__finally
{
funlockfile();
}
}
return result;
}
//------------------------------------------------------------------------------
int CStream::_fclose_nolock()
{
int result = EOF;
if( this == 0 )
{
errno = EINVAL;
return EOF;
}
if( IsInUse() )
{
// Stream is in use:
//(1) flush stream
//(2) free the buffer
//(3) close the file
//(4) delete the file if temporary
result = _flush();
_freebuf();
if( _close( _fileno() ) < 0 )
{
result = EOF;
}
else if( IsTmpFileName() )
{
//temporary file (i.e., one created by tmpfile() call).
//delete, if necessary (don't have to on Windows NT because it was done by the system when the handle was closed). also, free up the heap block holding the pathname.
free( GetTmpFileName() );
SetTmpFileName( nullptr );
}
}
SetBufferFlags( 0 );
return result;
}
//------------------------------------------------------------------------------
int CStream::_close( int fh )
{
int r = 0;
//_CHECK_FH_CLEAR_OSSERR_RETURN( fh, EBADF, -1 );
//_VALIDATE_CLEAR_OSSERR_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, -1);
//_VALIDATE_CLEAR_OSSERR_RETURN((_osfile(fh) & FOPEN), EBADF, -1);
flockfile();
__try
{
if( IsOpen() )
{
r = _close_nolock( fh );
}
else
{
errno = EBADF;
r = -1;
//assert(("Invalid file descriptor. File possibly closed by a different thread",0));
}
}
__finally
{
funlockfile();
}
return r;
}
//------------------------------------------------------------------------------
int CStream::_close_nolock( int fh )
{
//unsigned long dosretval;
/* Close the underlying OS file handle. Special cases:
* 1. If _get_osfhandle(fh) is INVALID_HANDLE_VALUE, don't try
* to actually close it. Just reset the lowio info so the
* handle can be reused. The standard handles are setup like
* this in Windows app, or a background app.
* 2. If fh is STDOUT or STDERR, and if STDOUT and STDERR are
* mapped to the same OS file handle, skip the CloseHandle
* is skipped (without error). STDOUT and STDERR are the only
* handles for which this support is provided. Other handles
* are mapped to the same OS file handle only at the
* programmer's risk.
*/
if( _fileno() > 2 )
{
delete m_pStreamDevice;
m_pStreamDevice = 0;
CDOSError::MapError( m_ErrorHelper.GetLastError() );
}
nsQOR::IRole::ref_type Role = CWin32Application::TheWin32Application()->GetRole();
CStandardIO* pStandardIO = Role->GetSubSystem( CStandardIO::ClassID() ).As< CStandardIO >();
if( pStandardIO )
{
pStandardIO->FreeHandle( _fileno() );
}
SetFlags( 0 ); //clear file flags
/*
if( dosretval )
{
// OS error
return -1;
}
*/
return 0;
}
//------------------------------------------------------------------------------
void CStream::rewind( void )
{
int fd;
if( this == NULL )
{
return;
}
fd = _fileno();
// Lock the file
flockfile();
__try
{
// Flush the stream
_flush();
// Clear errors
ClearBufferErrorFlags();
ClearCtrlZ();
// Set flags
// [note: _flush set _cnt=0 and _ptr=_base]
ClearBufferReadAndWrite();
// Position to beginning of file
if( _lseek( fd, 0L, 0 ) == -1 )
{
ClearBufferErrorFlags();
}
}
__finally
{
// unlock stream
funlockfile();
}
}
//------------------------------------------------------------------------------
int CStream::fgetpos( fpos_t* pos )
{
if( this == 0 || pos == 0 )
{
errno = EINVAL;
return -1;
}
if( ( *pos = _ftelli64() ) != -1i64 )
{
return( 0 );
}
else
{
return( -1 );
}
}
//------------------------------------------------------------------------------
int CStream::fsetpos( const fpos_t* pos )
{
if( this == NULL || pos == NULL )
{
errno = EINVAL;
return -1;
}
return( _fseeki64( *pos, SEEK_SET ) );
}
//------------------------------------------------------------------------------
int CStream::fseek( long int offset, int whence )
{
return fseeko( static_cast< off_t >( offset ), whence );
}
//------------------------------------------------------------------------------
int CStream::fseeko( off_t offset, int whence )
{
return _fseeki64( static_cast< Cmp__int64 >( offset ), whence );
}
//------------------------------------------------------------------------------
int CStream::_fseeki64( Cmp__int64 offset, int whence )
{
int retval = 0;
if( this == 0 )
{
errno = EINVAL;
return -1;
}
if( !( ( whence == SEEK_SET ) || ( whence == SEEK_CUR ) || ( whence == SEEK_END ) ) )
{
errno = EINVAL;
return -1;
}
flockfile();
__try
{
retval = _fseeki64_nolock( offset, whence );
}
__finally
{
funlockfile();
}
return( retval );
}
//------------------------------------------------------------------------------
int CStream::_fseeki64_nolock( Cmp__int64 offset, int whence )
{
assert( this != 0 );
if( !IsInUse() || ( ( whence != SEEK_SET ) && ( whence != SEEK_CUR ) && ( whence != SEEK_END ) ) )
{
errno = EINVAL;
return -1;
}
// Clear EOF flag
ClearBufferEOF();
// If seeking relative to current location, then convert to a seek relative to beginning of file. This accounts for buffering, etc. by letting ftell() tell us where we are.
if( whence == SEEK_CUR )
{
offset += _ftelli64_nolock();
whence = SEEK_SET;
}
// Flush buffer as necessary
_flush();
BufferPrepare(); // If file opened for read/write, clear flags since we don't know what the user is going to do next. If the file was opened for read access only, decrease _bufsiz so that the next _filbuf won't cost quite so much
// Seek to the desired locale and return.
return( _lseeki64( _fileno(), offset, whence ) == -1i64 ? -1 : 0 );
}
//------------------------------------------------------------------------------
long int CStream::ftell( void )
{
return static_cast< long >( ftello() );
}
//------------------------------------------------------------------------------
off_t CStream::ftello()
{
off_t retval = 0;
if( this == 0 )
{
errno = EINVAL;
return -1;
}
flockfile();
__try
{
retval = _ftell_nolock();
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
long CStream::_ftell_nolock()
{
unsigned int offset;
long filepos;
byte* p;
byte* max;
int fd;
unsigned int rdcnt;
char tmode;
if( this == 0 )
{
errno = EINVAL;
return -1;
}
fd = _fileno();
NormalizeCount();
if( ( filepos = _lseek( fd, 0L, SEEK_CUR ) ) < 0L )
{
return( -1L );
}
// _lseek validates fd, so it's now ok to retrieve the textmode
tmode = GetTextMode();
if( !IsBigBuffer() ) // _IONBF or no buffering designated
{
return( filepos - Count() );
}
offset = (unsigned)( BufferOffset() );
if( IsBufferReadWrite() )
{
if( tmode == __IOINFO_TM_UTF8 && BufferContainsTranslations() )
{
size_t curpos = (size_t)( BufferOffset() ) / sizeof( wchar_t );
if( Count() == 0 )
{
return filepos;
}
else
{
unsigned long bytes_read;
byte buf[ m_scuiInternalBufferSize ];
__int64 basepos = _lseeki64( fd, GetStartPos(), SEEK_SET );
if( basepos != GetStartPos() )
{
return ( -1 );
}
if( !m_pStreamDevice->Read( buf, m_scuiInternalBufferSize, &bytes_read, 0 ) )
{
return ( -1 );
}
if( _lseek( fd, filepos, SEEK_SET ) < 0 )
{
return -1;
}
if( curpos > bytes_read )
{
return ( -1 );
}
p = buf;
while( curpos-- && ( p < buf + bytes_read ) )
{
if( *p == CR )
{
// *p is CR, so must check next char for LF
if( p < buf + bytes_read - 1 )
{
if( *( p + 1 ) == LF )
{
p++;
}
}
}
else
{
p += utf8_no_of_trailbytes( *p );
}
p++;
}
return (long)( basepos + (size_t)( p - buf ) );
}
}
if( GetIsTextMode() )
{
for( p = GetBufferBasePointer(); p < (byte*)GetPointerIntoBuffer(); p++ )
{
if( *p == '\n' ) // adjust for '\r'
{
offset++;
}
}
}
}
else
{
errno = EINVAL;
return( -1L );
}
if( filepos == 0L )
{
return( (long)offset );
}
if( IsBufferRead() )
{
if( Count() == 0 ) // filepos holds correct location
{
offset = 0;
}
else
{
// Subtract out the number of unread bytes left in the buffer.
// [We can't simply use _iob[]._bufsiz because the last read may have hit EOF and, thus, the buffer was not completely filled.]
rdcnt = Count() + (unsigned)( BufferOffset() );
// If text mode, adjust for the cr/lf substitution. If binary mode, we're outta here.
if( GetIsTextMode() )
{
// (1) If we're not at eof, simply copy _bufsiz onto rdcnt to get the # of untranslated chars read.
// (2) If we're at eof, we must look through the buffer expanding the '\n' chars one at a time.
// [NOTE: Performance issue -- it is faster to do the two _lseek() calls than to blindly go through and expand the '\n' chars regardless of whether we're at eof or not.]
if( _lseek( fd, 0L, SEEK_END ) == filepos )
{
max = GetBufferBasePointer() + rdcnt;
for( p = GetBufferBasePointer(); p < max; p++ )
{
if( *p == '\n' )
{
rdcnt++;// adjust for '\r'
}
}
// If last byte was ^Z, the lowio read didn't tell us about it. Check flag and bump count, if necessary.
if( IsCtrlZ() )
{
++rdcnt;
}
}
else
{
if( _lseek( fd, filepos, SEEK_SET ) < 0 )
{
return ( -1 );
}
/* We want to set rdcnt to the number of bytes originally read into the stream buffer (before crlf->lf translation).
In most cases, this will just be _bufsiz. However, the buffer size may have been changed, due to fseek optimization,
at the END of the last _filbuf call. */
if( ( rdcnt <= _SMALL_BUFSIZ ) && ( IsMyBuffer() ) && !( IsVBuffer() ) )
{
// The translated contents of the buffer is small and we are not at eof. The buffer size must have been set to _SMALL_BUFSIZ during the last _filbuf call.
rdcnt = _SMALL_BUFSIZ;
}
else
{
rdcnt = GetBufferSize();
}
// If first byte in untranslated buffer was a '\n', assume it was preceeded by a '\r' which was discarded by the previous read operation and count the '\n'.
if( IsCRLF() )
{
++rdcnt;
}
}
if( tmode == __IOINFO_TM_UTF8 )
{
rdcnt /= sizeof( wchar_t );
}
}
filepos -= (long)rdcnt;
}
}
if( tmode == __IOINFO_TM_UTF8 )
{
offset /= sizeof( wchar_t );
}
return( filepos + (long)offset );
}
//------------------------------------------------------------------------------
Cmp__int64 CStream::_ftelli64()
{
Cmp__int64 retval = 0;
if( this == 0 )
{
errno = EINVAL;
return -1;
}
flockfile();
__try
{
retval = _ftelli64_nolock();
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
Cmp__int64 CStream::_ftelli64_nolock()
{
size_t offset;
Cmp__int64 filepos;
byte* p;
byte* max;
int fd;
size_t rdcnt;
char tmode;
assert( this != 0 );
fd = _fileno();
NormalizeCount();
if( ( filepos = _lseeki64( fd, 0i64, SEEK_CUR ) ) < 0L )
{
return( -1i64 );
}
// _lseek164 validates fd, so it's now ok to retrieve the textmode
tmode = GetTextMode();
if( !IsBigBuffer() ) // _IONBF or no buffering designated
{
return( filepos - Count() );
}
offset = (size_t)( BufferOffset() );
if( IsBufferReadWrite() )
{
if( tmode == __IOINFO_TM_UTF8 && BufferContainsTranslations() )
{
size_t curpos = (size_t)( BufferOffset() ) / sizeof( wchar_t );
if( Count() == 0 )
{
return filepos;
}
else
{
unsigned long bytes_read;
byte buf[ m_scuiInternalBufferSize ];
__int64 basepos = _lseeki64( fd, GetStartPos(), SEEK_SET );
if( basepos != GetStartPos() )
{
return ( -1 );
}
if( !m_pStreamDevice->Read( buf, m_scuiInternalBufferSize, &bytes_read, 0 ) )
{
return ( -1 );
}
if( _lseeki64( fd, filepos, SEEK_SET ) < 0 )
{
return -1;
}
if( curpos > bytes_read )
{
return ( -1 );
}
p = buf;
while( curpos-- && ( p < buf + bytes_read ) )
{
if( *p == CR )
{
// *p is CR, so must check next char for LF
if( p < buf + bytes_read - 1 )
{
if( *( p + 1 ) == LF )
{
p++;
}
}
}
else
{
p += utf8_no_of_trailbytes( *p );
}
p++;
}
return basepos + (size_t)( p - buf );
}
}
if( GetIsTextMode() )
{
for( p = GetBufferBasePointer() ; p < (byte*)GetPointerIntoBuffer(); p++ )
{
if( *p == '\n' ) // adjust for '\r'
{
offset++;
}
}
}
}
else if( !( IsBufferReadWrite() ) )
{
errno = EINVAL;
return ( -1i64 );
}
if( filepos == 0i64 )
{
return( (__int64)offset );
}
if( IsBufferRead() )
{
if( Count() == 0 ) // filepos holds correct location
{
offset = 0;
}
else
{
/* Subtract out the number of unread bytes left in the buffer. [We can't simply use _iob[]._bufsiz because
the last read may have hit EOF and, thus, the buffer was not completely filled.] */
rdcnt = Count() + (size_t)( BufferOffset() );
// If text mode, adjust for the cr/lf substitution. If binary mode, we're outta here.
if( GetIsTextMode() )
{
/* (1) If we're not at eof, simply copy _bufsiz onto rdcnt to get the # of untranslated
chars read. (2) If we're at eof, we must look through the buffer expanding the '\n'
chars one at a time. */
/* [NOTE: Performance issue -- it is faster to do the two _lseek() calls than to blindly go
through and expand the '\n' chars regardless of whether we're at eof or not.] */
if( _lseeki64( fd, 0i64, SEEK_END ) == filepos )
{
max = GetBufferBasePointer() + rdcnt;
for( p = GetBufferBasePointer(); p < max; p++ )
{
if( *p == '\n' )
{ // adjust for '\r'
rdcnt++;
}
}
// If last byte was ^Z, the lowio read didn't tell us about it. Check flag and bump count, if necessary.
if( IsCtrlZ() )
{
++rdcnt;
}
}
else
{
if( _lseeki64( fd, filepos, SEEK_SET ) < 0 )
{
return ( -1 );
}
/* We want to set rdcnt to the number of bytes originally read into the
stream buffer (before crlf->lf translation). In most cases, this
will just be _bufsiz. However, the buffer size may have been changed,
due to fseek optimization, at the END of the last _filbuf call. */
if( ( rdcnt <= _SMALL_BUFSIZ ) && ( IsMyBuffer() ) && !( IsVBuffer() ) )
{
// The translated contents of the buffer is small and we are not at eof. The buffer size must have been set to _SMALL_BUFSIZ during the last _filbuf call.
rdcnt = _SMALL_BUFSIZ;
}
else
{
rdcnt = GetBufferSize();
}
// If first byte in untranslated buffer was a '\n', assume it was preceeded by a '\r' which was discarded by the previous read operation and count the '\n'.
if( IsCRLF() )
{
++rdcnt;
}
}
}
if( tmode == __IOINFO_TM_UTF8 )
{
rdcnt /= sizeof( wchar_t );
}
filepos -= (__int64)rdcnt;
}
}
if( tmode == __IOINFO_TM_UTF8 )
{
offset /= sizeof( wchar_t );
}
return( filepos + (__int64)offset );
}
//------------------------------------------------------------------------------
Cmp__int64 CStream::_lseeki64( int fh, Cmp__int64 pos, int mthd )
{
__int64 r = -1i64;
//_CHECK_FH_CLEAR_OSSERR_RETURN( fh, EBADF, -1i64 );
//_VALIDATE_CLEAR_OSSERR_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, -1i64);
if( !( IsOpen() ) )
{
errno = EBADF;
return -1i64;
}
flockfile();
__try
{
// make sure the file is open (after locking)
if( IsOpen() )
{
r = _lseeki64_nolock( fh, pos, mthd ); /* seek */
}
else
{
errno = EBADF;
_set_doserrno( 0 ); // not OS error
r = -1i64;
//assert(("Invalid file descriptor. File possibly closed by a different thread",0));
}
}
__finally
{
funlockfile();
}
return r;
}
//------------------------------------------------------------------------------
Cmp__int64 CStream::_lseeki64_nolock( int fh, Cmp__int64 pos, int mthd )
{
Cmp__int64 i64Result = m_pStreamDevice->Seek( pos, mthd );
ClearCtrlZ();
return i64Result;
}
//------------------------------------------------------------------------------
long CStream::_lseek( int fh, long pos, int mthd )
{
int r = 0;
//_CHECK_FH_CLEAR_OSSERR_RETURN( fh, EBADF, -1 );
//_VALIDATE_CLEAR_OSSERR_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, -1);
if( !( IsOpen() ) )
{
errno = EBADF;
return -1;
}
flockfile();
__try
{
if( IsOpen() )
{
r = _lseek_nolock( fh, pos, mthd );
}
else
{
errno = EBADF;
_set_doserrno( 0 );
r = -1;
//assert(("Invalid file descriptor. File possibly closed by a different thread",0));
}
}
__finally
{
funlockfile();
}
return r;
}
//------------------------------------------------------------------------------
long CStream::_lseek_nolock( int fh, long pos, int mthd )
{
LARGE_INTEGER large_pos; // file position
Cmp__int64 saved_pos; // original file position
Cmp__int64 new_pos; // new file position
// tell o.s. to seek
large_pos.QuadPart = 0;
// Save the current file pointer
saved_pos = m_pStreamDevice->Tell();
if( saved_pos == -1 )
{
return -1;
}
new_pos = m_pStreamDevice->Seek( pos, mthd );
if( new_pos == -1 )
{
return -1;
}
large_pos.QuadPart = new_pos;
// The call succeeded, but the new file pointer location is too large for the return type or a negative value.
// So, restore file pointer to saved location and return error.
if( large_pos.u.HighPart != 0 )
{
m_pStreamDevice->Seek( saved_pos, File_Begin );
errno = EINVAL;
return -1;
}
ClearCtrlZ(); // clear the ctrl-z flag on the file
return static_cast< long >( new_pos ); // return
}
//------------------------------------------------------------------------------
int __cdecl _winput_l( CStream* _File, const wchar_t*, _locale_t _Locale, va_list _ArgList )
{
return 0;
}
//------------------------------------------------------------------------------
int __cdecl _input_s_l( CStream* _File, const unsigned char*, _locale_t _Locale, va_list _ArgList )
{
return 0;
}
//--------------------------------------------------------------------------------
int __cdecl _winput_s_l( CStream* _File, const wchar_t*, _locale_t _Locale, va_list _ArgList )
{
return 0;
}
//--------------------------------------------------------------------------------
int __cdecl _woutput( const wchar_t* format, va_list argptr )
{
return 0;//OutputW( format, 0, false, false, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _woutput_l( CStream* pStream, const wchar_t* format, localeinfo_struct* plocinfo, va_list argptr )
{
return 0;//OutputW( format, plocinfo, false, false, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _woutput_p( CStream* pStream, const wchar_t* format, va_list argptr )
{
return 0;//OutputW( format, 0, false, true, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _woutput_p_l( CStream* pStream, const wchar_t* format, localeinfo_struct* plocinfo, va_list argptr )
{
return 0;//OutputW( format, plocinfo, false, true, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _woutput_s( CStream* pStream, const wchar_t* format, va_list argptr )
{
return 0;//OutputW( format, 0, true, false, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _woutput_s_l( CStream* pStream, const wchar_t* format, localeinfo_struct* plocinfo, va_list argptr )
{
return 0;//OutputW( format, plocinfo, true, false, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _output( CStream* pStream, const char* format, va_list argptr )
{
return 0;//OutputA( format, 0, false, false, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _output_l( CStream* pStream, const char* format, localeinfo_struct* plocinfo, va_list argptr )
{
return 0;//OutputA( format, plocinfo, false, false, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _output_p( CStream* pStream, const char* format, va_list argptr )
{
return 0;//OutputA( format, 0, false, true, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _output_p_l( CStream* pStream, const char* format, localeinfo_struct* plocinfo, va_list argptr )
{
return 0;//OutputA( format, plocinfo, false, true, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _output_s( CStream* pStream, const char* format, va_list argptr )
{
return 0;//OutputA( format, 0, true, false, argptr );
}
//--------------------------------------------------------------------------------
int __cdecl _output_s_l( CStream* pStream, const char* format, localeinfo_struct* plocinfo, va_list argptr )
{
return 0;//OutputA( format, plocinfo, true, false, argptr );
}
//------------------------------------------------------------------------------
int CStream::fprintf( const char* format, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::fprintf_s( const char* format, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::fscanf( const char* format, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::fscanf_s( const char* format, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::vfprintf( const char* format, va_list arg )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::vfprintf_s( const char* format, va_list arg )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::vfscanf( const char* format, va_list arg )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fwprintf_l( const wchar_t* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fwprintf_p( const wchar_t* format, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fwprintf_p_l( const wchar_t* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fwprintf_s_l( const wchar_t* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fwscanf_l( const wchar_t* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fwscanf_s_l( const wchar_t* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fscanf_l( const char* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fscanf_s_l( const char* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fprintf_l( const char* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fprintf_p( const char* format, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fprintf_p_l( const char* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_fprintf_s_l( const char* format, ::locale_t locale, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::fwprintf( const wchar_t* format, ... )
{
int iResult = 0;
va_list args;
va_start(args, format);
iResult = vfwprintf(format, args);
va_end(args);
return iResult;
}
//------------------------------------------------------------------------------
int CStream::fwscanf( const wchar_t* format, va_list vargs )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::vfwprintf( const wchar_t* format, va_list arg )
{
return vfwprintf_helper( _woutput_l, format, 0, arg );
}
//------------------------------------------------------------------------------
int CStream::vfwscanf( const wchar_t* format, va_list arg )
{
return vfwscanf_fn( _winput_l, format, 0, arg );
}
//------------------------------------------------------------------------------
int CStream::fwprintf_s( const wchar_t* format, va_list vargs )
{
return _vfwprintf_s_l( format, 0, vargs );
}
//------------------------------------------------------------------------------
int CStream::fwscanf_s( const wchar_t* format, va_list vargs )
{
return vfwscanf_fn( _winput_s_l, format, 0, vargs );
}
//------------------------------------------------------------------------------
int CStream::vfwprintf_s( const wchar_t* format, va_list arg )
{
return vfwprintf_helper( _woutput_s_l, format, 0, arg );
}
//------------------------------------------------------------------------------
int CStream::_vfprintf_l( const char* format, ::locale_t locale, va_list argptr )
{
return vfprintf_helper( _output_l, format, locale, argptr );
}
//------------------------------------------------------------------------------
int CStream::_vfprintf_p( const char* format, va_list argptr )
{
return vfprintf_helper( _output_p_l, format, 0, argptr );
}
//------------------------------------------------------------------------------
int CStream::_vfprintf_p_l( const char* format, ::locale_t locale, va_list argptr )
{
return vfprintf_helper( _output_p_l, format, locale, argptr );
}
//------------------------------------------------------------------------------
int CStream::_vfprintf_s_l( const char* format, ::locale_t locale, va_list argptr )
{
return vfprintf_helper( _output_s_l, format, locale, argptr );
}
//------------------------------------------------------------------------------
int CStream::_vfwprintf_l( const wchar_t* format, ::locale_t locale, va_list argptr )
{
return vfwprintf_helper( _woutput_l, format, locale, argptr );
}
//------------------------------------------------------------------------------
int CStream::_vfwprintf_p( const wchar_t* format, va_list argptr )
{
return vfwprintf_helper( _woutput_p_l, format, 0, argptr );
}
//------------------------------------------------------------------------------
int CStream::_vfwprintf_p_l( const wchar_t* format, ::locale_t locale, va_list argptr )
{
return vfwprintf_helper( _woutput_p_l, format, locale, argptr );
}
//------------------------------------------------------------------------------
int CStream::_vfwprintf_s_l( const wchar_t* format, ::locale_t locale, va_list argptr )
{
return vfwprintf_helper( _woutput_s_l, format, locale, argptr );
}
//------------------------------------------------------------------------------
int CStream::vfwprintf_helper( WOUTPUTFN woutfn, const wchar_t* format, _locale_t plocinfo, va_list ap )
{
int buffing;
int retval = 0;
if( this == NULL || format == NULL )
{
errno = EINVAL;
return -1;
}
flockfile();
__try
{
buffing = _stbuf();
CStreamFormatter formatter(this);
retval = formatter.OutputW_l(format, ap);
//retval = woutfn( this, format, plocinfo, ap );
_ftbuf( buffing );
}
__finally
{
funlockfile();
}
return( retval );
}
//------------------------------------------------------------------------------
int CStream::vfprintf_helper( OUTPUTFN outfn, const char* format, _locale_t plocinfo, va_list ap )
{
int buffing;
int retval = 0;
if( this == NULL || format == NULL )
{
errno = EINVAL;
return -1;
}
flockfile();
__try
{
int fn;
if( !( ( IsBufferString() ) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && !IsUnicode() ) ) ) )
{
errno = EINVAL;
retval = -1;
}
if( retval == 0 )
{
buffing = _stbuf();
retval = outfn( this, format, plocinfo, ap );
_ftbuf( buffing );
}
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
int CStream::vfwscanf_fn( WINPUTFN winputfn, const wchar_t* format, _locale_t plocinfo, va_list arglist )
{
int retval = 0;
if( this == NULL || format == NULL )
{
errno = EINVAL;
return EOF;
}
flockfile();
__try
{
retval = ( winputfn( this, format, plocinfo, arglist ) );
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
int CStream::_fgetc_nolock()
{
return ( DecrementBufferCount() >= 0 ? 0xff & GetNextChar() : _filbuf() );
}
//------------------------------------------------------------------------------
int CStream::_fputc_nolock( int _c )
{
return ( DecrementBufferCount() >= 0 ? 0xff & ( PutNextChar((char)_c) ) : _flsbuf( _c ) );
}
//------------------------------------------------------------------------------
int CStream::_getc_nolock()
{
return _fgetc_nolock();
}
//------------------------------------------------------------------------------
int CStream::_putc_nolock( int _c )
{
return _fputc_nolock( _c );
}
//------------------------------------------------------------------------------
//#define _getchar_nolock() _getc_nolock(stdin)
//#define _putchar_nolock(_c) _putc_nolock((_c),stdout)
//#define _getwchar_nolock() _getwc_nolock(stdin)
//#define _putwchar_nolock(_c) _putwc_nolock((_c),stdout)
//------------------------------------------------------------------------------
int CStream::fgetc( void )
{
int retval = 0;
if( this == NULL )
{
errno = EINVAL;
return EOF;
}
flockfile();
__try
{
int fn;
if( !( ( IsBufferString()) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && !IsUnicode() ) ) ) )
{
errno = EINVAL;
retval = EOF;
}
if( retval == 0 )
{
retval = _getc_nolock();
}
}
__finally
{
funlockfile();
}
return( retval );
}
//------------------------------------------------------------------------------
char* CStream::fgets( char* string, int count )
{
char* pointer = string;
char* retval = string;
int ch;
if( this == NULL || string == NULL || count <= 0 )
{
errno = EINVAL;
return NULL;
}
// The C Standard states the input buffer should remain unchanged if EOF is encountered immediately. Hence we do not blank out the input buffer here
flockfile();
__try
{
int fn;
if( !( ( IsBufferString() ) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && !IsUnicode() ) ) ) )
{
errno = EINVAL;
retval = NULL;
}
if( retval != NULL )
{
while( --count )
{
if( ( ch = _fgetc_nolock() ) == EOF )
{
if( pointer == string )
{
retval = NULL;
goto done;
}
break;
}
if( ( *pointer++ = (char)ch ) == '\n' )
{
break;
}
}
*pointer = '\0';
}
done:;
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
int CStream::fputc( int ch )
{
int retval = 0;
if( this == NULL )
{
errno = EINVAL;
return EOF;
}
flockfile();
__try
{
int fn;
if( !( ( IsBufferString() ) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && !IsUnicode() ) ) ) )
{
errno = EINVAL;
retval = EOF;
}
if( retval == 0 )
{
retval = _putc_nolock( ch );
}
}
__finally
{
funlockfile();
}
return( retval );
}
//------------------------------------------------------------------------------
int CStream::fputs( const char* string )
{
int buffing;
size_t length;
size_t ndone = 0;
if( string == NULL || this == NULL )
{
errno = EINVAL;
return EOF;
}
int fn;
if( !( ( IsBufferString() ) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && !IsUnicode() ) ) ) )
{
errno = EINVAL;
return EOF;
}
length = strlen( string );
flockfile();
__try
{
buffing = _stbuf();
ndone = _fwrite_nolock( string, 1, length );
_ftbuf( buffing );
}
__finally
{
funlockfile();
}
return( ndone == length ? 0 : EOF );
}
//------------------------------------------------------------------------------
int CStream::getc( void )
{
int retval = 0;
if( this == NULL )
{
errno = EINVAL;
return EOF;
}
flockfile();
__try
{
int fn;
if( !( ( IsBufferString()) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && !IsUnicode() ) ) ) )
{
errno = EINVAL;
retval = EOF;
}
if( retval == 0 )
{
retval = _getc_nolock();
}
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
int CStream::getc_unlocked( void )
{
return _getc_nolock();
}
//------------------------------------------------------------------------------
ssize_t CStream::getdelim( char**, size_t*, int )
{
return 0;
}
//------------------------------------------------------------------------------
ssize_t CStream::getline( char**, size_t* )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::putc( int ch )
{
int retval = 0;
if( this == NULL )
{
errno = EINVAL;
return EOF;
}
flockfile();
__try
{
int fn;
if( !( ( IsBufferString() ) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && !IsUnicode() ) ) ) )
{
errno = EINVAL;
retval = EOF;
}
if( retval == 0 )
{
retval = _putc_nolock( ch );
}
}
__finally
{
funlockfile();
}
return( retval );
}
//------------------------------------------------------------------------------
int CStream::putc_unlocked( int c )
{
return _putc_nolock( c );
}
//------------------------------------------------------------------------------
int CStream::ungetc( int ch )
{
int retval = 0;
if( this == NULL )
{
errno = EINVAL;
return EOF;
}
flockfile();
__try
{
retval = _ungetc_nolock( ch );
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
int CStream::_ungetc_nolock( int ch )
{
int fn;
if( !( ( IsBufferString() ) || ( fn = _fileno(), ( ( GetTextMode() == __IOINFO_TM_ANSI ) && ! IsUnicode() ) ) ) )
{
errno = EINVAL;
return EOF;
}
// Stream must be open for read and can NOT be currently in write mode. Also, ungetc() character cannot be EOF.
if( ( ch == EOF ) || !( ( IsBufferRead() ) || ( ( IsBufferReadWrite() ) && !( IsBufferWrite() ) ) ) )
{
return EOF;
}
return BufferUngetChar( ch );
}
//------------------------------------------------------------------------------
int CStream::_putw( int binint )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::_getw( void )
{
return 0;
}
//------------------------------------------------------------------------------
wint_t CStream::fgetwc()
{
return 0;
}
//------------------------------------------------------------------------------
wchar_t* CStream::fgetws( wchar_t* s, int n )
{
return 0;
}
//------------------------------------------------------------------------------
wint_t CStream::fputwc( wchar_t c )
{
return 0;
}
//------------------------------------------------------------------------------
int CStream::fputws( const wchar_t* s )
{
return 0;
}
//------------------------------------------------------------------------------
wint_t CStream::getwc()
{
return 0;
}
//------------------------------------------------------------------------------
wint_t CStream::putwc( wchar_t c )
{
return 0;
}
//------------------------------------------------------------------------------
wint_t CStream::ungetwc( wint_t c )
{
return 0;
}
//------------------------------------------------------------------------------
wint_t CStream::_putwch_nolock( wchar_t ch )
{
unsigned long cchWritten = 0;
// write character to console file handle
CTerminal* pTerminal = CWin32Application::TheWin32Application()->GetRole()->GetSubSystem( CTerminal::ClassID() ).As< CTerminal >();
if( !pTerminal->Console()->ScreenBuffer()->Write( &ch, 1, &cchWritten ) )
{
return WEOF;
}
return ch;
}
//------------------------------------------------------------------------------
int CStream::_read_nolock( int fh, void* inputbuf, unsigned cnt )
{
int bytes_read = 0; // number of bytes read
char* buffer; // buffer to read to
int os_read; // bytes read on OS call
char *p, *q; // pointers into buffer
wchar_t *pu, *qu; // wchar_t pointers into buffer for UTF16
char peekchr; // peek-ahead character
wchar_t wpeekchr; // peek-ahead wchar_t
Cmp__int64 filepos; // file position after seek
unsigned long dosretval; // o.s. return value
char tmode; // textmode - ANSI/UTF-8/UTF-16
bool fromConsole = 0; // true when reading from console
void* buf; // buffer to read to
int retval = -2; // return value
unsigned inputsize = cnt;
//_CHECK_FH_CLEAR_OSSERR_RETURN( fh, EBADF, -1 );
//_VALIDATE_CLEAR_OSSERR_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, -1);
if( !( IsOpen() ) )
{
errno = EBADF;
return -1;
}
if( cnt > IntMax )
{
errno = EINVAL;
return -1;
}
if( cnt == 0 || ( IsFEOF() ) )
{
return 0; // nothing to read or at EOF, so return 0 read
}
if( inputbuf == NULL )
{
errno = EINVAL;
return -1;
}
tmode = GetTextMode();
switch( tmode )
{
case __IOINFO_TM_UTF8:
/* For a UTF-8 file, we need 2 buffers, because after reading we
need to convert it into UNICODE - MultiByteToWideChar doesn't do
in-place conversions. */
/* MultiByte To WideChar conversion may double the size of the
buffer required & hence we divide cnt by 2 */
/*
* Since we are reading UTF8 stream, cnt bytes read may vary
* from cnt wchar_t characters to cnt/4 wchar_t characters. For
* this reason if we need to read cnt characters, we will
* allocate MBCS buffer of cnt. In case cnt is 0, we will
* have 4 as minimum value. This will make sure we don't
* overflow for reading from pipe case.
*
*
* In this case the numbers of wchar_t characters that we can
* read is cnt/2. This means that the buffer size that we will
* require is cnt/2.
*/
// For UTF8 we want the count to be an even number
if( !( ( cnt & 1 ) == 0 ) )
{
_set_doserrno( 0 );
errno = EINVAL;
return -1;
}
cnt = ( cnt / 2 ) < 4 ? 4 : ( cnt / 2 );
buf = malloc( cnt );
if( !buf )
{
errno = ENOMEM;
_set_doserrno( CDOSError::E_nomem );
return -1;
}
SetStartPos( _lseeki64_nolock( fh, 0, File_Current ) );
break;
case __IOINFO_TM_UTF16LE:
// For UTF16 the count always needs to be an even number
if( !( ( cnt & 1 ) == 0 ) )
{
_set_doserrno( 0 );
errno = EINVAL;
return -1;
}
cnt &= ( ~1 );
// Fall Through to default
default:
// For non-UTF8 files, we need only 1 buffer - make buf point to the users input buffer
buf = inputbuf;
}
buffer = reinterpret_cast< char* >( buf );
char chPipe = 0;
ReadPipeBuffer( chPipe );
if( ( ( IsPipe() || IsDevice() ) ) && chPipe != LF && cnt != 0 )
{
// a pipe/device and pipe lookahead non-empty: read the lookahead char
*buffer++ = chPipe;
++bytes_read;
--cnt;
WritePipeBuffer( LF );
unsigned short usPipeBufferDest;
ReadPeakAheadPipeBuffer( usPipeBufferDest );
// For UTF16, there maybe one more look ahead char. For UTF8, there maybe 2 more look ahead chars
if( ( tmode != __IOINFO_TM_ANSI ) && ( LoByte( usPipeBufferDest) != LF ) && cnt != 0 )
{
*buffer++ = LoByte( usPipeBufferDest );
++bytes_read;
--cnt;
usPipeBufferDest &= ( 0xFF00 );
usPipeBufferDest |= ( LF );
if( ( tmode == __IOINFO_TM_UTF8 ) && ( HiByte(usPipeBufferDest) != LF ) && cnt != 0 )
{
*buffer++ = HiByte( usPipeBufferDest );
++bytes_read;
--cnt;
usPipeBufferDest &= ( 0x00FF );
usPipeBufferDest |= ( ((unsigned short)(LF)) << 8 );
}
}
WritePeakAheadPipeBuffer( usPipeBufferDest );
}
#if !defined(_CRT_APP) || defined(_KERNELX)
if( _isatty( fh ) && ( GetIsTextMode() ) )
{
unsigned long dwMode;
CTerminal* pTerminal = CWin32Application::TheWin32Application()->GetRole()->GetSubSystem( CTerminal::ClassID() ).As< CTerminal >();
fromConsole = pTerminal->Console()->ScreenBuffer()->GetInputMode( dwMode );
}
// read the data from Console
if( fromConsole && ( tmode == __IOINFO_TM_UTF16LE ) )
{
CTerminal* pTerminal = CWin32Application::TheWin32Application()->GetRole()->GetSubSystem( CTerminal::ClassID() ).As< CTerminal >();
if( !pTerminal->Console()->ScreenBuffer()->Read( buffer, cnt / 2, reinterpret_cast< unsigned long* >( &os_read ), 0 ) )
{
CDOSError::MapError( m_ErrorHelper.GetLastError() );
retval = -1;
goto error_return;
}
os_read *= 2; // In UTF16 mode, ReadConsoleW returns the actual number of wchar_t's read,
// so we make sure we update os_read accordingly
}
// read the data
else
#endif /* !defined(_CRT_APP) || defined(_KERNELX) */
if( !m_pStreamDevice->Read( buffer, cnt, reinterpret_cast< unsigned long* >( &os_read ), 0 ) || os_read < 0 || (size_t)os_read > cnt )
{
/* ReadFile has reported an error. recognize two special cases.
*
* 1. map ERROR_ACCESS_DENIED to EBADF
*
* 2. just return 0 if ERROR_BROKEN_PIPE has occurred. it
* means the handle is a read-handle on a pipe for which
* all write-handles have been closed and all data has been
* read. */
if( ( dosretval = m_ErrorHelper.GetLastError() ) == ErrorAccessDenied )
{
// wrong read/write mode should return EBADF, not EACCES
errno = EBADF;
_set_doserrno( dosretval );
retval = -1;
goto error_return;
}
else if( dosretval == ErrorBrokenPipe )
{
retval = 0;
goto error_return;
}
else
{
CDOSError::MapError( m_ErrorHelper.GetLastError() );
retval = -1;
goto error_return;
}
}
bytes_read += os_read; // update bytes read
if( GetIsTextMode() )
{
// now must translate CR-LFs to LFs in the buffer
// For ANSI & UTF8, we read byte by byte. For UTF16, we need to read 2 bytes (wchar_t's) at a time
if( tmode != __IOINFO_TM_UTF16LE )
{
// set CRLF flag to indicate LF at beginning of buffer
if( ( os_read != 0 ) && ( *(char*)buf == LF ) )
{
SetCRLF();
}
else
{
ClearCRLF();
}
// convert chars in the buffer: p is src, q is dest
p = q = reinterpret_cast< char* >( buf );
while( p < (char *)buf + bytes_read )
{
if( *p == CTRLZ )
{
// if fh is not a device, set ctrl-z flag
if( !( IsDevice() ) )
{
SetFEOF();
}
else
{
*q++ = *p++;
}
break; // stop translating
}
else if( *p != CR )
{
*q++ = *p++;
}
else
{
// *p is CR, so must check next char for LF
if( p < (char *)buf + bytes_read - 1 )
{
if( *( p + 1 ) == LF )
{
p += 2;
*q++ = LF; // convert CR-LF to LF
}
else
{
*q++ = *p++; // store char normally
}
}
else
{
// This is the hard part. We found a CR at end of buffer. We must peek ahead to see if next char is an LF.
++p;
dosretval = 0;
if( !m_pStreamDevice->Read( &peekchr, 1, reinterpret_cast< unsigned long* >( &os_read ), 0 ) )
{
dosretval = m_ErrorHelper.GetLastError();
}
if( dosretval != 0 || os_read == 0 )
{
// couldn't read ahead, store CR
*q++ = CR;
}
else
{
/*
* peekchr now has the extra character -- we now
* have several possibilities:
*
* 1. disk file and char is not LF; just seek
* back and copy CR
* 2. disk file and char is LF; seek back and
* discard CR
* 3. disk file, char is LF but this is a
* one-byte read: store LF, don't seek back
* 4. pipe/device and char is LF; store LF.
* 5. pipe/device and char isn't LF, store CR
* and put char in pipe lookahead buffer.
*/
if( IsDevice() || IsPipe() )
{
// non-seekable device
if( peekchr == LF )
{
*q++ = LF;
}
else
{
*q++ = CR;
WritePipeBuffer( peekchr );
}
}
else
{
// disk file
if( q == buf && peekchr == LF )
{
// nothing read yet; must make some progress
*q++ = LF;
}
else
{
// seek bac
filepos = _lseeki64_nolock( fh, -1i64, File_Current );
if( peekchr != LF )
{
*q++ = CR;
}
}
}
}
}
}
}
//we now change bytes_read to reflect the true number of chars in the buffer
bytes_read = (int)( q - (char*)buf );
if( ( tmode == __IOINFO_TM_UTF8 ) && ( bytes_read != 0 ) )
{
// UTF8 reads need to be converted into UTF16
--q; // q has gone beyond the last char
/* If the last byte is a standalone UTF-8 char. We then take the whole buffer. Otherwise we skip back till we come to a lead byte.
If the leadbyte forms a complete UTF-8 character will the remaining part of the buffer, then again we take the whole buffer.
If not, we skip to one byte which should be the final trail byte of the previous UTF-8 char or a standalone UTF-8 character
*/
if( _utf8_is_independent( *q ) )
{
++q;
// Final byte is standalone, we reset q, because we will now consider the full buffer which we have read
}
else
{
int ctr = 1;
int cnt_trailbytes;
while( !_utf8_is_leadbyte( *q ) && ctr <= 4 && q >= (char *)buf )
{
--q;
++ctr;
}
cnt_trailbytes = utf8_no_of_trailbytes( *q );
if( cnt_trailbytes == 0 )
{
// Should have exited the while by finding a lead byte else, the file has incorrect UTF-8 chars
errno = EILSEQ;
retval = -1;
goto error_return;
}
if( cnt_trailbytes + 1 == ctr )
{
//The leadbyte + the remaining bytes form a full set
q += ctr;
}
else
{
// Seek back
if( IsDevice() || IsPipe() )
{
// non-seekable device. Put the extra chars in _pipech & _pipech2. We would have a maximum of 3 extra chars
WritePipeBuffer( *q );
++q;
unsigned short usPipePeekBuffer = 0;
if( ctr >= 2 )
{
usPipePeekBuffer = *q;
++q;
}
if( ctr == 3 )
{
usPipePeekBuffer |= ( (unsigned short)( *q ) << 8 );
++q;
}
WritePeakAheadPipeBuffer( usPipePeekBuffer );
//We need to point q back to beyond whatever we actually took in.
q -= ctr;
}
else
{
// We have read extra chars, so we seek back
filepos = _lseeki64_nolock( fh, -ctr, FILE_CURRENT );
}
}
}
bytes_read = (int)( q - (char *)buf );
bytes_read = m_StringHelper.MultiByteToWideChar( CCodePage::UTF8, 0, reinterpret_cast< char* >( buf ), bytes_read, reinterpret_cast< wchar_t* >( inputbuf ), inputsize / 2 );
if( !bytes_read )
{
CDOSError::MapError( m_ErrorHelper.GetLastError() );
retval = -1;
goto error_return;
}
SetBufferContainsTranslations( bytes_read != (int)( q - (char *)buf ) );
// MultiByteToWideChar returns no of wchar_t's. Double it
bytes_read = bytes_read * 2;
}
}
#if !defined(_CRT_APP) || defined(_KERNELX)
// reading from console && tmode == __IOINFO_TM_UTF16LE */
else if( fromConsole )
{
pu = qu = (wchar_t *)buf;
while( pu < ( (wchar_t*)buf ) + ( bytes_read / 2 ) )
{
if( *pu == CTRLZ )
{
SetFEOF();
break; // stop translating
}
else if( *pu != CR )
{
*qu++ = *pu++;
}
else
{
// *pu is CR, so must check next wchar_t for LF
if( pu < ( (wchar_t*)buf ) + ( bytes_read / 2 ) - 1 )
{
if( *( pu + 1 ) == LF )
{
pu++;
*qu++ = LF; // convert CR-LF to LF
}
else
{
*qu++ = *pu++; // store char normally
}
}
}
}
// we now change bytes_read to reflect the true number of bytes in the buffer
bytes_read = (int)( qu - (wchar_t*)buf ) * 2;
}
#endif /* _CRT_APP */
// NOT reading from console and tmode == __IOINFO_TM_UTF16LE
else
{
// set CRLF flag to indicate LF at beginning of buffer
if( ( os_read != 0 ) && ( *(wchar_t *)buf == LF ) )
{
SetCRLF();
}
else
{
ClearCRLF();
}
// convert chars in the buffer: pu is src, qu is dest
pu = qu = (wchar_t *)buf;
while( (char *)pu < (char *)buf + bytes_read )
{
if( *pu == CTRLZ )
{
// if fh is not a device, set ctrl-z flag
if( !( IsDevice() ) )
{
SetFEOF();
}
else
{
*qu++ = *pu++;
}
break; // stop translating
}
else if( *pu != CR )
{
*qu++ = *pu++;
}
else
{
// *pu is CR, so must check next wchar_t for LF
if( (char *)pu < (char *)buf + bytes_read - 2 )
{
if( *( pu + 1 ) == LF )
{
pu += 2;
*qu++ = LF; // convert CR-LF to LF
}
else
{
*qu++ = *pu++; // store char normally
}
}
else
{
// This is the hard part. We found a CR at end of buffer. We must peek ahead to see if next wchar_t is an LF
++pu;
dosretval = 0;
if( !m_pStreamDevice->Read( &wpeekchr, 2, reinterpret_cast< unsigned long* >( &os_read ), 0 ) )
{
dosretval = m_ErrorHelper.GetLastError();
}
if( dosretval != 0 || os_read == 0 )
{
// couldn't read ahead, store CR
*qu++ = CR;
}
else
{
/* peekchr now has the extra character -- we
* now have several possibilities:
* 1. wchar_t is not LF; just seek back and
* copy CR
* 2. wchar_t is LF; seek back and discard CR
* 3. disk file, wchar_t is LF but this is a
* one-byte read: store LF, don't seek back.
*/
if( IsDevice() || IsPipe() )
{
// non-seekable device
if( wpeekchr == LF )
{
*qu++ = LF;
}
else
{
char * pwpeekchr = (char *)&wpeekchr;
*qu++ = CR;
WritePipeBuffer( *pwpeekchr );
++pwpeekchr;
unsigned short usPipeBuffer = *pwpeekchr;
usPipeBuffer |= ( (unsigned short)( LF ) << 8 );
WritePeakAheadPipeBuffer( usPipeBuffer );
}
}
else
{
if( (char*)qu == buf && wpeekchr == LF )
{
// nothing read yet; must make some progress
*qu++ = LF;
}
else
{
// seek back
filepos = _lseeki64_nolock( fh, -2, FILE_CURRENT );
if( wpeekchr != LF )
{
*qu++ = CR;
}
}
}
}
}
}
}
// we now change bytes_read to reflect the true number of chars in the buffer
bytes_read = (int)( (char*)qu - (char*)buf );
}
}
error_return:
if( buf != inputbuf )
{
free( buf );
}
return ( retval == -2 ) ? bytes_read : retval;
}
//------------------------------------------------------------------------------
size_t CStream::fread( void* ptr, size_t size, size_t nmemb )
{
return fread_s( ptr, Size_Max, size, nmemb );
}
//------------------------------------------------------------------------------
size_t CStream::_fread_nolock( void *buffer, size_t elementSize, size_t count )
{
// assumes there is enough space in the destination buffer
return _fread_nolock_s( buffer, Size_Max, elementSize, count );
}
//------------------------------------------------------------------------------
size_t CStream::fread_s( void* buffer, size_t bufferSize, size_t elementSize, size_t count )
{
size_t retval = 0;
if( elementSize == 0 || count == 0 )
{
return 0;
}
// only checking for stream == NULL here for _lock_str()
// the rest of the validation is in _fread_nolock_s()
if( this == NULL )
{
if( bufferSize != Size_Max )
{
memset( buffer, 0, bufferSize );
}
errno = EINVAL;
return 0;
}
flockfile();
__try
{
// do the read; _fread_nolock_s will make sure we do not buffer overrun
retval = _fread_nolock_s( buffer, bufferSize, elementSize, count );
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
size_t CStream::_fread_nolock_s( void *buffer, size_t bufferSize, size_t elementSize, size_t num )
{
char* data; // point inside the destination buffer to where we need to copy the read chars
size_t dataSize; // space left in the destionation buffer (in bytes)
size_t total; // total bytes to read
size_t count; // num bytes left to read
unsigned streambufsize; // size of stream buffer
unsigned nbytes; // how much to read now
unsigned nread; // how much we did read
int c; // a temp char
// initialize local vars
if( elementSize == 0 || num == 0 )
{
return 0;
}
if( buffer == NULL )
{
errno = EINVAL;
return 0;
}
data = reinterpret_cast< char* >( buffer );
dataSize = bufferSize;
if( this == NULL || num > ( Size_Max / elementSize ) )
{
if( bufferSize != Size_Max )
{
memset( buffer, 0, bufferSize );
}
if( this == NULL )
{
errno = EINVAL;
return 0;
}
if( num > ( Size_Max / elementSize ) )
{
errno = EINVAL;
return 0;
}
}
count = total = elementSize * num;
if( IsAnyBuffer() )
{
// already has buffer, use its size
streambufsize = GetBufferSize();
}
else
{
// assume will get _INTERNAL_BUFSIZ buffer
streambufsize = m_scuiInternalBufferSize;
}
// here is the main loop -- we go through here until we're done
while( count != 0 )
{
// if the buffer exists and has characters, copy them to user buffer
if( IsAnyBuffer() && GetCountOfBytesLeftInBuffer() != 0 )
{
if( GetCountOfBytesLeftInBuffer() < 0 )
{
//assert(("Inconsistent Stream Count. Flush between consecutive read and write", _cnt >= 0));
SetError();
return ( total - count ) / elementSize;
}
// how much do we want?
nbytes = ( count < (size_t)GetCountOfBytesLeftInBuffer() ) ? (unsigned)count : GetCountOfBytesLeftInBuffer();
if( nbytes > dataSize )
{
if( bufferSize != Size_Max )
{
memset( buffer, 0, bufferSize );
}
errno = ERANGE;
return 0;
//_VALIDATE_RETURN(("buffer too small", 0), ERANGE, 0)
}
ReadFromBuffer( data, dataSize, nbytes );
// update amt of data read
count -= nbytes;
data += nbytes;
dataSize -= nbytes;
}
else if( count >= streambufsize )
{
// If we have more than streambufsize chars to read, get data by calling read with an integral number of bufsiz blocks. Note that if the stream is text mode, read will return less chars than we ordered.
if( streambufsize )
{
// In 64bit apps size_t is bigger than unsigned (which is 32bit even in 64 bit machines), so we need to split the read into INT_MAX chunks
// since _read() only support up to _signed_ int (even though the in parameter is unsigned).
if( count > INT_MAX )
{
// calc chars to read -- the largest multiple of streambufsize smaller then INT_MAX
nbytes = (unsigned)( INT_MAX - INT_MAX % streambufsize );
}
else
{
// calc chars to read -- (count/streambufsize) * streambufsize
nbytes = (unsigned)( count - count % streambufsize );
}
}
else
{
nbytes = ( count > INT_MAX ) ? (unsigned)INT_MAX : (unsigned)count;
}
if( nbytes > dataSize )
{
if( bufferSize != Size_Max )
{
memset( buffer, 0, bufferSize );
}
errno = ERANGE;
return 0;
//_VALIDATE_RETURN(("buffer too small", 0), ERANGE, 0)
}
nread = _read_nolock( _fileno(), data, nbytes );
if( nread == 0 )
{
// end of file -- out of here
SetBufferEOF();
return ( total - count ) / elementSize;
}
else if( nread == (unsigned)-1 )
{
SetError();
return ( total - count ) / elementSize;
}
// update count and data to reflect read
count -= nread;
data += nread;
dataSize -= nread;
}
else
{
// less than streambufsize chars to read, so call _filbuf to fill buffer
if( ( c = _filbuf() ) == EOF )
{
// error or eof, stream flags set by _filbuf
return ( total - count ) / elementSize;
}
// _filbuf returned a char -- store it
if( dataSize == 0 )
{
if( bufferSize != Size_Max )
{
memset( buffer, 0, bufferSize );
}
errno = ERANGE;
return 0;
//_VALIDATE_RETURN(("buffer too small", 0), ERANGE, 0)
}
*data++ = (char)c;
--count;
--dataSize;
// update buffer size
streambufsize = GetBufferSize();
}
}
// we finished successfully, so just return num
return num;
}
//------------------------------------------------------------------------------
int CStream::_filbuf()
{
if( this == NULL )
{
errno = EINVAL;
return EOF;
}
if( !IsInUse() || IsBufferString() )
{
return EOF;
}
if( IsBufferWrite() )
{
SetError();
return EOF;
}
BeginRead();
// Get a buffer, if necessary.
if( !IsAnyBuffer() )
{
_getbuf();
}
else
{
SetPointerIntoBuffer( (char*)GetBufferBasePointer() );
}
SetCountOfBytesLeftInBuffer( _read( _fileno(), GetBufferBasePointer(), GetBufferSize() ) );
if( GetCountOfBytesLeftInBuffer() == 0 )
{
SetBufferEOF();
SetCountOfBytesLeftInBuffer( 0 );
return EOF;
}
if( GetCountOfBytesLeftInBuffer() == -1 )
{
SetError();
SetCountOfBytesLeftInBuffer( 0 );
return EOF;
}
if( !( ( IsBufferWrite() | IsBufferReadWrite() ) ) && ( ( _fileno() & ( FTEXT | FEOFLAG ) ) == ( FTEXT | FEOFLAG ) ) )
{
SetCtrlZ();
}
// Check for small _bufsiz (_SMALL_BUFSIZ). If it is small and if it is our buffer, then this must be the first _filbuf after
// an fseek on a read-access-only stream. Restore _bufsiz to its larger value (_INTERNAL_BUFSIZ) so that the next _filbuf call,
// if one is made, will fill the whole buffer.
if( ( GetBufferSize() == _SMALL_BUFSIZ ) && ( IsMyBuffer() ) && !( IsVBuffer() ) )
{
SetBufferSize( m_scuiInternalBufferSize );
}
DecrementBufferCount();
return( 0xff & GetNextChar() );
}
//------------------------------------------------------------------------------
int CStream::_read( int fh, void* buf, unsigned cnt )
{
int r = 0;
//_CHECK_FH_CLEAR_OSSERR_RETURN( fh, EBADF, -1 );
//_VALIDATE_CLEAR_OSSERR_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, -1);
if( !( IsOpen() ) )
{
errno = EBADF;
return -1;
}
flockfile();
__try
{
if( IsOpen() )
{
r = _read_nolock( fh, buf, cnt ); // read bytes
}
else
{
errno = EBADF;
_set_doserrno( 0 );
r = -1;
//assert(("Invalid file descriptor. File possibly closed by a different thread",0));
}
}
__finally
{
funlockfile();
}
return r;
}
//------------------------------------------------------------------------------
size_t CStream::fwrite( const void* buffer, size_t size, size_t count )
{
size_t retval = 0;
if( size == 0 || count == 0 )
{
return 0;
}
if( this == 0 )
{
errno = EINVAL;
return 0;
}
flockfile();
__try
{
retval = _fwrite_nolock( buffer, size, count );
}
__finally
{
funlockfile();
}
return retval;
}
//------------------------------------------------------------------------------
size_t CStream::_fwrite_nolock( const void* buffer, size_t size, size_t num )
{
const char* data; // point to where data comes from next
size_t total; // total bytes to write
size_t count; // num bytes left to write
unsigned bufsize; // size of stream buffer
unsigned nbytes; // number of bytes to write now
unsigned nactuallywritten; // number of bytes actually written by write() call
unsigned nwritten; // number of bytes we consider written
int c; // a temp char
if( size == 0 || num == 0 )
{
return 0;
}
if( this == 0 )
{
errno = EINVAL;
return 0;
}
if( buffer == 0 )
{
errno = EINVAL;
return 0;
}
if( num > ( Size_Max / size ) )
{
errno = EINVAL;
return 0;
}
data = reinterpret_cast< const char* >( buffer );
count = total = size * num;
if( IsAnyBuffer() ) // already has buffer, use its size
{
bufsize = GetBufferSize();
}
else
{ // assume will get _INTERNAL_BUFSIZ buffer
bufsize = _INTERNAL_BUFSIZ;
}
// here is the main loop -- we go through here until we're done
while( count != 0 )
{
// if the buffer is big and has room, copy data to buffer
if( IsBigBuffer() && GetCountOfBytesLeftInBuffer() != 0 )
{
if( GetCountOfBytesLeftInBuffer() < 0 )
{
assert( ( "Inconsistent Stream Count. Flush between consecutive read and write", GetCountOfBytesLeftInBuffer() >= 0 ) );
SetError();
return ( total - count ) / size;
}
// how much do we want?
nbytes = ( count < (unsigned)GetCountOfBytesLeftInBuffer() ) ? (unsigned)count : GetCountOfBytesLeftInBuffer();
WriteIntoBuffer( (const byte*)data, nbytes );
// update stream and amount of data written
count -= nbytes;
data += nbytes;
}
else if( count >= bufsize )
{
/* If we have more than bufsize chars to write, write data by calling write with an integral number of
bufsiz blocks. If we reach here and we have a big buffer, it must be full so _flush it. */
if( IsBigBuffer() )
{
if( _flush() )
{
// error, stream flags set -- we're outof here
return ( total - count ) / size;
}
}
// calc chars to read -- (count/bufsize) * bufsize
nbytes = ( bufsize ? (unsigned)( count - count % bufsize ) : (unsigned)count );
nactuallywritten = _write( _fileno(), data, nbytes );
if( nactuallywritten == (unsigned)EOF )
{
// error -- out of here
SetError();
return ( total - count ) / size;
}
//VSWhidbey#326224 - _write can return more bytes than we requested due unicode involved conversions in text files.
//But we do not care about how many bytes were written as long as the number is at least as big as we wanted.
nwritten = ( nactuallywritten > nbytes ? nbytes : nactuallywritten );
// update count and data to reflect write
count -= nwritten;
data += nwritten;
if( nactuallywritten < nbytes )
{
// error -- out of here
SetError();
return ( total - count ) / size;
}
}
else
{
// buffer full and not enough chars to do direct write, so do a _flsbuf.
c = *data; // _flsbuf write one char, this is it
if( _flsbuf( c ) == EOF )
{
// error or eof, stream flags set by _flsbuf
return ( total - count ) / size;
}
// _flsbuf wrote a char -- update count
++data;
--count;
// update buffer size */
bufsize = GetBufferSize() > 0 ? GetBufferSize() : 1;
}
}
// we finished successfully, so just return num
return num;
}
//------------------------------------------------------------------------------
int CStream::_flsbuf( int ch )
{
int charcount;
int written;
int fh;
assert( this != NULL );
fh = _fileno();
if( !( IsBufferRead() || IsBufferWrite() ) )
{
errno = EBADF;
SetError();
return( EOF );
}
else if( ( IsBufferString() ) )
{
errno = ERANGE;
SetError();
return( EOF );
}
/* Check that _IOREAD is not set or, if it is, then so is _IOEOF. Note that _IOREAD and IOEOF both being set implies switching from read to
write at end-of-file, which is allowed by ANSI. Note that resetting the _cnt and _ptr fields amounts to doing an fflush() on the stream
in this case. Note also that the _cnt field has to be reset to 0 for the error path as well (i.e., _IOREAD set but _IOEOF not set) as
well as the non-error path. */
if( IsBufferRead() )
{
if( IsBufferEOF() )
{
BufferFlushed();
EndRead();
}
else
{
SetCountOfBytesLeftInBuffer( 0 );
SetError();
return( EOF );
}
}
SetCountOfBytesLeftInBuffer( 0 );
BeginWrite();
ClearBufferEOF();
written = charcount = 0;
// Get a buffer for this stream, if necessary.
if( !IsAnyBuffer() )
{
/* Do NOT get a buffer if (1) stream is stdout/stderr, and
(2) stream is NOT a tty. [If stdout/stderr is a tty, we do NOT set up single char buffering. This is so that later temporary buffering will not be thwarted by the _IONBF bit being set (see _stbuf/_ftbuf usage).]
*/
if( !( ( ( this == stdout ) || ( this == stderr ) ) && ( _isatty( fh ) ) ) )
{
_getbuf();
}
}
// If big buffer is assigned to stream...
if( IsBigBuffer() )
{
//assert( ("inconsistent IOB fields", _ptr - _base >= 0 ) );
charcount = BufferOffset();
SetPointerIntoBuffer( (char*)GetBufferBasePointer() + sizeof( char ) );
SetCountOfBytesLeftInBuffer( GetBufferSize() - ( int )sizeof( char ) );
if( charcount > 0 )
{
written = _write( fh, GetBufferBasePointer(), charcount );
}
else
{
if( IsAppendMode() )
{
if( _lseeki64( fh, 0L, SEEK_END ) == -1 )
{
SetError();
return( EOF );
}
}
}
( *GetBufferBasePointer() ) = (byte)( ch );
}
else // Perform single character output (either _IONBF or no buffering)
{
charcount = sizeof( char );
written = _write( fh, &ch, charcount );
}
// See if the _write() was successful.
if( written != charcount )
{
SetError();
return( EOF );
}
return( ch & 0xff );
}
//------------------------------------------------------------------------------
int CStream::_write( int fh, const void* buf, unsigned cnt )
{
int r = 0; // return value
// validate handle
if( fh == _NO_CONSOLE_FILENO )
{
_set_doserrno( 0 );
errno = EBADF;
return -1;
}
int _Expr_val = !!( ( fh >= 0 ) );//&& (unsigned)fh < (unsigned)_nhandle));
assert( ( _Expr_val ) );//, _WTXT("(fh >= 0 && (unsigned)fh < (unsigned)_nhandle)") );
if( !( _Expr_val ) )
{
_set_doserrno( 0 );
errno = EBADF;
//TODO: Raise invalid parameter error
return -1;
}
//_VALIDATE_CLEAR_OSSERR_RETURN((_osfile(fh) & FOPEN), EBADF, -1);
flockfile();
__try
{
if( IsOpen() )
{
r = _write_nolock( fh, buf, cnt ); // write bytes
}
else
{
errno = EBADF;
_set_doserrno( 0 ); // not o.s. error
r = -1;
//_ASSERTE(("Invalid file descriptor. File possibly closed by a different thread",0));
}
}
__finally
{
funlockfile();
}
return r;
}
//------------------------------------------------------------------------------
int CStream::_write_nolock( int fh, const void* buf, unsigned cnt )
{
int lfcount = 0; // count of line feeds
int charcount = 0; // count of chars written so far
int written; // count of chars written on this write
unsigned long dosretval = 0; // o.s. return value
char tmode; // textmode - ANSI or UTF-16
bool toConsole = false; // true when writing to console
bool isCLocale = false; // true when locale handle is C locale
if( cnt == 0 )
{
return 0; // nothing to do
}
assert( buf != NULL );
if( buf == NULL )
{
_set_doserrno( 0 );
errno = EINVAL;
return -1;
}
tmode = GetTextMode();
if( tmode == __IOINFO_TM_UTF16LE || tmode == __IOINFO_TM_UTF8 )
{
// For a UTF-16 file, the count must always be an even number
assert( ( cnt & 1 ) == 0 );
if( ( cnt & 1 ) != 0 )
{
_set_doserrno( 0 );
errno = EINVAL;
return -1;
}
}
if( IsAppendMode() )
{
// appending - seek to end of file; ignore error, because maybe file doesn't allow seeking
(void)_lseeki64_nolock( fh, 0, File_End );
}
// check for text mode with LF's in the buffer
/* Note that in case the handle belongs to Console, write file will generate garbage output. For user to print these characters correctly, we will need to print ANSI.
* Also note that in case of printing to Console, we still have to convert the characters to console codepage. */
if( _isatty( fh ) && ( GetIsTextMode() ) )
{
unsigned long dwMode = 0;
//isCLocale = (ptd->ptlocinfo->locale_name[LC_CTYPE] == NULL);
isCLocale = ( GetCurrentWin32Thread()->LocaleInfoPtr()->Category( CLocale::LCCTYPE ).CatLocale() == NULL ) ? true : false;
CTerminal* pTerminal = CWin32Application::TheWin32Application()->GetRole()->GetSubSystem( CTerminal::ClassID() ).As< CTerminal >();
toConsole = pTerminal->Console()->ScreenBuffer()->GetInputMode( dwMode );
}
// don't need double conversion if it's ANSI mode C locale
if( toConsole && !( isCLocale && ( tmode == __IOINFO_TM_ANSI ) ) )
{
CTerminal* pTerminal = CWin32Application::TheWin32Application()->GetRole()->GetSubSystem( CTerminal::ClassID() ).As< CTerminal >();
unsigned int consoleCP = pTerminal->Console()->OutputCodePage().ID();
char mboutbuf[ MBLenMax ];
wchar_t tmpchar = 0;
int size = 0;
written = 0;
char *pch;
for( pch = (char *)buf; (unsigned)( pch - (char *)buf ) < cnt; )
{
int bCR = 0;
if( tmode == __IOINFO_TM_ANSI )
{
bCR = *pch == LF;
// Here we need to do double convert. i.e. convert from multibyte to unicode and then from unicode to multibyte in Console codepage.
// Here, we have take into account that _write() might be called byte by byte, so when we see a lead byte without a trail byte, we have to store it and return no error.
if( IsLeadByteBufferUsed() )
{
// we got something buffered, join it with the lead byte and convert
assert( isleadbyte( ReadDBCSBuffer() ) );
mboutbuf[ 0 ] = ReadDBCSBuffer();
mboutbuf[ 1 ] = *pch;
// reseting the flag
SetIsLeadByteBufferUsed( false );
if( mbtowc( &tmpchar, mboutbuf, 2 ) == -1 )
{
break;
}
}
else
{
if( isleadbyte( *pch ) )
{
if( ( cnt - ( pch - (char*)buf ) ) > 1 )
{
// and we have more bytes to read, just convert
if( mbtowc( &tmpchar, pch, 2 ) == -1 )
{
break;
}
// Increment pch to accomodate DBCS character.
++pch;
}
else
{
// and we ran out of bytes to read, buffer the lead byte
WriteDBCSBuffer( *pch );
// lying that we actually wrote the last character, so it doesn't error
charcount++;
break;
}
}
else
{
// single char conversion
if( mbtowc( &tmpchar, pch, 1 ) == -1 )
{
break;
}
}
}
++pch;
}
else if( tmode == __IOINFO_TM_UTF8 || tmode == __IOINFO_TM_UTF16LE )
{
//Note that bCR set above is not valid in case of UNICODE stream. We need to set it using unicode character.
tmpchar = *(wchar_t *)pch;
bCR = tmpchar == LF;
pch += 2;
}
if( tmode == __IOINFO_TM_ANSI )
{
if( ( size = m_StringHelper.WideCharToMultiByte( consoleCP, 0, &tmpchar, 1, mboutbuf, sizeof( mboutbuf ), NULL, NULL ) ) == 0 )
{
break;
}
else
{
if( m_pStreamDevice->Write( mboutbuf, size, reinterpret_cast< unsigned long* >( &written ), 0 ) )
{
/* When we are converting, some convertion can result in 2 mbcs char -> 1 wchar -> 1 mbcs
* (ie. printing out Japanese characters in English ConsoleCP,
* the Japanese char will be converted to a single question mark)
* Therefore, we want to use how many bytes we converted + lfcount
* instead of how many bytes we actually wrote
*/
charcount = lfcount + (int)( pch - (char*)buf );
if( written < size )
{
break;
}
}
else
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
}
if( bCR )
{
size = 1;
mboutbuf[ 0 ] = CR;
if( m_pStreamDevice->Write( mboutbuf, size, reinterpret_cast< unsigned long* >( &written ), 0 ) )
{
if( written < size )
{
break;
}
lfcount++;
charcount++;
}
else
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
}
}
else if( tmode == __IOINFO_TM_UTF8 || tmode == __IOINFO_TM_UTF16LE )
{
if( _putwch_nolock( tmpchar ) == tmpchar )
{
charcount += 2;
}
else
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
if( bCR ) // emit carriage return
{
size = 1;
tmpchar = CR;
if( _putwch_nolock( tmpchar ) == tmpchar )
{
charcount++;
lfcount++;
}
else
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
}
}
}
}
else if( GetIsTextMode() )
{
// text mode, translate LF's to CR/LF's on output
dosretval = 0; // no OS error yet
if( tmode == __IOINFO_TM_ANSI )
{
char ch; // current character
char* p = NULL, *q = NULL; // pointers into buf and lfbuf resp.
char lfbuf[ BUF_SIZE ];
p = (char *)buf; // start at beginning of buffer
while( (unsigned)( p - (char *)buf ) < cnt )
{
q = lfbuf; // start at beginning of lfbuf
// fill the lf buf, except maybe last char
while( q - lfbuf < sizeof( lfbuf ) - 1 && (unsigned)( p - (char *)buf ) < cnt )
{
ch = *p++;
if( ch == LF )
{
++lfcount;
*q++ = CR;
}
*q++ = ch;
}
// write the lf buf and update total
if( m_pStreamDevice->Write( lfbuf, (int)( q - lfbuf ), reinterpret_cast< unsigned long* >( &written ), 0 ) )
{
charcount += written;
if( written < q - lfbuf )
break;
}
else
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
}
}
else if( tmode == __IOINFO_TM_UTF16LE )
{
char lfbuf[ BUF_SIZE ];
wchar_t wch; // current wide char
wchar_t *pu = (wchar_t *)buf;
wchar_t *qu = NULL;
while( (unsigned)( (char *)pu - (char *)buf ) < cnt )
{
qu = (wchar_t *)lfbuf; // start at beginning of lfbuf
// fill the lf buf, except maybe last wchar_t
while( ( ( (char *)qu - lfbuf ) < ( sizeof( lfbuf ) - 2 ) ) && ( (unsigned)( (char *)pu - (char *)buf ) < cnt ) )
{
wch = *pu++;
if( wch == LF )
{
lfcount += 2;
*qu++ = CR;
}
*qu++ = wch;
}
// write the lf buf and update total
if( m_pStreamDevice->Write( lfbuf, (int)( (char*)qu - lfbuf ), reinterpret_cast< unsigned long* >( &written ), 0 ) )
{
charcount += written;
if( written < ( (char *)qu - lfbuf ) )
break;
}
else
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
}
}
else
{
// Let's divide the lfbuf in 1:2 wher 1 is for storing widecharacters and 2 if for converting it to UTF8.
// This takes into account the worst case scenario where all the UTF8 characters are 4 byte long.
char utf8_buf[ ( BUF_SIZE * 2 ) / 3 ];
wchar_t utf16_buf[ BUF_SIZE / 6 ];
wchar_t wch; // current wide char
wchar_t *pu = (wchar_t *)buf;
wchar_t *qu = NULL;
pu = (wchar_t *)buf;
while( (unsigned)( (char *)pu - (char *)buf ) < cnt )
{
int bytes_converted = 0;
qu = utf16_buf; // start at beginning of lfbuf
while( ( ( (char *)qu - (char *)utf16_buf ) < ( sizeof( utf16_buf ) - 2 ) ) && ( (unsigned)( (char *)pu - (char *)buf ) < cnt ) )
{
wch = *pu++;
if( wch == LF )
{
// no need to count the linefeeds here: we calculate the written chars in another way
*qu++ = CR;
}
*qu++ = wch;
}
bytes_converted = m_StringHelper.WideCharToMultiByte( CCodePage::UTF8, 0, utf16_buf, ( (int)( (char *)qu - (char *)utf16_buf ) ) / 2, utf8_buf, sizeof( utf8_buf ), 0, 0 );
if( bytes_converted == 0 )
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
else
{
// Here we need to make every attempt to write all the converted characters.
//The resaon behind this is incase half the bytes of a UTF8 character is written, it may currupt whole of the stream or file.
// The loop below will make sure we exit only if all the bytes converted are written (which makes sure no partial MBCS is written) or there was some error in the stream.
int bytes_written = 0;
do
{
if( m_pStreamDevice->Write( utf8_buf + bytes_written, bytes_converted - bytes_written, reinterpret_cast< unsigned long* >( &written ), 0 ) )
{
bytes_written += written;
}
else
{
dosretval = m_ErrorHelper.GetLastError();
break;
}
} while( bytes_converted > bytes_written );
// Only way the condition below could be true is if there was en error.
//In case of error we need to break this loop as well.
if( bytes_converted > bytes_written )
{
break;
}
// if this chunk has been committed successfully, update charcount
charcount = (int)( (char *)pu - (char *)buf );
}
}
}
}
else
{
// binary mode, no translation
if( m_pStreamDevice->Write( (const byte*)buf, cnt, reinterpret_cast< unsigned long* >( &written ), 0 ) )
{
dosretval = 0;
charcount = written;
}
else
{
dosretval = m_ErrorHelper.GetLastError();
}
}
if( charcount == 0 )
{
// If nothing was written, first check if an o.s. error, otherwise we return -1 and set errno to ENOSPC, unless a device and first char was CTRL-Z
if( dosretval != 0 )
{
// o.s. error happened, map error
if( dosretval == ErrorAccessDenied )
{
// wrong read/write mode should return EBADF, not EACCES
errno = EBADF;
_set_doserrno( dosretval );
}
else
{
CDOSError::MapError( m_ErrorHelper.GetLastError() );
}
return -1;
}
else if( IsDevice() && *(char *)buf == CTRLZ )
{
return 0;
}
else
{
errno = ENOSPC;
_set_doserrno( 0 ); // no o.s. error
return -1;
}
}
else
{
// return adjusted bytes written
return charcount - lfcount;
}
}
//------------------------------------------------------------------------------
bool CStream::IsWrite( void )
{
return IsBufferWrite();
}
//------------------------------------------------------------------------------
void CStream::SetLowLevelFlags( byte Flags )
{
SetFlags( Flags );
}
//------------------------------------------------------------------------------
void CStream::SetLowLevelFile( CFile* pFile )
{
if( m_pStreamDevice == 0 )
{
m_pStreamDevice = pFile;
}
}
}//nsWin32
| 24.546089 | 285 | 0.520823 | [
"object"
] |
f26db166da969e8ea326c55d5a327ac578c5994e | 2,043 | cpp | C++ | src/utils/strparse/strparse.cpp | wangzhezhe/observerchain | faa8fb9d845a2720704538f01e1e7597083d4510 | [
"MIT"
] | null | null | null | src/utils/strparse/strparse.cpp | wangzhezhe/observerchain | faa8fb9d845a2720704538f01e1e7597083d4510 | [
"MIT"
] | null | null | null | src/utils/strparse/strparse.cpp | wangzhezhe/observerchain | faa8fb9d845a2720704538f01e1e7597083d4510 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include "./strparse.h"
using namespace std;
vector<int> strSplit(string str)
{
vector<int> words;
int leftIdx = 0;
int rightIdx = 0;
while (rightIdx < str.size())
{
while (rightIdx < str.size() && str[rightIdx] != ',')
rightIdx++;
words.push_back(stoi(str.substr(leftIdx, rightIdx - leftIdx)));
leftIdx = rightIdx + 1;
rightIdx = rightIdx + 1;
}
return words;
}
//GRID[<0,0>:<1,1>]%TS[5] use % to split, then get grid info
//use regx GRID\[.+\]% first
//then get specific data
string getGridFromRawMeta( string publishedMeta){
printf("input str (%s)\n", publishedMeta.data());
int position = publishedMeta.find("%");
publishedMeta.erase(publishedMeta.begin()+position,publishedMeta.end());
string rawGrid = publishedMeta;
printf("raw grid %s\n",rawGrid.data());
string GridInner = rawGrid.substr(5,rawGrid.length()-6);
return GridInner;
}
//use regx TS\[.+\] first
int getTsFromRawMeta( string publishedMeta){
int position = publishedMeta.find("%");
publishedMeta.erase(publishedMeta.begin(),publishedMeta.begin()+position+1);
string rawTS = publishedMeta;
printf("raw ts %s\n",rawTS.data());
int TS = stoi(rawTS.substr(3,rawTS.length()-4));
return TS;
}
//the meta string should be this format <0,0>:<2,2>
void getbbxfromGridMeta(string gridRawMeta, vector<int> &lb, vector<int> &ub)
{
printf("get gridRawMeta %s\n",gridRawMeta.data());
int startPosition = gridRawMeta.find(":");
string lbmeta = gridRawMeta;
string ubmeta = gridRawMeta;
lbmeta.erase(lbmeta.begin() + startPosition, lbmeta.end());
ubmeta.erase(0, startPosition + 1);
lbmeta = lbmeta.substr(0, lbmeta.length() - 1);
lbmeta = lbmeta.substr(1, lbmeta.length());
ubmeta = ubmeta.substr(0, ubmeta.length() - 1);
ubmeta = ubmeta.substr(1, ubmeta.length());
lb = strSplit(lbmeta);
ub = strSplit(ubmeta);
return;
} | 24.035294 | 80 | 0.632893 | [
"vector"
] |
f26e1709a575a9e79fa57076076533ea074c7a80 | 2,565 | cpp | C++ | src/EncodersOdometry.cpp | Orion3k/Siryo-Differential-Drive-Robot | f3a64e4584ba63c88589bc90e87a23b1eae56e3f | [
"MIT"
] | null | null | null | src/EncodersOdometry.cpp | Orion3k/Siryo-Differential-Drive-Robot | f3a64e4584ba63c88589bc90e87a23b1eae56e3f | [
"MIT"
] | null | null | null | src/EncodersOdometry.cpp | Orion3k/Siryo-Differential-Drive-Robot | f3a64e4584ba63c88589bc90e87a23b1eae56e3f | [
"MIT"
] | null | null | null | #include "ros/ros.h"
#include "nav_msgs/Odometry.h"
#include "tf/transform_broadcaster.h"
#include "geometry_msgs/Vector3Stamped.h"
#include "math.h"
class Odom_class{
private:
ros::NodeHandle nh;
ros::Subscriber speed_sub;
ros::Publisher odom_pub;
tf::TransformBroadcaster tf_pub;
tf::Quaternion q;
tf::Transform transform;
ros::Time current_time, last_time;
geometry_msgs::Quaternion odom_quat;
double dt, x ,y, z, vl, va, vx, vy, L, R, dtheta, theta;
public:
Odom_class(){
speed_sub = nh.subscribe("/wheels_speed",1,&Odom_class::encodersCallback,this);
odom_pub = nh.advertise<nav_msgs::Odometry>("/wheel_encoders/odom",1000);
last_time = ros::Time::now();
nh.getParam("/robot_base_L",L);
theta = 0;
R = 0;
x = 0;
y = 0;
z = 0;
va = 0;
vl = 0;
vx = 0;
vy = 0;
dtheta = 0;
ROS_INFO("%s","Inner class constructor entered\n");
}
void encodersCallback(const geometry_msgs::Vector3Stamped::ConstPtr& msg){
//odometry
dt = msg->vector.z;
va = (msg->vector.y - msg->vector.x)/L;
R = (L* (msg->vector.y + msg->vector.x) )/(2 * (msg->vector.y - msg->vector.x) );
vl = (msg->vector.y + msg->vector.x) / 2;
dtheta = va * dt;
theta = theta + dtheta;
vx = vl * cos(theta);
vy = vl * sin(theta);
x = x + vx * dt;
y = y + vy * dt;
nav_msgs::Odometry odom;
odom.header.stamp = current_time;
odom.header.frame_id = "robot_odom_base";
odom.child_frame_id = "robot_link";
odom_quat = tf::createQuaternionMsgFromYaw(theta);
//set pose
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = z;
odom.pose.pose.orientation = odom_quat;
//set velocity
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = va;
odom_pub.publish(odom);
//tf
transform.setOrigin(tf::Vector3(x,y,z));
q.setRPY(0,0,theta);
transform.setRotation(q);
tf_pub.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "map", "robot_odom_base"));
}
};
int main(int argc, char **argv){
ros::init(argc,argv,"EncodersOdometry");
Odom_class my_odom_class;
ros::spin();
return 0;
}
| 28.820225 | 106 | 0.552437 | [
"vector",
"transform"
] |
f270b0847ad301fc648e3ad382a6648847a57969 | 3,346 | cpp | C++ | src/parser/parser.cpp | adamhutchings/chirpc | 70d190fa79fa9f968b8de14ca41a8f50bae0019b | [
"MIT"
] | 1 | 2021-06-02T13:24:13.000Z | 2021-06-02T13:24:13.000Z | src/parser/parser.cpp | dekrain/chirpc | 93a6230da746d1e6e16230d79b151dee0d3f4a09 | [
"MIT"
] | null | null | null | src/parser/parser.cpp | dekrain/chirpc | 93a6230da746d1e6e16230d79b151dee0d3f4a09 | [
"MIT"
] | null | null | null | #include "parser.hpp"
void parser::load_tokens(std::string fn, std::vector<token> t)
{
this->filename = fn;
this->tkns = t;
}
std::vector<helper> parser::get_helpers()
{
return this->helpers;
}
ast parser::get_ast()
{
return this->tree;
}
void parser::parse()
{
this->ok = true;
//this->tree.root.children.push_back(this->get_stmt());
// Only gets the top-level stuff
while(!match(tkn_type::eof) && this->ok)
{
tkn_type t = this->peek().type;
if(t == tkn_type::kw_entry)
{
this->tree.entry = get_entry();
this->tree.has_entry = true;
}
else if(t == tkn_type::kw_import)
{
this->tree.imports.push_back(get_import());
}
else if(t == tkn_type::kw_extern)
{
this->tree.externs.push_back(get_extern());
}
else if(t == tkn_type::kw_func)
{
if(is_func_def(true))
{
this->tree.fdefs.push_back(get_func_def());
}
else if(is_func_decl(true))
{
this->tree.fdecls.push_back(get_func_decl());
}
else
{
// Is either a var or an error
helper e;
e.l = peek().loc;
e.msg = "I am a lazy person";
e.type = helper_type::location_err;
this->helpers.push_back(e);
this->ok = false;
}
}
else
{
this->ok = false;
helper e;
e.type = helper_type::location_err;
e.l = this->peek().loc;
e.msg = "Invalid top-level statement";
this->helpers.push_back(e);
}
}
}
bool parser::match(tkn_type v)
{
// Probably good enough to stop like 99% of bad behaviour
if (!this->ok)
{
return false;
}
if (this->peek().type == v)
{
cursor++;
return true;
}
return false;
}
bool parser::expect(tkn_type v)
{
if (!match(v))
{
helper e;
if (cursor >= this->tkns.size())
{
e.type = helper_type::line_err;
// If line err, doesn't care about start or end, just line
location l;
l.filename = this->filename;
l.line = this->tkns.at(this->tkns.size() - 1).loc.line;
e.msg = "Unexpected end of file.";
}
else
{
e.l = tkns.at(this->cursor).loc;
e.l.filename = this->filename;
e.type = helper_type::location_err;
e.msg = "Unexpected token";
}
this->helpers.push_back(e);
}
return true;
}
token parser::peekb()
{
if (cursor > 0)
{
return this->tkns.at(cursor - 1);
}
else
{
token t;
t.type = tkn_type::eof;
return t;
}
}
token parser::peek()
{
if (cursor >= 0 && cursor < this->tkns.size())
{
return this->tkns.at(cursor);
}
else
{
token t;
t.type = tkn_type::eof;
return t;
}
}
token parser::peekf()
{
if (cursor + 1 < this->tkns.size())
{
return this->tkns.at(cursor + 1);
}
else
{
token t;
t.type = tkn_type::eof;
return t;
}
} | 21.448718 | 70 | 0.472803 | [
"vector"
] |
f27b5cdaa66c8e6b921608cf58b7318083f36000 | 46,475 | cpp | C++ | src/opbox/net/nnti/NetNnti.cpp | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-01-25T21:21:07.000Z | 2021-04-29T17:24:00.000Z | src/opbox/net/nnti/NetNnti.cpp | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 8 | 2018-10-09T14:35:30.000Z | 2020-09-30T20:09:42.000Z | src/opbox/net/nnti/NetNnti.cpp | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-04-23T19:01:36.000Z | 2021-05-11T07:44:55.000Z | // Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#include <algorithm>
#include <functional>
#include <iostream>
#include <sstream>
#include <thread>
#include <sys/unistd.h> //gethostname
#include <boost/bimap.hpp>
#include "opbox/net/net.hh"
#include "opbox/net/net_internal.hh"
#include "opbox/net/peer.hh"
#include "nnti/nnti.h"
#include "nnti/nnti_logger.hpp"
#include "nnti/nnti_transport.hpp"
#include "nnti/nnti_callback.hpp"
#include "nnti/nnti_wr.hpp"
#include "nnti/transport_factory.hpp"
#include "faodel-common/Configuration.hh"
#include "faodel-common/NodeID.hh"
#include "whookie/Server.hh"
#include "lunasa/Lunasa.hh"
#include "lunasa/DataObject.hh"
#include "opbox/common/Types.hh"
#include "opbox/OpBox.hh"
using namespace std;
using namespace net;
using namespace opbox;
using namespace lunasa;
namespace opbox {
namespace net {
typedef struct peer_t {
NNTI_peer_t p;
peer_t() {} //Empty when given nothing
peer_t(const NNTI_peer_t &p_) : p(p_) {}
peer_t(const peer_t &p_) : p(p_.p) {}
peer_t & operator=(const peer_t &rhs) { p = rhs.p; return *this; }
peer_t & operator=(const NNTI_peer_t &rhs) { p = rhs; return *this; }
operator const NNTI_peer_t &() const {return p; }
operator NNTI_peer_t &() { return p; }
bool operator== (const peer_t &other) const { return (p == other.p); }
bool operator!= (const peer_t &other) const { return (p != other.p); }
bool operator< (const peer_t &other) const { return (p < other.p); }
} peer_t;
namespace NetNnti
{
typedef boost::bimap< faodel::nodeid_t, opbox::net::peer_t * > nodeid_peer_bimap;
typedef nodeid_peer_bimap::value_type nodeid_peer_value;
nodeid_peer_bimap peer_bimap;
NNTI_attrs_t nnti_attrs_;
faodel::nodeid_t myid_;
bool use_zero_copy_;
class user_invoking_callback
{
private:
std::function< WaitingType(OpArgs *args) > user_cb_;
void *context_;
UpdateType event_to_update_type(NNTI_event_t *event) {
switch(event->type) {
case NNTI_EVENT_SEND:
return UpdateType::send_success;
break;
case NNTI_EVENT_PUT:
return UpdateType::put_success;
break;
case NNTI_EVENT_GET:
return UpdateType::get_success;
break;
case NNTI_EVENT_ATOMIC:
return UpdateType::atomic_success;
break;
default:
abort();
break;
}
}
public:
user_invoking_callback()
{
return;
}
user_invoking_callback(lambda_net_update_t user_cb, void *context)
{
user_cb_ = user_cb;
context_ = context;
return;
}
NNTI_result_t operator() (NNTI_event_t *event, void *context)
{
NNTI_result_t rc = NNTI_OK;
log_debug("NetNnti", "user_invoking_callback->operator()");
//peer_t sender(event->peer);
//OpArgs args;
//results_t results;
//args.type = event_to_update_type(event);
//args.data.msg.sender = &sender;
//args.data.msg.ptr = (message_t*)((char*)event->start + event->offset);
//WaitingType cb_rc = user_cb_(args, &results);
//CDU: TODO- Do we need to pass in sender, and msg?
OpArgs *args = new OpArgs( event_to_update_type(event) );
user_cb_(args);
//CDU: end
// if the LDO was used to send a message, then we own it so release it.
// an LDO used for RDMAs or atomics is owned by the app, so it should release it.
if (event->op == NNTI_OP_SEND) {
DataObject *ldo = (DataObject*)context_;
// opbox::net::ReleaseMessage(ldo);
delete ldo;
}
return rc;
}
};
class default_callback
{
public:
NNTI_result_t operator() (NNTI_event_t *event, void *context)
{
DataObject *ldo = (DataObject*)context;
// opbox::net::ReleaseMessage(ldo);
delete ldo;
return NNTI_OK;
}
};
bool initialized_;
bool started_;
faodel::Configuration config_;
nnti::transports::transport *t_;
NNTI_event_queue_t unexpected_eq_;
NNTI_event_queue_t send_eq_;
NNTI_event_queue_t recv_eq_;
NNTI_event_queue_t rdma_eq_;
default_callback *dcb_;
user_invoking_callback *uicb_;
nnti::datatype::nnti_event_callback *default_send_cb_;
struct NntiRecvBuffer {
DataObject ldo_;
NntiRecvBuffer(
DataObject msg)
{
ldo_ = msg;
}
};
std::deque<struct NntiRecvBuffer*> recv_buffers_;
void postRecvBuffer(DataObject ldo)
{
recv_buffers_.push_back(new NntiRecvBuffer(ldo));
}
void repostRecvBuffer(NntiRecvBuffer *nrb)
{
recv_buffers_.push_back(nrb);
}
void setupRecvQueue()
{
opbox::net::Attrs attrs;
opbox::net::GetAttrs(&attrs);
for (int i=0;i<10;i++) {
DataObject ldo = NewMessage(attrs.max_eager_size);
postRecvBuffer(ldo);
}
}
void teardownRecvQueue()
{
while(!recv_buffers_.empty()) {
NntiRecvBuffer *nrb = recv_buffers_.front();
recv_buffers_.pop_front();
// opbox::net::ReleaseMessage(nrb->ldo_);
delete nrb;
}
}
void translateConfig(faodel::Configuration &config)
{
faodel::rc_t rc;
std::vector<std::string> keys;
bool b;
/*
* NNTI doesn't support toggling of individual logger severities.
* Instead, find the most verbose severity that is toggled on and
* use that as the NNTI severity.
*/
keys = {
"debug",
"info",
"warn",
"error",
"fatal",
};
for (auto key : keys ) {
rc = config.GetBool(&b, std::string("net.log."+key), "false");
if (rc==0 && b) {
config.Set("nnti.logger.severity", key);
break;
}
}
/*
* Directly map net.log.filename to nnti.logger.filename.
*/
std::string logfile;
rc = config.GetString(&logfile, "net.log.filename");
if (rc==0) {
config.Set("nnti.logger.filename", logfile);
}
/*
* Directly map net.transport.name to nnti.transport.name. If
* net.transport.name is not set, nnti.transport.name will not
* be set.
*/
std::string transport_name;
rc = config.GetString(&transport_name, "net.transport.name");
if (rc==0) {
if (transport_name == "gni") {
// translate the libfabric name to the NNTI name
transport_name = "ugni";
} else if (transport_name == "verbs") {
// translate the libfabric name to the NNTI name
transport_name = "ibverbs";
} else if (transport_name == "sockets") {
// NNTI doesn't have a sockets transport. warn and try MPI.
// TODO: the logger isn't initialized yet. use cerr until this is fixed.
std::cerr << "NetNnti -> net.transport.name has unsupported value 'sockets'. Failing back to 'mpi'." << std::endl;
transport_name = "mpi";
}
config.Set("nnti.transport.name", transport_name);
}
/*
* In Opbox, NNTI specific keys start with "net.nnti." so we
* strip off the "net." before sending the config to NNTI.
*/
size_t index;
std::vector<std::pair<std::string,std::string>> all_kv;
config.GetAllSettings(&all_kv);
for ( auto kv : all_kv ) {
std::string k = kv.first;
index = k.find("net.nnti.", 0);
// only do the replace if "net.nnti." is at the beginning of the key name
if (index == 0) {
k.replace(index, 9, "nnti.");
config.Set(k, kv.second);
}
}
}
}
namespace NetNnti
{
std::function<void(opbox::net::peer_ptr_t, opbox::message_t*)> recv_cb_;
// This is the Nnti implementation of the remote network buffer
struct NntiBufferRemote {
uint32_t offset;
uint32_t length;
char packed[];
};
// This is the Nnti implementation of the local network buffer.
struct NntiBufferLocal : NetBufferLocal {
NNTI_buffer_t nnti_buffer;
uint64_t base_addr;
uint32_t length;
virtual ~NntiBufferLocal() {}
void makeRemoteBuffer (
size_t remote_offset, // in
size_t remote_length, // in
NetBufferRemote *remote_buffer) override; // out
};
void NntiBufferLocal::makeRemoteBuffer(
size_t remote_offset, // in
size_t remote_length, // in
NetBufferRemote *remote_buffer) { // out
NntiBufferRemote *rb = (NntiBufferRemote*)remote_buffer;
rb->offset = remote_offset;
rb->length = remote_length;
t_->dt_pack((void*)nnti_buffer, &rb->packed[0], MAX_NET_BUFFER_REMOTE_SIZE-8);
log_debug("NetNnti", "offsetof(nbr.packed) is %lu", offsetof(NntiBufferRemote, packed));
}
void RegisterMemory(void *base_addr, size_t length, void *&pinned)
{
NntiBufferLocal *nbl = new NntiBufferLocal();
nnti::datatype::nnti_event_callback *cb = new nnti::datatype::nnti_event_callback(t_, *dcb_);
t_->register_memory(
(char*)base_addr,
length,
static_cast<NNTI_buffer_flags_t>(NNTI_BF_LOCAL_READ|NNTI_BF_LOCAL_WRITE|NNTI_BF_REMOTE_READ|NNTI_BF_REMOTE_WRITE|NNTI_BF_REMOTE_ATOMIC),
NNTI_INVALID_HANDLE,
*cb,
nullptr,
&nbl->nnti_buffer);
nbl->base_addr = (uint64_t)base_addr;
nbl->length = length;
pinned = (void*)nbl;
}
void UnregisterMemory(void *&pinned)
{
NntiBufferLocal *nbl = (NntiBufferLocal *)pinned;
t_->unregister_memory(nbl->nnti_buffer);
delete nbl;
pinned = nullptr;
}
class unexpected_callback
{
public:
NNTI_result_t operator() (NNTI_event_t *event, void *context)
{
log_debug("NetNnti", "unexpected_callback->operator()");
if (!started_) {
return NNTI_EIO;
}
if (event->length <= nnti_attrs_.max_eager_size) {
log_debug("NetNnti", "using short message path");
log_debug_stream("NetNnti") << event;
while(recv_buffers_.empty()) {
std::this_thread::yield();
}
NntiRecvBuffer *nrb = recv_buffers_.front();
recv_buffers_.pop_front();
NntiBufferLocal *msg_bl;
uint32_t msg_bl_offset;
nrb->ldo_.GetDataRdmaHandle((void **)&msg_bl, msg_bl_offset);
// memset(nrb->ldo_->metaPtr(), 5, nrb->ldo_->metaSize());
// memset(nrb->ldo_->dataPtr(), 6, nrb->ldo_->dataSize());
// stringstream ss;
// nrb->ldo_->sstr(ss,0,0);
// log_debug_stream("NetNnti") << ss.str();
NNTI_event_t e;
NNTI_result_t rc = t_->next_unexpected(msg_bl->nnti_buffer, msg_bl_offset, &e);
if (rc != NNTI_OK) {
abort();
}
log_debug_stream("NetNnti") << e;
peer_t *sender = new peer_t(e.peer);
message_t *msg = (message_t*)nrb->ldo_.GetDataPtr();
recv_cb_(sender, msg);
repostRecvBuffer(nrb);
} else {
log_debug("NetNnti", "using long message path");
log_debug_stream("NetNnti") << event;
uint32_t meta_size = nnti_attrs_.mtu - nnti_attrs_.max_eager_size;
DataObject long_msg(meta_size, event->length, DataObject::AllocatorType::eager);
NntiBufferLocal *msg_bl;
uint32_t msg_bl_offset;
long_msg.GetDataRdmaHandle((void **)&msg_bl, msg_bl_offset);
// memset(long_msg.metaPtr(), 5, long_msg.metaSize());
// memset(long_msg.dataPtr(), 6, long_msg.dataSize());
// stringstream ss;
// long_msg.sstr(ss,0,0);
// log_debug_stream("NetNnti") << ss.str();
NNTI_event_t e;
NNTI_result_t rc = t_->next_unexpected(msg_bl->nnti_buffer, msg_bl_offset, &e);
if (rc != NNTI_OK) {
abort();
}
log_debug_stream("NetNnti") << e;
peer_t *sender = new peer_t(e.peer);
message_t *msg = (message_t*)long_msg.GetDataPtr();
recv_cb_(sender, msg);
}
return NNTI_OK;
}
};
}
using namespace NetNnti;
/**
* @brief Initialize the network module using @c config.
*/
void Init(
const faodel::Configuration &config)
{
config_ = config; // make a copy
translateConfig(config_);
dcb_ = new default_callback();
uicb_ = new user_invoking_callback();
default_send_cb_ = new nnti::datatype::nnti_event_callback(t_, *dcb_);
use_zero_copy_=false;
initialized_=true;
}
/**
* @brief Start the network module.
*/
void Start()
{
NNTI_result_t rc;
//Whookie should be started by this point. We can get its info now.
F_ASSERT(whookie::Server::IsRunning(), "Whookie not started before NetNnti started");
myid_ = whookie::Server::GetNodeID();
t_ = nnti::transports::factory::get_instance(config_);
rc = t_->start();
if (rc == NNTI_EINVAL) {
throw std::runtime_error("Couldn't start the NNTI transport because the network device couldn't be initialized. "
"Is net.transport.name correct in $FAODEL_CONFIG file?");
} else if (rc != NNTI_OK) {
throw std::runtime_error("Couldn't start the NNTI transport - reason unknown");
}
t_->attrs(&nnti_attrs_);
nnti::datatype::nnti_event_callback unexpected_cb(t_, unexpected_callback());
rc = t_->eq_create(128, NNTI_EQF_UNEXPECTED, unexpected_cb, nullptr, &unexpected_eq_);
F_ASSERT(rc==NNTI_OK, "couldn't create unexpected EQ");
rc = t_->eq_create(128, NNTI_EQF_UNSET, &send_eq_);
F_ASSERT(rc==NNTI_OK, "couldn't create unexpected EQ");
rc = t_->eq_create(128, NNTI_EQF_UNSET, &recv_eq_);
F_ASSERT(rc==NNTI_OK, "couldn't create unexpected EQ");
rc = t_->eq_create(128, NNTI_EQF_UNSET, &rdma_eq_);
F_ASSERT(rc==NNTI_OK, "couldn't create unexpected EQ");
lunasa::RegisterPinUnpin(RegisterMemory, UnregisterMemory);
setupRecvQueue();
std::stringstream ss;
config_.sstr(ss, 0, 0);
log_debug_stream("test_setup") << ss.str() << std::endl;
started_=true;
}
/**
* @brief Shutdown the network module.
*/
void Finish()
{
F_ASSERT(initialized_, "NetNnti not initialized");
F_ASSERT(started_, "NetNnti not started");
started_=false;
auto it = peer_bimap.begin();
while (it != peer_bimap.end()) {
log_debug("NetNnti", "Disconnecting nodeid %s (%x)", it->left.GetHex().c_str(), it->right);
Disconnect(it->right);
it = peer_bimap.begin();
}
teardownRecvQueue();
t_->stop();
delete dcb_;
delete uicb_;
}
/**
* @brief Register a callback that is invoked for each message received.
*/
void RegisterRecvCallback(
std::function<void(opbox::net::peer_ptr_t, opbox::message_t*)> recv_cb)
{
recv_cb_ = recv_cb;
}
/**
* @brief Get the node id of this process.
*
* Deprecated since Opbox now has this functionality (@c opbox::GetMyID()).
*/
faodel::nodeid_t GetMyID()
{
F_ASSERT(initialized_, "NetNnti not initialized");
return myid_;
}
/**
* @brief Convert a node id to a peer using the network module's map.
*
* Deprecated since Opbox is responsible for maintaining it's own map if desired.
*/
faodel::nodeid_t ConvertPeerToNodeID(
opbox::net::peer_t *peer)
{
faodel::nodeid_t nodeid;
try {
nodeid = peer_bimap.right.at(peer);
}
catch ( std::out_of_range & e ) {
log_debug("NetNnti", "Couldn't find %p", (void*)peer);
}
return nodeid;
}
/**
* @brief Convert a peer to a node id using the network module's map.
*
* Deprecated since Opbox is responsible for maintaining it's own map if desired.
*/
opbox::net::peer_t *ConvertNodeIDToPeer(
faodel::nodeid_t nodeid)
{
opbox::net::peer_t *peer = nullptr;
try {
peer = peer_bimap.left.at(nodeid);
}
catch ( std::out_of_range & e ) {
log_debug("NetNnti", "Couldn't find %s", std::string(nodeid.GetIP()+":"+nodeid.GetPort()).c_str());
}
return peer;
}
/**
* @brief Get the name of the active network module.
*/
string GetDriverName() {
return "nnti3";
}
/**
* @brief Get the attributes of the network module.
* @param[out] attrs Where attributes are copied to
*/
void GetAttrs(
Attrs *attrs) {
attrs->mtu = nnti_attrs_.mtu;
attrs->max_eager_size = nnti_attrs_.max_eager_size;
char url_c[NNTI_URL_LEN];
t_->get_url(url_c, NNTI_URL_LEN);
std::string url(url_c);
uint32_t first = url.find("://");
first += 3;
uint32_t second = url.find(":", first);
second += 1;
uint32_t third = url.find("/", second);
std::string hostname = url.substr(first, (second-1)-first);
std::string port = url.substr(second, third-second);
strcpy(attrs->bind_hostname, hostname.c_str());
strcpy(attrs->listen_port, port.c_str());
log_debug("NetNnti", "attrs.mtu = %ld", attrs->mtu);
log_debug("NetNnti", "attrs.max_eager_size = %ld", attrs->max_eager_size);
log_debug("NetNnti", "attrs.bind_hostname = %s", attrs->bind_hostname);
log_debug("NetNnti", "attrs.listen_port = %s", attrs->listen_port);
}
/**
* @brief Prepare for communication with the peer identified by peer_addr and peer_port.
*
* @param[out] peer A handle to a peer that can be used for network operations.
* @param[in] peer_addr The hostname or IP address the peer is bound to.
* @param[in] peer_port The port the peer is listening on.
* @return A result code
*/
int Connect(
peer_ptr_t *peer,
const char *peer_addr,
const char *peer_port)
{
faodel::nodeid_t nodeid = faodel::nodeid_t(peer_addr, peer_port);
return Connect(peer, nodeid);
}
/**
* @brief Prepare for communication with the peer identified by node ID.
*
* @param[out] peer A handle to a peer that can be used for network operations.
* @param[in] peer_nodeid The node ID of the peer.
* @return A result code
*/
int Connect(
peer_ptr_t *peer,
faodel::nodeid_t peer_nodeid)
{
NNTI_result_t rc = NNTI_OK;
*peer = ConvertNodeIDToPeer(peer_nodeid);
if (nullptr == *peer) {
std::stringstream url;
NNTI_peer_t p;
url << "http://" << peer_nodeid.GetIP() << ":" << peer_nodeid.GetPort() << "/";
log_debug("NetNnti", "Connecting to %s", url.str().c_str());
rc = t_->connect(url.str().c_str(), 1000, &p);
log_debug("NetNnti", "Connected to %p", (void*)p);
*peer = new peer_t(p);
peer_bimap.insert(nodeid_peer_value(peer_nodeid,*peer));
}
return rc;
}
int Disconnect(
peer_ptr_t peer)
{
int rc = NNTI_OK;
peer_bimap.right.erase(peer);
rc = t_->disconnect(peer->p);
delete peer;
return rc;
}
int Disconnect(
faodel::nodeid_t peer_nodeid)
{
log_debug("NetNnti", "Disconnecting from %s", std::string(peer_nodeid.GetIP()+":"+peer_nodeid.GetPort()).c_str());
peer_ptr_t peer = ConvertNodeIDToPeer(peer_nodeid);
if (peer == nullptr) {
log_warn("NetNnti", "%s is not connected", std::string(peer_nodeid.GetIP()+":"+peer_nodeid.GetPort()).c_str());
return -1;
}
return Disconnect(peer);
}
/*
* @brief Create a DataObject that can be used for zero copy sends.
*
* @param[in] size The size in bytes of the data section of the LDO.
* @return A pointer to the new LDO.
*/
DataObject NewMessage(
uint64_t size)
{
uint32_t meta_size = nnti_attrs_.mtu - nnti_attrs_.max_eager_size;
DataObject ldo(meta_size, size, DataObject::AllocatorType::eager);
return std::move(ldo);
}
/*
* @brief Explicitly release a message DataObject after use.
*
* @param[in] msg The message to release.
*/
void ReleaseMessage(
DataObject msg)
{
// delete msg;
}
namespace internal {
/*
* @brief This method returns the offset of the NetBufferRemote.
*
* @param[in] nbr - the nbr to query
* @return the offset of the NetBufferRemote
*/
uint32_t GetOffset(
opbox::net::NetBufferRemote *nbr) // in
{
NntiBufferRemote *b = (NntiBufferRemote *)nbr;
return b->offset;
}
/*
* @brief This method returns the length of the NetBufferRemote.
*
* @param[in] nbr - the nbr to query
* @return the length of the NetBufferRemote
*/
uint32_t GetLength(
opbox::net::NetBufferRemote *nbr) // in
{
NntiBufferRemote *b = (NntiBufferRemote *)nbr;
return b->length;
}
/*
* @brief This method increases the offset of the NetBufferRemote.
*
* @param[in] nbr - the nbr to modify
* @param[in] addend - the offset adjustment
* @return 0 if success, otherwise nonzero
*
* This method increases the offset of the NetBufferRemote. As a
* side effect, the length will be reduced by the same amount so
* that the window doesn't slide. addend must be greater than or
* equal to zero and less than the current length.
*/
int IncreaseOffset(
opbox::net::NetBufferRemote *nbr, // in
uint32_t addend) // in
{
NntiBufferRemote *b = (NntiBufferRemote *)nbr;
if (addend < b->length) {
b->offset += addend;
b->length -= addend;
} else {
return -1;
}
return 0;
}
/*
* @brief This method decreases the length of the NetBufferRemote.
*
* @param[in] nbr - the nbr to modify
* @param[in] subtrahend - the length adjustment
* @return 0 if success, otherwise nonzero
*
* This method decreases the length of the NetBufferRemote. The
* offset is not adjusted. subtrahend must be greater than or
* equal to zero and less than the current length.
*/
int DecreaseLength(
opbox::net::NetBufferRemote *nbr, // in
uint32_t subtrahend) // in
{
NntiBufferRemote *b = (NntiBufferRemote *)nbr;
if (subtrahend < b->length) {
b->length -= subtrahend;
} else {
return -1;
}
return 0;
}
/*
* @brief This method sets the length of the NetBufferRemote.
*
* @param[in] nbr the nbr to modify
* @param[in] length the new length
* @return 0 if success, otherwise nonzero
*
* This method sets the length of the NetBufferRemote. The offset
* is not adjusted. subtrahend must be greater than zero and less
* than the current length.
*
*/
int TrimToLength(
opbox::net::NetBufferRemote *nbr, // in
uint32_t length) // in
{
NntiBufferRemote *b = (NntiBufferRemote *)nbr;
if (length < b->length) {
b->length = length;
} else {
return -1;
}
return 0;
}
}
/**
* @brief Send a message to the peer identified by @c peer.
*
* @param[in] peer A handle to the tagret peer.
* @param[in] msg The LDO to send.
*
* Send the entire msg to peer. After the send completes
* (successfully or not), release msg.
* opbox gets no feedback about this operations (fire and forget).
*/
void SendMsg(
peer_t *peer,
DataObject msg)
{
volatile int rc;
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NNTI_peer_t peer_hdl = peer->p;
NntiBufferLocal *msg_bl = nullptr;
uint32_t msg_bl_offset = 0;
if (use_zero_copy_ &&
((msg.GetMetaSize() + msg.GetDataSize()) <= nnti_attrs_.mtu)) {
log_debug("NetNnti", "using zero-copy");
rc = msg.GetMetaRdmaHandle( (void **)&msg_bl, msg_bl_offset);
if (rc != 0) {
log_error("NetNnti", "msg->GetMetaRdmaHandle() failed: %d", rc);
abort();
}
base_wr.op = NNTI_OP_SEND;
base_wr.flags = (NNTI_op_flags_t)(NNTI_OF_LOCAL_EVENT | NNTI_OF_ZERO_COPY);
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = msg_bl->nnti_buffer;
base_wr.local_offset = msg_bl_offset;
base_wr.remote_hdl = NNTI_INVALID_HANDLE;
base_wr.remote_offset = 0;
base_wr.length = msg.GetMetaSize() + msg.GetDataSize() + msg.GetPaddingSize();
} else {
rc = msg.GetDataRdmaHandle( (void **)&msg_bl, msg_bl_offset);
if (rc != 0) {
log_error("NetNnti", "msg->GetDataRdmaHandle() failed: %d", rc);
abort();
}
base_wr.op = NNTI_OP_SEND;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = msg_bl->nnti_buffer;
base_wr.local_offset = msg_bl_offset;
base_wr.remote_hdl = NNTI_INVALID_HANDLE;
base_wr.remote_offset = 0;
base_wr.length = msg.GetDataSize() + msg.GetPaddingSize();
}
base_wr.cb_context = new DataObject(msg);
nnti::datatype::nnti_work_request wr(t_, base_wr, *default_send_cb_);
t_->send(&wr, &wid);
}
/**
* @brief Send a message to the peer identified by @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] msg The LDO to send.
* @param[in] user_cb The callback to invoke when events are generated from this send.
*
* Send the entire msg to peer. user_cb is invoked after the send
* completes. msg is not automatically released.
*/
void SendMsg(
peer_t *peer,
DataObject msg,
lambda_net_update_t user_cb)
{
volatile int rc;
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NNTI_peer_t peer_hdl = peer->p;
NntiBufferLocal *msg_bl = nullptr;
uint32_t msg_bl_offset = 0;
if (use_zero_copy_ &&
((msg.GetMetaSize() + msg.GetDataSize()) <= nnti_attrs_.mtu)) {
log_debug("NetNnti", "using zero-copy");
rc = msg.GetMetaRdmaHandle( (void **)&msg_bl, msg_bl_offset);
if (rc != 0) {
log_error("NetNnti", "msg->GetMetaRdmaHandle() failed: %d", rc);
abort();
}
base_wr.op = NNTI_OP_SEND;
base_wr.flags = (NNTI_op_flags_t)(NNTI_OF_LOCAL_EVENT | NNTI_OF_ZERO_COPY);
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = msg_bl->nnti_buffer;
base_wr.local_offset = msg_bl_offset;
base_wr.remote_hdl = NNTI_INVALID_HANDLE;
base_wr.remote_offset = 0;
base_wr.length = msg.GetMetaSize() + msg.GetDataSize() + msg.GetPaddingSize();;
} else {
rc = msg.GetDataRdmaHandle( (void **)&msg_bl, msg_bl_offset);
if (rc != 0) {
log_error("NetNnti", "msg->GetDataRdmaHandle() failed: %d", rc);
abort();
}
base_wr.op = NNTI_OP_SEND;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = msg_bl->nnti_buffer;
base_wr.local_offset = msg_bl_offset;
base_wr.remote_hdl = NNTI_INVALID_HANDLE;
base_wr.remote_offset = 0;
base_wr.length = msg.GetDataSize() + msg.GetPaddingSize();
}
user_invoking_callback *uicb = new user_invoking_callback(user_cb, new DataObject(msg));
nnti::datatype::nnti_event_callback *send_cb = new nnti::datatype::nnti_event_callback(t_, *uicb);
nnti::datatype::nnti_work_request wr(t_, base_wr, *send_cb);
t_->send(&wr, &wid);
}
/**
* @brief Read an entire LDO from @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] remote_buffer The source of the GET.
* @param[in] local_ldo The destination of the GET.
* @param[in] user_cb The callback to invoke when events are generated from this GET.
*
* Execute a one-sided read from remote_buffer on peer to local_ldo.
* Both remote and local offsets are zero. The length of the read
* is the smaller of remote_buffer and local_ldo. user_cb is invoked after
* the read completes.
*/
void Get(
peer_t *peer,
NetBufferRemote *remote_buffer,
DataObject local_ldo,
lambda_net_update_t user_cb)
{
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NntiBufferRemote *nbr = (NntiBufferRemote *)remote_buffer;
NNTI_peer_t peer_hdl = peer->p;
NNTI_buffer_t remote_hdl;
t_->dt_unpack((void*)&remote_hdl, &nbr->packed[0], MAX_NET_BUFFER_REMOTE_SIZE-8);
NntiBufferLocal *local_bl;
uint32_t local_bl_offset;
uint64_t local_size = local_ldo.GetHeaderSize() + local_ldo.GetMetaSize() +
local_ldo.GetDataSize() + local_ldo.GetPaddingSize();
local_ldo.GetHeaderRdmaHandle( (void **)&local_bl, local_bl_offset);
base_wr.op = NNTI_OP_GET;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = local_bl->nnti_buffer;
base_wr.local_offset = local_bl_offset;
base_wr.remote_hdl = remote_hdl;
base_wr.remote_offset = nbr->offset;
base_wr.length = std::min(local_size, (uint64_t) nbr->length); //TODO: widths?
nnti::datatype::nnti_event_callback *get_cb = nullptr;
if (user_cb) {
user_invoking_callback *uicb = new user_invoking_callback(user_cb, new DataObject(local_ldo));
get_cb = new nnti::datatype::nnti_event_callback(t_, *uicb);
} else {
default_callback *dcb = new default_callback();
get_cb = new nnti::datatype::nnti_event_callback(t_, *dcb);
}
nnti::datatype::nnti_work_request wr(t_, base_wr, *get_cb);
#if 1
{
bool abort_now=false;
// check that local/remote offset and length are 4-byte aligned
if (base_wr.local_offset%4 != 0) {
log_error("NetNnti", "opbox::net::Get() local_offset is not 4-byte aligned - %lu", base_wr.local_offset);
abort_now=true;
}
if (base_wr.remote_offset%4 != 0) {
log_error("NetNnti", "opbox::net::Get() remote_offset is not 4-byte aligned - %lu", base_wr.remote_offset);
abort_now=true;
}
if (base_wr.length%4 != 0) {
log_error("NetNnti", "opbox::net::Get() length is not 4-byte aligned - %lu (local_size = %ld / padding = %d)",
base_wr.length, local_size, local_ldo.GetPaddingSize());
abort_now=true;
}
if (abort_now) {
abort();
}
}
#endif
t_->get(&wr, &wid);
}
/*
* @brief Read a subset of an LDO from @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] remote_buffer The source of the GET.
* @param[in] remote_offset The offset into the source buffer.
* @param[in] local_ldo The destination of the GET.
* @param[in] local_offset The offset into the destination buffer.
* @param[in] length The length of the GET.
* @param[in] user_cb The callback to invoke when events are generated from this GET.
*
* Execute a one-sided read from remote_buffer on peer to local_ldo.
* user_cb is invoked after the read completes.
*/
void Get(
peer_t *peer,
NetBufferRemote *remote_buffer,
uint64_t remote_offset,
DataObject local_ldo,
uint64_t local_offset,
uint64_t length,
lambda_net_update_t user_cb)
{
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NntiBufferRemote *nbr = (NntiBufferRemote *)remote_buffer;
NNTI_peer_t peer_hdl = peer->p;
NNTI_buffer_t remote_hdl;
t_->dt_unpack((void*)&remote_hdl, &nbr->packed[0], MAX_NET_BUFFER_REMOTE_SIZE-8);
NntiBufferLocal *local_bl;
uint32_t local_bl_offset;
local_ldo.GetHeaderRdmaHandle( (void **)&local_bl, local_bl_offset);
base_wr.op = NNTI_OP_GET;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = local_bl->nnti_buffer;
base_wr.local_offset = local_bl_offset + local_offset;
base_wr.remote_hdl = remote_hdl;
base_wr.remote_offset = nbr->offset + remote_offset;
base_wr.length = length+local_ldo.GetPaddingSize();
nnti::datatype::nnti_event_callback *get_cb = nullptr;
if (user_cb) {
user_invoking_callback *uicb = new user_invoking_callback(user_cb, new DataObject(local_ldo));
get_cb = new nnti::datatype::nnti_event_callback(t_, *uicb);
} else {
default_callback *dcb = new default_callback();
get_cb = new nnti::datatype::nnti_event_callback(t_, *dcb);
}
nnti::datatype::nnti_work_request wr(t_, base_wr, *get_cb);
#if 1
{
bool abort_now=false;
bool report_all=false;
// check that local/remote offset and length are 4-byte aligned
if (base_wr.local_offset%4 != 0) {
log_error("NetNnti", "opbox::net::Get() local_offset is not 4-byte aligned - %lu", base_wr.local_offset);
abort_now=true;
} else if (report_all) {
log_error("NetNnti", "opbox::net::Get() local_offset is 4-byte aligned - %lu", base_wr.local_offset);
}
if (base_wr.remote_offset%4 != 0) {
log_error("NetNnti", "opbox::net::Get() remote_offset is not 4-byte aligned - %lu", base_wr.remote_offset);
abort_now=true;
} else if (report_all) {
log_error("NetNnti", "opbox::net::Get() remote_offset is 4-byte aligned - %lu", base_wr.remote_offset);
}
if (base_wr.length%4 != 0) {
log_error("NetNnti", "opbox::net::Get() length is not 4-byte aligned - %lu (length = %d / padding = %d)",
base_wr.length, length, local_ldo.GetPaddingSize());
abort_now=true;
} else if (report_all) {
log_error("NetNnti", "opbox::net::Get() length is 4-byte aligned - %lu", base_wr.length);
}
if (abort_now) {
abort();
}
}
#endif
t_->get(&wr, &wid);
}
/*
* @brief Write an entire LDO to @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] local_ldo The source of the PUT.
* @param[in] remote_buffer The destination of the PUT.
* @param[in] user_cb The callback to invoke when events are generated from this PUT.
*
* Execute a one-sided write to remote_buffer on peer from local_ldo.
* Both remote and local offsets are zero. The length of the write
* is the smaller of remote_buffer and local_ldo. user_cb is invoked after
* the write completes.
*/
void Put(
peer_t *peer,
DataObject local_ldo,
NetBufferRemote *remote_buffer,
lambda_net_update_t user_cb)
{
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NntiBufferRemote *nbr = (NntiBufferRemote *)remote_buffer;
NNTI_peer_t peer_hdl = peer->p;
NNTI_buffer_t remote_hdl;
t_->dt_unpack((void*)&remote_hdl, &nbr->packed[0], MAX_NET_BUFFER_REMOTE_SIZE-8);
NntiBufferLocal *local_bl;
uint32_t local_bl_offset;
uint64_t local_size = local_ldo.GetHeaderSize() + local_ldo.GetMetaSize() + local_ldo.GetDataSize() + local_ldo.GetPaddingSize();
local_ldo.GetHeaderRdmaHandle( (void **)&local_bl, local_bl_offset);
base_wr.op = NNTI_OP_PUT;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = local_bl->nnti_buffer;
base_wr.local_offset = local_bl_offset;
base_wr.remote_hdl = remote_hdl;
base_wr.remote_offset = nbr->offset;
base_wr.length = std::min(local_size, (uint64_t)nbr->length);
nnti::datatype::nnti_event_callback *put_cb = nullptr;
if (user_cb) {
user_invoking_callback *uicb = new user_invoking_callback(user_cb, new DataObject(local_ldo));
put_cb = new nnti::datatype::nnti_event_callback(t_, *uicb);
} else {
default_callback *dcb = new default_callback();
put_cb = new nnti::datatype::nnti_event_callback(t_, *dcb);
}
nnti::datatype::nnti_work_request wr(t_, base_wr, *put_cb);
t_->put(&wr, &wid);
}
/*
* @brief Write a subset of an LDO to @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] local_ldo The source of the PUT.
* @param[in] local_offset The offset into the source buffer.
* @param[in] remote_buffer The destination of the PUT.
* @param[in] remote_offset The offset into the destination buffer.
* @param[in] length The length of the PUT.
* @param[in] user_cb The callback to invoke when events are generated from this PUT.
*
* Execute a one-sided write to remote_buffer on peer from local_ldo.
* user_cb is invoked after the write completes.
*/
void Put(
peer_t *peer,
DataObject local_ldo,
uint64_t local_offset,
NetBufferRemote *remote_buffer,
uint64_t remote_offset,
uint64_t length,
lambda_net_update_t user_cb)
{
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NntiBufferRemote *nbr = (NntiBufferRemote *)remote_buffer;
NNTI_peer_t peer_hdl = peer->p;
NNTI_buffer_t remote_hdl;
t_->dt_unpack((void*)&remote_hdl, &nbr->packed[0], MAX_NET_BUFFER_REMOTE_SIZE-8);
NntiBufferLocal *local_bl;
uint32_t local_bl_offset;
local_ldo.GetHeaderRdmaHandle( (void **)&local_bl, local_bl_offset);
base_wr.op = NNTI_OP_PUT;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = local_bl->nnti_buffer;
base_wr.local_offset = local_bl_offset + local_offset;
base_wr.remote_hdl = remote_hdl;
base_wr.remote_offset = nbr->offset + remote_offset;
base_wr.length = length;
nnti::datatype::nnti_event_callback *put_cb = nullptr;
if (user_cb) {
user_invoking_callback *uicb = new user_invoking_callback(user_cb, new DataObject(local_ldo));
put_cb = new nnti::datatype::nnti_event_callback(t_, *uicb);
} else {
default_callback *dcb = new default_callback();
put_cb = new nnti::datatype::nnti_event_callback(t_, *dcb);
}
nnti::datatype::nnti_work_request wr(t_, base_wr, *put_cb);
t_->put(&wr, &wid);
}
/*
* @brief Perform an atomic operation on an LDO at @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] local_ldo The result of the atomic buffer.
* @param[in] local_offset The offset into the result buffer.
* @param[in] remote_buffer The target of the atomic operation.
* @param[in] remote_offset The offset into the target buffer.
* @param[in] length The length of the atomic operation.
* @param[in] user_cb The callback to invoke when events are generated from this PUT.
*
* Execute a one-sided atomic operation on peer at remote_buffer.
* length is the width of the operands in bits. user_cb is
* invoked after the atomic completes.
*/
void Atomic(
peer_ptr_t peer,
AtomicOp op,
DataObject local_ldo,
uint64_t local_offset,
NetBufferRemote *remote_buffer,
uint64_t remote_offset,
uint64_t length, // TODO: this param is ignored because we only do 64-bit atomics
lambda_net_update_t user_cb)
{
return;
}
/*
* @brief Perform an atomic operation on an LDO at @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] local_ldo The result of the atomic buffer.
* @param[in] local_offset The offset into the result buffer.
* @param[in] remote_buffer The target of the atomic operation.
* @param[in] remote_offset The offset into the target buffer.
* @param[in] length The length of the atomic operation.
* @param[in] operand The operand of the atomic operation.
* @param[in] user_cb The callback to invoke when events are generated from this PUT.
*
* Execute a one-sided atomic operation with one operand on peer at
* remote_buffer. length is the width of the operands in bits. user_cb is
* invoked after the atomic completes.
*/
void Atomic(
peer_ptr_t peer,
AtomicOp op,
DataObject local_ldo,
uint64_t local_offset,
NetBufferRemote *remote_buffer,
uint64_t remote_offset,
uint64_t length, // TODO: this param is ignored because we only do 64-bit atomics
int64_t operand,
lambda_net_update_t user_cb)
{
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NntiBufferRemote *nbr = (NntiBufferRemote *)remote_buffer;
NNTI_peer_t peer_hdl = peer->p;
NNTI_buffer_t remote_hdl;
t_->dt_unpack((void*)&remote_hdl, &nbr->packed[0], MAX_NET_BUFFER_REMOTE_SIZE-8);
NntiBufferLocal *local_bl;
uint32_t local_bl_offset;
local_ldo.GetDataRdmaHandle( (void **)&local_bl, local_bl_offset);
base_wr.op = NNTI_OP_ATOMIC_FADD;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = local_bl->nnti_buffer;
base_wr.local_offset = local_bl_offset + local_offset;
base_wr.remote_hdl = remote_hdl;
base_wr.remote_offset = nbr->offset + remote_offset;
base_wr.operand1 = operand;
base_wr.length = 8;
nnti::datatype::nnti_event_callback *atomic_cb = nullptr;
if (user_cb) {
user_invoking_callback *uicb = new user_invoking_callback(user_cb, new DataObject(local_ldo));
atomic_cb = new nnti::datatype::nnti_event_callback(t_, *uicb);
} else {
default_callback *dcb = new default_callback();
atomic_cb = new nnti::datatype::nnti_event_callback(t_, *dcb);
}
nnti::datatype::nnti_work_request wr(t_, base_wr, *atomic_cb);
t_->atomic_fop(&wr, &wid);
}
/*
* @brief Perform an atomic operation on an LDO at @c peer.
*
* @param[in] peer A handle to the target peer.
* @param[in] local_ldo The result of the atomic buffer.
* @param[in] local_offset The offset into the result buffer.
* @param[in] remote_buffer The target of the atomic operation.
* @param[in] remote_offset The offset into the target buffer.
* @param[in] length The length of the atomic operation.
* @param[in] operand1 The first operand of the atomic operation.
* @param[in] operand2 The second operand of the atomic operation.
* @param[in] user_cb The callback to invoke when events are generated from this PUT.
*
* Execute a one-sided atomic operation with two operands on peer at
* remote_buffer. length is the width of the operands in bits. user_cb is
* invoked after the atomic completes.
*/
void Atomic(
peer_ptr_t peer,
AtomicOp op,
DataObject local_ldo,
uint64_t local_offset,
NetBufferRemote *remote_buffer,
uint64_t remote_offset,
uint64_t length, // TODO: this param is ignored because we only do 64-bit atomics
int64_t operand1,
int64_t operand2,
lambda_net_update_t user_cb)
{
NNTI_work_request_t base_wr = NNTI_WR_INITIALIZER;
NNTI_work_id_t wid;
NntiBufferRemote *nbr = (NntiBufferRemote *)remote_buffer;
NNTI_peer_t peer_hdl = peer->p;
NNTI_buffer_t remote_hdl;
t_->dt_unpack((void*)&remote_hdl, &nbr->packed[0], MAX_NET_BUFFER_REMOTE_SIZE-8);
NntiBufferLocal *local_bl;
uint32_t local_bl_offset;
local_ldo.GetDataRdmaHandle( (void **)&local_bl, local_bl_offset);
base_wr.op = NNTI_OP_ATOMIC_CSWAP;
base_wr.flags = NNTI_OF_LOCAL_EVENT;
base_wr.trans_hdl = nnti::transports::transport::to_hdl(t_);
base_wr.peer = peer_hdl;
base_wr.local_hdl = local_bl->nnti_buffer;
base_wr.local_offset = local_bl_offset + local_offset;
base_wr.remote_hdl = remote_hdl;
base_wr.remote_offset = nbr->offset + remote_offset;
base_wr.operand1 = operand1;
base_wr.operand2 = operand2;
base_wr.length = 8;
nnti::datatype::nnti_event_callback *atomic_cb = nullptr;
if (user_cb) {
user_invoking_callback *uicb = new user_invoking_callback(user_cb, new DataObject(local_ldo));
atomic_cb = new nnti::datatype::nnti_event_callback(t_, *uicb);
} else {
default_callback *dcb = new default_callback();
atomic_cb = new nnti::datatype::nnti_event_callback(t_, *dcb);
}
nnti::datatype::nnti_work_request wr(t_, base_wr, *atomic_cb);
t_->atomic_cswap(&wr, &wid);
}
}
}
| 32.614035 | 148 | 0.620054 | [
"vector"
] |
f286cb2abebfa0519fa296b28f587a1dfa8d3c09 | 11,171 | cpp | C++ | Dev/Cpp/Test/SIMD/SIMDTest.cpp | emadurandal/Effekseer | c5cb963c9a8483258a9f972bd681b0c08b2ceef3 | [
"Apache-2.0",
"BSD-3-Clause"
] | 957 | 2015-01-03T11:44:51.000Z | 2022-03-29T06:50:43.000Z | Dev/Cpp/Test/SIMD/SIMDTest.cpp | emadurandal/Effekseer | c5cb963c9a8483258a9f972bd681b0c08b2ceef3 | [
"Apache-2.0",
"BSD-3-Clause"
] | 305 | 2015-01-03T04:04:43.000Z | 2022-03-28T13:29:11.000Z | Dev/Cpp/Test/SIMD/SIMDTest.cpp | emadurandal/Effekseer | c5cb963c9a8483258a9f972bd681b0c08b2ceef3 | [
"Apache-2.0",
"BSD-3-Clause"
] | 175 | 2015-01-22T11:58:49.000Z | 2022-03-28T07:41:56.000Z | #include <cassert>
#include "SIMD/Float4.h"
#include "SIMD/Int4.h"
#include "SIMD/Bridge.h"
#include "SIMD/Vec2f.h"
#include "SIMD/Vec3f.h"
#include "SIMD/Vec4f.h"
#include "SIMD/Mat43f.h"
#include "SIMD/Mat44f.h"
#include "SIMD/Utils.h"
#include "Effekseer.Vector2D.h"
#include "Effekseer.Vector3D.h"
#include "Effekseer.Matrix43.h"
#include "Effekseer.Matrix44.h"
#define ASSERT(e) assert(e)
//#define ASSERT(e) if (!(e)) printf("assert failed.\n");
using namespace Effekseer;
using namespace Effekseer::SIMD;
void test_Float4()
{
{
float a[4] = {1, 2, 3, 4};
Float4 ret = Float4::Load4(a);
ASSERT(ret == Float4(1, 2, 3, 4));
}
{
Float4 a(1, 2, 3, 4);
float ret[4];
Float4::Store4(ret, a);
ASSERT(ret[0] == 1.0f && ret[1] == 2.0f && ret[2] == 3.0f && ret[3] == 4.0f);
}
{
Float4 a;
a.SetX(5);
a.SetY(6);
a.SetZ(7);
a.SetW(8);
ASSERT(a == Float4(5, 6, 7, 8));
}
{
Float4 a(3, 4, 5, 6);
float x = a.GetX();
float y = a.GetY();
float z = a.GetZ();
float w = a.GetW();
ASSERT(x == 3.0f && y == 4.0f && z == 5.0f && w == 6.0f);
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8);
Float4 ret = a + b;
ASSERT(ret == Float4(6, 8, 10, 12));
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8);
Float4 ret = a - b;
ASSERT(ret == Float4(-4, -4, -4, -4));
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8);
Float4 ret = a * b;
ASSERT(ret == Float4(5, 12, 21, 32));
}
{
Float4 a(1, 2, 3, 4);
Float4 ret = a * 5;
ASSERT(ret == Float4(5, 10, 15, 20));
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8), c(9, 10, 11, 12);
Float4 ret = Float4::MulAdd(a, b, c);
ASSERT(ret == Float4(46, 62, 80, 100));
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8), c(9, 10, 11, 12);
Float4 ret = Float4::MulSub(a, b, c);
ASSERT(ret == Float4(-44, -58, -74, -92));
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8);
ASSERT(Float4::MulLane<0>(a, b) == Float4(5, 10, 15, 20));
ASSERT(Float4::MulLane<1>(a, b) == Float4(6, 12, 18, 24));
ASSERT(Float4::MulLane<2>(a, b) == Float4(7, 14, 21, 28));
ASSERT(Float4::MulLane<3>(a, b) == Float4(8, 16, 24, 32));
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8);
ASSERT(Float4::MulAddLane<0>(Float4(3), a, b) == Float4( 8, 13, 18, 23));
ASSERT(Float4::MulAddLane<1>(Float4(3), a, b) == Float4( 9, 15, 21, 27));
ASSERT(Float4::MulAddLane<2>(Float4(3), a, b) == Float4(10, 17, 24, 31));
ASSERT(Float4::MulAddLane<3>(Float4(3), a, b) == Float4(11, 19, 27, 35));
}
{
Float4 a(1, 2, 3, 4), b(5, 6, 7, 8);
ASSERT(Float4::MulSubLane<0>(Float4(30), a, b) == Float4(25, 20, 15, 10));
ASSERT(Float4::MulSubLane<1>(Float4(30), a, b) == Float4(24, 18, 12, 6));
ASSERT(Float4::MulSubLane<2>(Float4(30), a, b) == Float4(23, 16, 9, 2));
ASSERT(Float4::MulSubLane<3>(Float4(30), a, b) == Float4(22, 14, 6, -2));
}
{
Float4 a(1, -2, 3, -4);
Float4 ret = Float4::Abs(a);
ASSERT(ret == Float4(1, 2, 3, 4));
}
{
Float4 a(1, 5, 3, 7), b(4, 8, 2, 6);
Float4 ret = Float4::Min(a, b);
ASSERT(ret == Float4(1, 5, 2, 6));
}
{
Float4 a(1, 5, 3, 7), b(4, 8, 2, 6);
Float4 ret = Float4::Max(a, b);
ASSERT(ret == Float4(4, 8, 3, 7));
}
{
Float4 a(1, 2, 3, 4);
Float4 ret = Float4::Sqrt(a);
Float4 testret = Float4(1.0f, 1.4142135623730950488016887242097f, 1.7320508075688772935274463415059f, 2.0f);
ASSERT(Float4::MoveMask(Float4::NearEqual(ret, testret)) == 0xf);
}
{
Float4 a(1, 2, 3, 4);
Float4 ret = Float4::Rsqrt(a);
Float4 testret = Float4(1.0f, 0.70710678118654752440084436210485f, 0.57735026918962576450914878050195f, 0.5f);
ASSERT(Float4::MoveMask(Float4::NearEqual(ret, testret, 1e-3f)) == 0xf);
}
{
Float4 a(1, 2, 3, 4), b(5, 4, 3, 2);
ASSERT(Float4::MoveMask(Float4::Equal(a, b)) == 0x4);
ASSERT(Float4::MoveMask(Float4::NotEqual(a, b)) == 0xb);
ASSERT(Float4::MoveMask(Float4::LessThan(a, b)) == 0x3);
ASSERT(Float4::MoveMask(Float4::LessEqual(a, b)) == 0x7);
ASSERT(Float4::MoveMask(Float4::GreaterThan(a, b)) == 0x8);
ASSERT(Float4::MoveMask(Float4::GreaterEqual(a, b)) == 0xc);
}
{
Float4 a(1, 2, 3, 4);
ASSERT(a == a.Convert4i().Convert4f());
}
{
Float4 a(1, 2, 3, 4);
ASSERT(a.Convert4i() == Int4(1, 2, 3, 4));
}
{
Float4 a(1, 2, 3, 4);
ASSERT(a.Dup<0>() == Float4(1, 1, 1, 1));
ASSERT(a.Dup<1>() == Float4(2, 2, 2, 2));
ASSERT(a.Dup<2>() == Float4(3, 3, 3, 3));
ASSERT(a.Dup<3>() == Float4(4, 4, 4, 4));
}
{
Float4 a(1, 2, 3, 4), b(4, 3, 2, 1);
Float4 mask = Float4::LessThan(a, b);
Float4 ret = Float4::Select(mask, a, b);
ASSERT(ret == Float4(1, 2, 2, 1));
}
}
void test_Vec2f()
{
{
Vec2f a(2, 3), b(4, 5);
Vec2f c = a + b;
ASSERT(c == Vec2f(6, 8));
}
{
Vec2f a(2, 3), b(4, 5);
Vec2f c = a - b;
ASSERT(c == Vec2f(-2, -2));
}
}
void test_Vec3f()
{
{
Vec3f a(2, 3, 4), b(4, 5, 6);
Vec3f c = a + b;
ASSERT(c == Vec3f(6, 8, 10));
}
{
Vec3f a(2, 3, 4), b(4, 5, 6);
Vec3f c = a - b;
ASSERT(c == Vec3f(-2, -2, -2));
}
{
Vec3f a(2, 3, 4);
Vec3f c = a * 5.0f;
ASSERT(c == Vec3f(10, 15, 20));
}
{
Vec3f a(2, 3, 4);
Vec3f c = a / 2.0f;
ASSERT(c == Vec3f(1.0f, 1.5f, 2.0f));
}
{
Vec3f a(2, 3, 4), b(4, 5, 6);
float c = Vec3f::Dot(a, b);
ASSERT(c == 47);
}
{
Vec3f a(2, 3, 4), b(4, 5, 6);
Vec3f c = Vec3f::Cross(a, b);
ASSERT(c == Vec3f(-2, 4, -2));
}
}
void test_Vec4f()
{
}
void test_Mat43f()
{
{
Mat43f a(
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12);
Mat43f b(
12, 11, 10,
9, 8, 7,
6, 5, 4,
3, 2, 1);
Mat43f ret = a * b;
ASSERT(ret == Mat43f(
48, 42, 36,
129, 114, 99,
210, 186, 162,
294, 260, 226)
);
}
{
Vec3f a(1, 2, 3);
Mat43f b(
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12);
Vec3f ret = Vec3f::Transform(a, b);
ASSERT(ret == Vec3f(40, 47, 54));
}
{
Mat43f a = Mat43f::Scaling(5.0f, 6.0f, 7.0f);
Matrix43 b; b.Scaling(5.0f, 6.0f, 7.0f);
ASSERT(a == Mat43f(b));
}
{
Mat43f a = Mat43f::RotationX(12);
Matrix43 b; b.RotationX(12);
ASSERT(a == Mat43f(b));
}
{
Mat43f a = Mat43f::RotationY(12);
Matrix43 b; b.RotationY(12);
ASSERT(a == Mat43f(b));
}
{
Mat43f a = Mat43f::RotationZ(12);
Matrix43 b; b.RotationZ(12);
ASSERT(a == Mat43f(b));
}
{
Mat43f a = Mat43f::RotationXYZ(12, 34, 56);
Matrix43 b; b.RotationXYZ(12, 34, 56);
ASSERT(a == Mat43f(b));
}
{
Mat43f a = Mat43f::RotationAxis(Vec3f(1, 2, 3), 56);
Matrix43 b; b.RotationAxis(Vector3D(1, 2, 3), 56);
ASSERT(a == Mat43f(b));
}
{
Mat43f a = Mat43f::SRT(Vec3f(1, 2, 3), Mat43f::RotationXYZ(12, 34, 56), Vec3f(3.0f, 2.0f, 0.5f));
Matrix43 b; b.RotationXYZ(12, 34, 56);
Matrix43 c; c.SetSRT(Vector3D(1, 2, 3), b, Vector3D(3.0f, 2.0f, 0.5f));
ASSERT(a == Mat43f(c));
Vec3f s1, t1;
Mat43f r1;
a.GetSRT(s1, r1, t1);
Vector3D s2, t2;
Matrix43 r2;
c.GetSRT(s2, r2, t2);
ASSERT(Vec3f::Equal(s1, Vec3f(s2), 0.001f));
ASSERT(Mat43f::Equal(r1, Mat43f(r2), 0.001f));
ASSERT(Vec3f::Equal(t1, Vec3f(t2), 0.001f));
}
}
void test_Mat44f()
{
{
Mat44f a(
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16);
Mat44f b(
16, 15, 14, 13,
12, 11, 10, 9,
8, 7, 6, 5,
4, 3, 2, 1);
Mat44f ret = a * b;
ASSERT(ret == Mat44f(
80, 70, 60, 50,
240, 214, 188, 162,
400, 358, 316, 274,
560, 502, 444, 386)
);
}
{
Vec3f a(1, 2, 3);
Mat44f b(
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16);
Vec3f ret = Vec3f::Transform(a, b);
ASSERT(ret == Vec3f(51, 58, 65));
}
{
Mat44f a(
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16);
Mat44f b = a.Transpose();
ASSERT(b == Mat44f(
1, 5, 9, 13,
2, 6, 10, 14,
3, 7, 11, 15,
4, 8, 12, 16));
}
}
void test_Int4()
{
{
int32_t a[4] = {1, 2, 3, 4};
Int4 ret = Int4::Load4(a);
ASSERT(ret == Int4(1, 2, 3, 4));
}
{
Int4 a(1, 2, 3, 4);
int32_t ret[4];
Int4::Store4(ret, a);
ASSERT(ret[0] == 1.0f && ret[1] == 2.0f && ret[2] == 3.0f && ret[3] == 4.0f);
}
{
Int4 a;
a.SetX(5);
a.SetY(6);
a.SetZ(7);
a.SetW(8);
ASSERT(a == Int4(5, 6, 7, 8));
}
{
Int4 a(3, 4, 5, 6);
int32_t x = a.GetX();
int32_t y = a.GetY();
int32_t z = a.GetZ();
int32_t w = a.GetW();
ASSERT(x == 3.0f && y == 4.0f && z == 5.0f && w == 6.0f);
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8);
Int4 ret = a + b;
ASSERT(ret == Int4(6, 8, 10, 12));
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8);
Int4 ret = a - b;
ASSERT(ret == Int4(-4, -4, -4, -4));
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8);
Int4 ret = a * b;
ASSERT(ret == Int4(5, 12, 21, 32));
}
{
Int4 a(1, 2, 3, 4);
Int4 ret = a * 5;
ASSERT(ret == Int4(5, 10, 15, 20));
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8), c(9, 10, 11, 12);
Int4 ret = Int4::MulAdd(a, b, c);
ASSERT(ret == Int4(46, 62, 80, 100));
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8), c(9, 10, 11, 12);
Int4 ret = Int4::MulSub(a, b, c);
ASSERT(ret == Int4(-44, -58, -74, -92));
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8);
ASSERT(Int4::MulLane<0>(a, b) == Int4(5, 10, 15, 20));
ASSERT(Int4::MulLane<1>(a, b) == Int4(6, 12, 18, 24));
ASSERT(Int4::MulLane<2>(a, b) == Int4(7, 14, 21, 28));
ASSERT(Int4::MulLane<3>(a, b) == Int4(8, 16, 24, 32));
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8);
ASSERT(Int4::MulAddLane<0>(Int4(3), a, b) == Int4( 8, 13, 18, 23));
ASSERT(Int4::MulAddLane<1>(Int4(3), a, b) == Int4( 9, 15, 21, 27));
ASSERT(Int4::MulAddLane<2>(Int4(3), a, b) == Int4(10, 17, 24, 31));
ASSERT(Int4::MulAddLane<3>(Int4(3), a, b) == Int4(11, 19, 27, 35));
}
{
Int4 a(1, 2, 3, 4), b(5, 6, 7, 8);
ASSERT(Int4::MulSubLane<0>(Int4(30), a, b) == Int4(25, 20, 15, 10));
ASSERT(Int4::MulSubLane<1>(Int4(30), a, b) == Int4(24, 18, 12, 6));
ASSERT(Int4::MulSubLane<2>(Int4(30), a, b) == Int4(23, 16, 9, 2));
ASSERT(Int4::MulSubLane<3>(Int4(30), a, b) == Int4(22, 14, 6, -2));
}
{
Int4 a(1, -2, 3, -4);
Int4 ret = Int4::Abs(a);
ASSERT(ret == Int4(1, 2, 3, 4));
}
{
Int4 a(1, 5, 3, 7), b(4, 8, 2, 6);
Int4 ret = Int4::Min(a, b);
ASSERT(ret == Int4(1, 5, 2, 6));
}
{
Int4 a(1, 5, 3, 7), b(4, 8, 2, 6);
Int4 ret = Int4::Max(a, b);
ASSERT(ret == Int4(4, 8, 3, 7));
}
{
Int4 a(1, 2, 3, 4);
Int4 ret = Int4::ShiftL<1>(a);
ASSERT(ret == Int4(2, 4, 6, 8));
}
{
Int4 a(1, 2, 3, 4);
Int4 ret = Int4::ShiftR<1>(a);
ASSERT(ret == Int4(0, 1, 1, 2));
}
{
Int4 a(-4, -3, 2, 1);
Int4 ret = Int4::ShiftRA<1>(a);
ASSERT(ret == Int4(-2, -2, 1, 0));
}
{
Int4 a(1, 2, 3, 4), b(5, 4, 3, 2);
ASSERT(Int4::MoveMask(Int4::Equal(a, b)) == 0x4);
ASSERT(Int4::MoveMask(Int4::NotEqual(a, b)) == 0xb);
ASSERT(Int4::MoveMask(Int4::LessThan(a, b)) == 0x3);
ASSERT(Int4::MoveMask(Int4::LessEqual(a, b)) == 0x7);
ASSERT(Int4::MoveMask(Int4::GreaterThan(a, b)) == 0x8);
ASSERT(Int4::MoveMask(Int4::GreaterEqual(a, b)) == 0xc);
}
{
Int4 a(1, 2, 3, 4);
ASSERT(a == a.Convert4f().Convert4i());
}
{
Int4 a(1, 2, 3, 4);
ASSERT(a.Convert4f() == Float4(1.0f, 2.0f, 3.0f, 4.0f));
}
}
int main(int argc, char *argv[])
{
test_Float4();
test_Vec2f();
test_Vec3f();
test_Vec4f();
test_Mat43f();
test_Mat44f();
test_Int4();
return 0;
}
| 21.157197 | 112 | 0.518485 | [
"transform"
] |
f2afc135a11fdd5f034dae85123ece7e8ed1fe6b | 4,021 | cpp | C++ | src/core/lib/core_data_model/asset_browser/asset_browser_model20.cpp | wgsyd/wgtf | d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed | [
"BSD-3-Clause"
] | 28 | 2016-06-03T05:28:25.000Z | 2019-02-14T12:04:31.000Z | src/core/lib/core_data_model/asset_browser/asset_browser_model20.cpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | null | null | null | src/core/lib/core_data_model/asset_browser/asset_browser_model20.cpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | 14 | 2016-06-03T05:52:27.000Z | 2019-03-21T09:56:03.000Z |
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
// asset_browser_model.cpp
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright (c) Wargaming.net. All rights reserved.
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "asset_browser_model20.hpp"
#include "i_asset_preview_provider.hpp"
#include "core_string_utils/file_path.hpp"
#include "core_object/managed_object.hpp"
#include <unordered_map>
#include "image_preview.hpp"
#include "core_ui_framework/i_ui_framework.hpp"
#include "core_dependency_system/depends.hpp"
namespace wgt
{
namespace AssetBrowser20_Local
{
class ImageFilePreviewProvider : public IAssetPreviewProvider
{
public:
ImageFilePreviewProvider()
:imagePreview_(std::make_unique<ImagePreview>())
{
}
virtual ObjectHandle getPreview(const char* filePath) override
{
if (!supportPreview(filePath))
{
return nullptr;
}
imagePreview_->setAssetPath(filePath);
return imagePreview_.getHandle();
}
private:
bool supportPreview(const char* filePath) const
{
DependsLocal<IUIFramework> depends;
auto uiFramework = depends.get<IUIFramework>();
if (uiFramework == nullptr)
{
return false;
}
return uiFramework->hasThumbnail(filePath);
}
ManagedObject<ImagePreview> imagePreview_;
};
}
namespace AssetBrowser20
{
struct AssetBrowserModel::Impl
{
Impl()
: assetPreviewProvider_()
, assetModel_(nullptr)
, iconSize_(64)
{
}
std::weak_ptr<IAssetPreviewProvider> assetPreviewProvider_;
AbstractItemModel* assetModel_;
int iconSize_;
std::string programSelectedItemPath_;
Signal<void(Variant&)> programSelectedItemChanged_;
std::vector<std::string> nameFilters_;
AssetBrowser20_Local::ImageFilePreviewProvider defaultFilePreviewProvider_;
};
AssetBrowserModel::AssetBrowserModel()
: pImpl_(new AssetBrowserModel::Impl)
{
}
AssetBrowserModel::~AssetBrowserModel()
{
}
AbstractItemModel* AssetBrowserModel::getAssetModel() const
{
return pImpl_->assetModel_;
}
const std::vector<std::string>& AssetBrowserModel::getNameFilters() const
{
return pImpl_->nameFilters_;
}
int AssetBrowserModel::getIconSize() const
{
return pImpl_->iconSize_;
}
void AssetBrowserModel::programSelectItemByPath(const char* path)
{
pImpl_->programSelectedItemPath_ = path ? path : "";
pImpl_->programSelectedItemChanged_(Variant(pImpl_->programSelectedItemPath_.c_str()));
}
const char* AssetBrowserModel::getProgramSelectedItemPath() const
{
return pImpl_->programSelectedItemPath_.c_str();
}
void AssetBrowserModel::getProgramSelectedItemSignal(Signal<void(Variant&)>** result) const
{
*result = const_cast<Signal<void(Variant&)>*>(&pImpl_->programSelectedItemChanged_);
}
Variant AssetBrowserModel::assetPreview(std::string assetPath)
{
ObjectHandle objectHandle = nullptr;
if (pImpl_->assetPreviewProvider_.lock() != nullptr)
{
objectHandle = pImpl_->assetPreviewProvider_.lock()->getPreview(assetPath.c_str());
}
else
{
objectHandle = pImpl_->defaultFilePreviewProvider_.getPreview(assetPath.c_str());
}
if (!objectHandle.isValid())
{
return Variant();
}
return objectHandle;
}
void AssetBrowserModel::setAssetModel(AbstractItemModel* assetModel)
{
pImpl_->assetModel_ = assetModel;
}
void AssetBrowserModel::setNameFilters(const std::vector<std::string>& nameFilters)
{
pImpl_->nameFilters_ = nameFilters;
}
void AssetBrowserModel::setIconSize(int iconSize)
{
pImpl_->iconSize_ = iconSize;
}
void AssetBrowserModel::setAssetPreviewProvider(std::shared_ptr<IAssetPreviewProvider> assetPreviewProvider)
{
pImpl_->assetPreviewProvider_ = assetPreviewProvider;
}
}
} // end namespace wgt
| 25.13125 | 177 | 0.668242 | [
"vector"
] |
f2b17d75ee702cafe29febff95f17981d3879259 | 990 | hpp | C++ | data-manager/src/server/dataManagerServer/session/frameElaboration/JPEGDecoder.hpp | Saafke/4dm | 68e235164afb1f127def35e9c15ca883ec1426d4 | [
"MIT"
] | 8 | 2021-03-16T06:48:57.000Z | 2021-11-30T09:34:09.000Z | data-manager/src/server/dataManagerServer/session/frameElaboration/JPEGDecoder.hpp | Saafke/4dm | 68e235164afb1f127def35e9c15ca883ec1426d4 | [
"MIT"
] | null | null | null | data-manager/src/server/dataManagerServer/session/frameElaboration/JPEGDecoder.hpp | Saafke/4dm | 68e235164afb1f127def35e9c15ca883ec1426d4 | [
"MIT"
] | 3 | 2021-05-02T15:38:17.000Z | 2021-07-07T09:19:48.000Z | /*
* JPEGDecoder.hpp
*
* Created on: Apr 23, 2019
* Author: mbortolon
*/
#ifndef SRC_DATAMANAGERSERVER_SESSION_FRAMEELABORATION_JPEGDECODER_HPP_
#define SRC_DATAMANAGERSERVER_SESSION_FRAMEELABORATION_JPEGDECODER_HPP_
#include "AbstractDecoder.hpp"
#include <string>
#include <vector>
#include "src/common/dataManager/frameContainer/FrameDecapsulate.hpp"
#include "src/common/dataManager/frameContainer/Frame.hpp"
namespace dataManagerServer {
namespace session {
namespace frameElaboration {
class JPEGDecoder: public dataManagerServer::session::frameElaboration::AbstractDecoder {
public:
virtual ~JPEGDecoder();
bool init(std::string& initBytes);
dataManager::frameContainer::FrameDecapsulate* elaborateFrame(dataManager::frameContainer::Frame* frame);
private:
std::vector<int> params;
};
} /* namespace frameElaboration */
} /* namespace session */
} /* namespace dataManagerServer */
#endif /* SRC_DATAMANAGERSERVER_SESSION_FRAMEELABORATION_JPEGDECODER_HPP_ */
| 26.052632 | 106 | 0.79697 | [
"vector"
] |
f2c62059a98a0279c23bb9e177e621e25febd3a9 | 12,512 | cpp | C++ | native/dqnagent.cpp | xdavidwu/2048-dqn | 3e97bff69d7ce51bfb73cdbf9cbfd0c1d0898d29 | [
"MIT"
] | 3 | 2019-01-08T12:58:28.000Z | 2019-01-12T11:32:59.000Z | native/dqnagent.cpp | xdavidwu/2048-dqn | 3e97bff69d7ce51bfb73cdbf9cbfd0c1d0898d29 | [
"MIT"
] | 1 | 2019-01-08T12:58:17.000Z | 2019-01-09T10:14:56.000Z | native/dqnagent.cpp | xdavidwu/2048-dqn | 3e97bff69d7ce51bfb73cdbf9cbfd0c1d0898d29 | [
"MIT"
] | null | null | null | #include "2048.h"
#include <cmath>
#include <vector>
#include <random>
#include <thread>
#include <experimental/algorithm>
#include <tensorflow/cc/client/client_session.h>
#include <tensorflow/cc/ops/standard_ops.h>
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/cc/framework/gradients.h>
#include <absl/strings/string_view.h>
#include <sys/time.h>
using namespace tensorflow;
using namespace tensorflow::ops;
#define MEM_SIZE 1<<17
#define MEM_START_TRAIN 1<<17
#define BATCH 1<<9
#define QT_UPDATE_INT 64
#define PRINT_INT (1L<<16)
#define DOUBLE_DQN 0
#define GAMMA 0.94f
#define LEARNING_RATE 0.000005
//static float LEARNING_RATE=1;
typedef struct{
cell_t s[16];
dir_t a;
score_t r;
cell_t sp[16];
int isterm;
}mem_t;
static std::vector<mem_t> replaymem(MEM_SIZE);
static int replaymem_idx=0,replaymem_full=0;
static float epsilon;
static int train_counter=0;
static int print_counter=0;
static int block_train=0;
static Scope scope=Scope::NewRootScope();
static Placeholder x(scope,DT_FLOAT);
static Placeholder qt_x(scope,DT_FLOAT);
static Placeholder yp(scope,DT_FLOAT);
static Variable cb(scope,{256},DT_FLOAT);
static Variable cw(scope,{2,2,1,256},DT_FLOAT);
static Variable cb2(scope,{64},DT_FLOAT);
static Variable cw2(scope,{2,2,256,64},DT_FLOAT);
static Variable b(scope,{128},DT_FLOAT);
static Variable w(scope,{256,128},DT_FLOAT);
static Variable b2(scope,{4},DT_FLOAT);
static Variable w2(scope,{128,4},DT_FLOAT);
static Variable cb_ms(scope,{256},DT_FLOAT);
static Variable cw_ms(scope,{2,2,1,256},DT_FLOAT);
static Variable cb2_ms(scope,{64},DT_FLOAT);
static Variable cw2_ms(scope,{2,2,256,64},DT_FLOAT);
static Variable b_ms(scope,{128},DT_FLOAT);
static Variable w_ms(scope,{256,128},DT_FLOAT);
static Variable b2_ms(scope,{4},DT_FLOAT);
static Variable w2_ms(scope,{128,4},DT_FLOAT);
static Variable cb_mom(scope,{256},DT_FLOAT);
static Variable cw_mom(scope,{2,2,1,256},DT_FLOAT);
static Variable cb2_mom(scope,{64},DT_FLOAT);
static Variable cw2_mom(scope,{2,2,256,64},DT_FLOAT);
static Variable b_mom(scope,{128},DT_FLOAT);
static Variable w_mom(scope,{256,128},DT_FLOAT);
static Variable b2_mom(scope,{4},DT_FLOAT);
static Variable w2_mom(scope,{128,4},DT_FLOAT);
static Variable qt_cb(scope,{256},DT_FLOAT);
static Variable qt_cw(scope,{2,2,1,256},DT_FLOAT);
static Variable qt_cb2(scope,{64},DT_FLOAT);
static Variable qt_cw2(scope,{2,2,256,64},DT_FLOAT);
static Variable qt_b(scope,{128},DT_FLOAT);
static Variable qt_w(scope,{256,128},DT_FLOAT);
static Variable qt_b2(scope,{4},DT_FLOAT);
static Variable qt_w2(scope,{128,4},DT_FLOAT);
static Reshape xp(scope,x,{-1,4,4,1});
static Relu co(scope,Add(scope,Conv2D(scope,xp,cw,{1,1,1,1},absl::string_view("VALID")),cb));
static Relu co2(scope,Add(scope,Conv2D(scope,co,cw2,{1,1,1,1},absl::string_view("VALID")),cb2));
static Reshape xf(scope,co2,{-1,4*64});
static Relu o(scope,Add(scope,MatMul(scope,xf,w),b));
static Add y(scope,MatMul(scope,o,w2),b2);
static Max ymax(scope,y,1);
static ArgMax argmax(scope,y,1);
static Mean loss(scope,Mean(scope,Square(scope,Subtract(scope,yp,y)),1),0);
static Reshape qt_xp(scope,qt_x,{-1,4,4,1});
static Relu qt_co(scope,Add(scope,Conv2D(scope,qt_xp,qt_cw,{1,1,1,1},absl::string_view("VALID")),qt_cb));
static Relu qt_co2(scope,Add(scope,Conv2D(scope,qt_co,qt_cw2,{1,1,1,1},absl::string_view("VALID")),qt_cb2));
static Reshape qt_xf(scope,qt_co2,{-1,4*64});
static Relu qt_o(scope,Add(scope,MatMul(scope,qt_xf,qt_w),qt_b));
static Add qt_y(scope,MatMul(scope,qt_o,qt_w2),qt_b2);
static Max qt_ymax(scope,qt_y,1);
static std::vector<Output> qt_update({
Assign(scope,qt_cb,cb),
Assign(scope,qt_cw,cw),
Assign(scope,qt_cb2,cb2),
Assign(scope,qt_cw2,cw2),
Assign(scope,qt_b,b),
Assign(scope,qt_w,w),
Assign(scope,qt_b2,b2),
Assign(scope,qt_w2,w2)
});
static std::vector<Output> q_init({
Assign(scope,cb,Fill(scope,{256},float(0.0))),
Assign(scope,cw,Multiply(scope,TruncatedNormal(scope,{2,2,1,256},DT_FLOAT),Fill(scope,{2,2,1,256},float(sqrt(2.0/(2*2*1+256)))))),
Assign(scope,cb2,Fill(scope,{64},float(0.0))),
Assign(scope,cw2,Multiply(scope,TruncatedNormal(scope,{2,2,256,64},DT_FLOAT),Fill(scope,{2,2,256,64},float{sqrt(2.0/(2*2*256+64))}))),
Assign(scope,b,Fill(scope,{128},float(0.0))),
Assign(scope,w,Multiply(scope,TruncatedNormal(scope,{256,128},DT_FLOAT),Fill(scope,{256,128},float(sqrt(2.0/(256+128)))))),
Assign(scope,b2,Fill(scope,{4},float(0.0))),
Assign(scope,w2,Multiply(scope,TruncatedNormal(scope,{128,4},DT_FLOAT),Fill(scope,{128,4},float(sqrt(2.0/(128+4))))))
});
static std::vector<Output> rms_init({
Assign(scope,cb_ms,ZerosLike(scope,cb)),
Assign(scope,cw_ms,ZerosLike(scope,cw)),
Assign(scope,cb2_ms,ZerosLike(scope,cb2)),
Assign(scope,cw2_ms,ZerosLike(scope,cw2)),
Assign(scope,b_ms,ZerosLike(scope,b)),
Assign(scope,w_ms,ZerosLike(scope,w)),
Assign(scope,b2_ms,ZerosLike(scope,b2)),
Assign(scope,w2_ms,ZerosLike(scope,w2)),
Assign(scope,cb_mom,ZerosLike(scope,cb)),
Assign(scope,cw_mom,ZerosLike(scope,cw)),
Assign(scope,cb2_mom,ZerosLike(scope,cb2)),
Assign(scope,cw2_mom,ZerosLike(scope,cw2)),
Assign(scope,b_mom,ZerosLike(scope,b)),
Assign(scope,w_mom,ZerosLike(scope,w)),
Assign(scope,b2_mom,ZerosLike(scope,b2)),
Assign(scope,w2_mom,ZerosLike(scope,w2))
});
static std::vector<Output> step;
static ClientSession* cs;
// 2048 max 1<<17 max r < 1<<18 /4 1<<16
static float log2tbl[1<<16];
static std::thread* prefetch_thread=nullptr;
static std::vector<mem_t> bat(BATCH);
static std::vector<mem_t>::iterator it;
static float loss_sum=0.0;
//static long us_sum=0;
static Tensor *s,*sp;
static Tensor *s1=new Tensor(DT_FLOAT, TensorShape{BATCH,4,4}),*sp1=new Tensor(DT_FLOAT, TensorShape{BATCH,4,4});
static Tensor *s2=new Tensor(DT_FLOAT, TensorShape{BATCH,4,4}),*sp2=new Tensor(DT_FLOAT, TensorShape{BATCH,4,4});
static inline void gen_log2(){
for(int a=4;a<(1<<18);a+=4) log2tbl[a>>2]=std::log2f(a);
}
static inline float dbl_rand(){
return (float)rand()/RAND_MAX;
}
void dqnagent_pushmem(cell_t *s,dir_t a,score_t r,cell_t *sp,int isterm){
if(unlikely(block_train))return;
mem_t nmem={.a=a,.r=r,.isterm=isterm};
memcpy(nmem.s,s,sizeof(cell_t)*16);
memcpy(nmem.sp,sp,sizeof(cell_t)*16);
replaymem[replaymem_idx++]=nmem;
if(unlikely(replaymem_idx==MEM_SIZE)){
replaymem_full=1;
replaymem_idx=0;
}
}
static void dqnagent_init(){
SessionOptions opt;
//opt.config.mutable_gpu_options()->set_per_process_gpu_memory_fraction(0.9);
//opt.config.mutable_graph_options()->mutable_optimizer_options()->set_global_jit_level(tensorflow::OptimizerOptions::OFF);
cs=new ClientSession(scope,opt);
TF_CHECK_OK(cs->Run({},q_init,nullptr));
TF_CHECK_OK(cs->Run({},rms_init,nullptr));
TF_CHECK_OK(cs->Run({},{qt_update},nullptr));
std::vector<Output> grad_outputs;
TF_CHECK_OK(AddSymbolicGradients(scope,{loss},{cb,cw,cb2,cw2,b,w,b2,w2},&grad_outputs));
Input::Initializer lr(float(LEARNING_RATE)),rho(float(0.9)),ep(float(1.0e-10)),mom(float(0.0));
step.push_back(ApplyRMSProp(scope,cb,cb_ms,cb_mom,lr,rho,mom,ep,{grad_outputs[0]}));
step.push_back(ApplyRMSProp(scope,cw,cw_ms,cw_mom,lr,rho,mom,ep,{grad_outputs[1]}));
step.push_back(ApplyRMSProp(scope,cb2,cb2_ms,cb2_mom,lr,rho,mom,ep,{grad_outputs[2]}));
step.push_back(ApplyRMSProp(scope,cw2,cw2_ms,cw2_mom,lr,rho,mom,ep,{grad_outputs[3]}));
step.push_back(ApplyRMSProp(scope,b,b_ms,b_mom,lr,rho,mom,ep,{grad_outputs[4]}));
step.push_back(ApplyRMSProp(scope,w,w_ms,w_mom,lr,rho,mom,ep,{grad_outputs[5]}));
step.push_back(ApplyRMSProp(scope,b2,b2_ms,b2_mom,lr,rho,mom,ep,{grad_outputs[6]}));
step.push_back(ApplyRMSProp(scope,w2,w2_ms,w2_mom,lr,rho,mom,ep,{grad_outputs[7]}));
}
Tensor x_d(DT_FLOAT, TensorShape{1,4,4});
auto x_df=x_d.flat<float>().data();
dir_t dqnagent_getact(cell_t *s){
if(unlikely(dbl_rand()<epsilon)){
return static_cast<dir_t>(rand()&0x3);
}
for(int a=0;a<16;a++) x_df[a]=(float)s[a];
std::vector<Tensor> outputs;
TF_CHECK_OK(cs->Run({{x,x_d}},{argmax},&outputs));
return static_cast<dir_t>(outputs[0].scalar<int>()());
}
static void sample_thr(){
if(unlikely(replaymem_full)) it=replaymem.end();
else it=replaymem.begin()+replaymem_idx-1;
std::experimental::sample(replaymem.begin(),it,bat.begin(),BATCH,std::mt19937_64{std::random_device{}()});
auto mf=((print_counter&0x1)?s1:s2)->flat<float>().data();
auto mfp=((print_counter&0x1)?sp1:sp2)->flat<float>().data();
#pragma omp parallel for num_threads(2)
for(int i=0;i<BATCH;i++){
for(int j=0;j<16;j++){
mf[i*16+j]=(float)bat[i].s[j];
mfp[i*16+j]=(float)bat[i].sp[j];
}
}
}
static Tensor q_,ya,ynxt,ym;
//struct timeval tp,ta;
void dqnagent_train(){
if(unlikely(block_train||((!replaymem_full)&&replaymem_idx<MEM_START_TRAIN))) return;
if(unlikely(prefetch_thread==nullptr)){
if(replaymem_full) it=replaymem.end();
else it=replaymem.begin()+replaymem_idx-1;
std::experimental::sample(replaymem.begin(),it,bat.begin(),BATCH,std::mt19937_64{std::random_device{}()});
auto mf=((print_counter&0x1)?s1:s2)->flat<float>().data();
auto mfp=((print_counter&0x1)?sp1:sp2)->flat<float>().data();
#pragma omp parallel for num_threads(2)
for(int i=0;i<BATCH;i++){
for(int j=0;j<16;j++){
mf[i*16+j]=(float)bat[i].s[j];
mfp[i*16+j]=(float)bat[i].sp[j];
}
}
}
else{
//gettimeofday(&tp,NULL);
prefetch_thread->join();
delete prefetch_thread;
//gettimeofday(&ta,NULL);
//us_sum+=(ta.tv_sec-tp.tv_sec)*1000000+ta.tv_usec-tp.tv_usec;
}
print_counter++;
prefetch_thread=new std::thread(sample_thr);
s=(print_counter&0x1)?s2:s1;
sp=(print_counter&0x1)?sp2:sp1;
std::vector<Tensor> outputs;
if(DOUBLE_DQN){
TF_CHECK_OK(cs->Run({{x,*s}},{y},&outputs));
q_=outputs[0];
TF_CHECK_OK(cs->Run({{x,*sp},{qt_x,*sp}},{argmax,qt_y},&outputs));
ya=outputs[0];
ynxt=outputs[1];
}
else{
TF_CHECK_OK(cs->Run({{qt_x,*sp},{x,*s}},{y,qt_ymax},&outputs));
q_=outputs[0];
ym=outputs[1];
}
float r;
auto qm=q_.matrix<float>();
if(DOUBLE_DQN){
auto ynxtm=ynxt.matrix<float>();
auto yam=ya.flat<int>().data();
for(int i=0;i<BATCH;i++){
r=(bat[i].r)?log2tbl[bat[i].r>>2]:0.0;
if(unlikely(bat[i].isterm)){
qm(i,bat[i].a)=r;
}
else{
qm(i,bat[i].a)=r+GAMMA*ynxtm(i,yam[i]);
}
}
}
else{
auto ymm=ym.flat<float>().data();
for(int i=0;i<BATCH;i++){
r=(bat[i].r)?log2tbl[bat[i].r>>2]:0.0;
if(unlikely(bat[i].isterm)){
qm(i,bat[i].a)=r;
}
else{
qm(i,bat[i].a)=r+GAMMA*ymm[i];
}
}
}
TF_CHECK_OK(cs->Run({{x,*s},{yp,q_}},{step},nullptr));
if(likely(print_counter&0xF))return;
TF_CHECK_OK(cs->Run({{x,*s},{yp,q_}},{loss},&outputs));
loss_sum+=outputs[0].scalar<float>()();
if(unlikely(++train_counter==QT_UPDATE_INT)){
train_counter=0;
TF_CHECK_OK(cs->Run({},{qt_update},nullptr));
}
if(unlikely(print_counter==PRINT_INT)){
print_counter=0;
// std::cout<<us_sum/PRINT_INT<<std::endl;
// us_sum=0;
// TF_CHECK_OK(cs->Run({{x,s},{yp,q_}},{y,loss},&outputs));
//for(int i=0;i<16;i++)std::cout<<bat[BATCH-1].s[i]<<" ";
//std::cout<<"\n"<<bat[BATCH-1].a<<" "<<bat[BATCH-1].r<<"\n";
//for(int i=0;i<16;i++)std::cout<<bat[BATCH-1].sp[i]<<" ";
//std::cout<<bat[BATCH-1].isterm<<std::endl;
// std::cout<<outputs[1].scalar<float>()<<" "<<q_.matrix<float>()(BATCH-1,bat[BATCH-1].a)<<" "<<outputs[0].matrix<float>()(BATCH-1,bat[BATCH-1].a)<<" "<<r<<std::endl;
// prefetch_thread=new std::thread(sample_thr);
std::cout<<loss_sum/(PRINT_INT>>4)<<std::endl;
loss_sum=0.0;
}
}
int main(){
gen_log2();
dqnagent_init();
agent_t dqnagent={.getact=dqnagent_getact,.pushmem=dqnagent_pushmem,.train=dqnagent_train};
srand(time(NULL));
epsilon=1.0f;
double epsilon_append=0.98;
double epsilon_bak;
while((!replaymem_full)&&replaymem_idx<MEM_START_TRAIN) episode(dqnagent);
puts("Filled");
FZTE(j,400){
unsigned int tscore=0,tstep=0;
epsilon=1.0/(j*1.5/10.0);
FZTE(i,100){
log_t elog=episode(dqnagent);
tscore+=elog.score;
tstep+=elog.step;
//epsilon_append*=0.999f;//7f;
//epsilon=0.03+epsilon_append;
}
printf("Train %d %f %u %u %f\n",j,epsilon,tscore/100,tstep/100,(float)tscore/tstep);
if(!(j%4)){
epsilon_bak=epsilon;
epsilon=0.0f;
block_train=1;
tscore=0;
tstep=0;
FZTE(i,100){
log_t elog=episode(dqnagent);
tscore+=elog.score;
tstep+=elog.step;
}
printf("Test %d %f %u %u %f\n",j,epsilon,tscore/100,tstep/100,(float)tscore/tstep);
block_train=0;
epsilon=epsilon_bak;
}
}
delete cs;
return 0;
}
| 34.373626 | 167 | 0.702925 | [
"vector"
] |
f2d545f79846d97070a5a8c387b71a44483ee67e | 864 | cpp | C++ | DSA-450/01Array/24longestSeq.cpp | vikkastiwari/cpp-coding-questions | 020790e1a3b26c7b24991427004730b3f0785c71 | [
"MIT"
] | null | null | null | DSA-450/01Array/24longestSeq.cpp | vikkastiwari/cpp-coding-questions | 020790e1a3b26c7b24991427004730b3f0785c71 | [
"MIT"
] | null | null | null | DSA-450/01Array/24longestSeq.cpp | vikkastiwari/cpp-coding-questions | 020790e1a3b26c7b24991427004730b3f0785c71 | [
"MIT"
] | null | null | null | // question link: https://leetcode.com/problems/longest-consecutive-sequence/
#include <bits/stdc++.h>
using namespace std;
int longestConsecutive(vector<int> &nums)
{
if (nums.size() == 1)
return 1;
sort(nums.begin(), nums.end());
vector<int> seq;
int count = 0, max = 0;
seq.push_back(nums[0]);
for (int i = 1; i < nums.size(); i++)
{
if (nums[i] != nums[i - 1])
{
seq.push_back(nums[i]);
}
}
for (int i = 0; i < seq.size(); i++)
{
if (i > 0 && (seq[i] == seq[i - 1] + 1))
{
count++;
}
else
{
count = 1;
}
if (count > max)
max = count;
}
return max;
}
int main()
{
vector<int> arr = {100, 4, 200, 1, 3, 2};
cout << longestConsecutive(arr) << endl;
return 0;
}
| 18.782609 | 77 | 0.457176 | [
"vector"
] |
f2d8847532361a1b7ea154d493f9e8f5e689ac54 | 12,964 | cpp | C++ | fundamentals/battleship/memberfunc.cpp | kaanguney/c_plus_plus | cc7c4d26184ea9dd86aec588aa8a07dbcd65b33a | [
"MIT"
] | null | null | null | fundamentals/battleship/memberfunc.cpp | kaanguney/c_plus_plus | cc7c4d26184ea9dd86aec588aa8a07dbcd65b33a | [
"MIT"
] | null | null | null | fundamentals/battleship/memberfunc.cpp | kaanguney/c_plus_plus | cc7c4d26184ea9dd86aec588aa8a07dbcd65b33a | [
"MIT"
] | null | null | null | #include "myboard.h"
#include "players.h"
#include <iostream>
#include <iomanip> // for setw
using namespace std;
myboard::myboard() { // default constructor for myboard.h, initialize all to zero...
for(int i=0; i<6; i++) {
for(int j=0; j<6; j++) {
theBoard[i][j] = 0;
}
}
}
void myboard::displayBoard() {
cout << "Board:" << endl;
cout << " ";
for(int i=1; i<=2; i++) {
cout << "P" << i;
if(i==1) {
cout << " |";
}
cout << " ";
}
cout << endl;
for(int i=0; i<6; i++) {
for(int j=0; j<6; j++) {
if(j==3) {
cout << " |";
}
cout << setw(4) << theBoard[i][j];
}
cout << endl;
}
}
players::players(myboard &board, int ID) // default constructor for players.h
:player_board(board), playerID(ID)
{ }
bool myboard::putShip(int playerID, int shipID, int rowStart, int colStart, int rowEnd, int colEnd) {
if(!(shipID == 1 || shipID == 2)) { // check ship ID...
return false;
}
if(rowStart < 0 || colStart < 0 || rowEnd < 0 || colEnd < 0) { // negative coordinates
return false;
}
// to check whether coordinates match with ID's...
int row_diff = abs(rowEnd - rowStart);
int col_diff = abs(colEnd - colStart);
bool check_shape = false;
// checking if ship shape matches ID...
if(row_diff == 0 && col_diff == 1 && shipID == 1) { // small ship type 1
check_shape = true;
}
else if(row_diff == 1 && col_diff == 0 && shipID == 1) { // small ship type 2
check_shape = true;
}
else if(row_diff == 0 && col_diff == 2 && shipID == 2) { // big ship type 1
check_shape = true;
}
else if(row_diff == 2 && col_diff == 0 && shipID == 2) { // big ship type 2
check_shape = true;
}
else {
return false; // wrong ship shape...
}
// ship shape checked...
bool check_coord = false; // check coordinates
if(check_shape) { // if ship shape is true...
if(playerID == 1) {
if(row_diff == 0 && col_diff == 1) { // small ship type 1
if(!(rowStart > 5)) {
if(colStart > 2 || colEnd > 2) {
return false;
}
else {
check_coord = true;
}
}
else {
return false; // exceeds row
}
}
else if(row_diff == 1 && col_diff == 0) { // small ship type 2
if(!(colStart > 2)) {
if(rowStart > 5 || rowEnd > 5) {
return false;
}
else {
check_coord = true;
}
}
else {
return false; // exceeds columns
}
}
else if(row_diff == 0 && col_diff == 2) { // big ship type 1
if(!(rowStart > 5)) {
if(colStart > 2 || colEnd > 2) {
return false;
}
else {
check_coord = true;
}
}
else {
return false; // exceeds rows
}
}
else { // big ship type 2
if(!(colStart > 2)) {
if(rowStart > 5 || rowEnd > 5) {
return false;
}
else {
check_coord = true;
}
}
else {
return false; // exceeds columns
}
}
}
else { // player ID is 2...
if(playerID == 2) {
if(row_diff == 0 && col_diff == 1) { // small ship type 1
if(!(rowStart > 5)) {
if(colStart < 3 || colStart > 5) {
return false;
}
else {
if(colEnd < 3 || colEnd > 5) {
return false;
}
else {
check_coord = true;
}
}
}
else {
return false; // exceeds rows
}
}
else if(row_diff == 1 && col_diff == 0) { // small ship type 2
if(!(colStart < 3 || colStart > 5)) {
if(rowStart > 5 || rowEnd > 5) {
return false;
}
else {
check_coord = true;
}
}
else {
return false; // exceeds cols
}
}
else if(row_diff == 0 && col_diff == 2) { // big ship type 1
if(!(rowStart > 5)) {
if(colStart < 3 || colStart > 5) {
return false;
}
else {
if(colEnd < 3 || colEnd > 5) {
return false;
}
else {
check_coord = true;
}
}
}
else {
return false; // exceeds rows
}
}
else { // big ship type 2
if(!(colStart < 3 || colStart > 5)) {
if(rowStart > 5 || rowEnd > 5) {
return false;
}
else {
check_coord = true;
}
}
else {
return false; // exceeds cols
}
}
}
}
}
// coordinates checked... ship shape checked....
// now, check if previously occupied or not...
if(check_coord) {
// check previosuly occupied cell...
if(row_diff == 0) {
if(colEnd > colStart) {
for(int i=colStart; i<=colEnd; i++) {
if(theBoard[rowStart][i] == 1) {
return false;
}
}
}
else {
for(int i=colEnd; i<=colStart; i++) {
if(theBoard[rowStart][i] == 1) {
return false;
}
}
}
}
else if(row_diff == 1) {
if(rowEnd > rowStart) {
for(int i=rowStart; i<=rowEnd; i++) {
if(theBoard[i][colStart] == 1) {
return false;
}
}
}
else {
for(int i=rowEnd; i<=rowStart; i++) {
if(theBoard[i][colStart] == 1) {
return false;
}
}
}
}
else if(row_diff == 2) {
if(rowEnd > rowStart) {
for(int i=rowStart; i<=rowEnd; i++) {
if(theBoard[i][colStart] == 1) {
return false;
}
}
}
else {
for(int i=rowEnd; i<=rowStart; i++) {
if(theBoard[i][colStart] == 1) {
return false;
}
}
}
}
// previously occupied cell checked...
// unoccupied cell, place 1's for valid coordinates...
if(row_diff == 0) {
if(colStart > colEnd) {
for(int i=colEnd; i<=colStart; i++) {
theBoard[rowStart][i] = 1;
}
}
else {
for(int i=colStart; i<=colEnd; i++) {
theBoard[rowStart][i] = 1;
}
}
}
else {
if(rowStart > rowEnd) {
for(int i=rowEnd; i<=rowStart; i++) {
theBoard[i][colStart] = 1;
}
}
else {
for(int i=rowStart; i<=rowEnd; i++) {
theBoard[i][colStart] = 1;
}
}
}
}
return true;
}
bool myboard::makeAHit(int row, int column) {
for(int i=0; i<6; i++) {
for(int j=0; j<6; j++) {
if(i == row && j == column) {
if(theBoard[i][j] == 1) { // guess is valid
theBoard[i][j] = -1; // successful hit
return true;
}
}
}
}
return false; // guess not containing a ship piece
}
bool myboard::checkIfPlayerWon(int playerID) {
int count= 0;
bool check = false;
if(playerID == 1) {
for(int i=0; i<6; i++) {
for(int j=3; j<6; j++) {
if(theBoard[i][j] == -1) {
count++;
}
}
}
}
else if(playerID == 2) {
for(int i=0; i<6; i++) {
for(int j=0; j<3; j++) {
if(theBoard[i][j] == -1) {
count++;
}
}
}
}
if(count == 5) {
check = true;
}
return check;
}
bool players::guess(int row, int column) {
bool check = player_board.makeAHit(row, column);
return check;
}
bool players::wins() {
bool check = player_board.checkIfPlayerWon(playerID);
return check;
}
| 25.22179 | 101 | 0.266893 | [
"shape"
] |
f2e2221c8936c703a188047c6d63c4e9a1e97efa | 4,315 | cpp | C++ | Distance.cpp | puzzgames/juddperft | 467fdadd755a691304acbc292a3f58cde0fd1c24 | [
"MIT"
] | null | null | null | Distance.cpp | puzzgames/juddperft | 467fdadd755a691304acbc292a3f58cde0fd1c24 | [
"MIT"
] | null | null | null | Distance.cpp | puzzgames/juddperft | 467fdadd755a691304acbc292a3f58cde0fd1c24 | [
"MIT"
] | null | null | null | //
// Created by andrzej on 9/17/21.
//
#include "Distance.h"
int Distance::lcslen(std::string a, std::string b) {
int h = a.length() + 1;
int w = b.length() + 1;
int *C = new int[w * h]; // (a, b).length() + 1
for (int i = 0; i <= a.length(); i++)
C[i * w + 0] = 0;
for (int j = 0; j <= b.length(); j++)
C[0 * w + j] = 0;
for (int i = 1; i <= a.length(); i++)
for (int j = 1; j <= b.length(); j++) {
if (a[i - 1] == b[j - 1])//i-1,j-1
C[i * w + j] = C[(i - 1) * w + j - 1] + 1;
else
C[i * w + j] = std::max(C[i * w + j - 1], C[(i - 1) * w + j]);
}
int len = C[w * h - 1];
delete[] C;
return len;
}
bool Distance::compareByScorePriority(const WordScores &a, const WordScores &b) {
if (a.scores != b.scores)
return a.scores > b.scores;
else if (a.priority != b.priority)
return a.priority > b.priority;
else
return a.word > b.word;
}
int Distance::distance(std::string a, std::string b) {
int lcs = lcslen(a, b);
int _added = added(lcs, a, b);
int _deleted = deleted(lcs, a, b);
if (_added>_deleted)
return _added+2*_deleted;
else
return 2*_added+2*_deleted;
}
/*
* If returns with similarity 0, returns only one
* if max priority < -len myword / 2 -> return nothing
* if returns all with max similarity if have the same priority
* else returns all with maximal priority
* */
void Distance::mostSimilar(std::string myword, std::vector<WordScores> &list) {
for (auto &ws: list) {
ws.scores = -distance(myword, ws.word);
}
std::sort(list.begin(), list.end(), compareByScorePriority);
int maxscores = list[0].scores;
int maxpriority = list[0].priority;
if (maxscores == 0) {
list[0].returnIt = true;
return;
}
for (auto &ws: list) {
if (ws.scores < maxscores || ws.priority < maxpriority) break;
ws.returnIt = true;
}
}
/*
* 0: found exact implemented method
* 1: found exact not implemented method
* 2: found one implemented method
* 3: found many implemented methods
* 4: found one not implemented method
* 5: found many not implemented methods
* 6: not found too short
* 7: not found tool long
* 8: comparable length
* 9: count = 0
* */
std::string Distance::process(std::string myword, std::vector<WordScores> list, int &code) {
mostSimilar(myword,list);
const WordScores &first = list[0];
if (first.word==myword) {
if (first.priority > 0) {
code = 0;
return "";
}
else {
code = 1;
return "command '"+first.word+"' is unimplemented";
}
}
int count = 0;
for (auto &ws : list)
if (ws.returnIt) count++;
if (count==0) {
code = 8;
return "matching command '"+myword+"' not found";
}
if (-first.scores>myword.size()*1.5) {
double len_ratio = (double) myword.size() / first.word.size();
if (len_ratio<0.7) {
code = 6;
return "command '"+myword+"' not found, probably too short";
} else if (len_ratio>1.4) {
code = 7;
return "command '"+myword+"' not found, probably too long";
} else {
code = 8;
return "command '"+myword+"' not found";
}
}
int maxpriority = first.priority;
std::string result;
if (count==1) {
result = "do you mean the ";
if (maxpriority>0) {
result+="command ";
code = 2;
}
else {
result+="unimplemented command ";
code = 3;
}
result += "'"+first.word+"'";
return result+"?";
} else {
result = "do you mean any of the ";
if (maxpriority>0) {
result+="commands";
code = 4;
}
else {
result+="unimplemented commands";
code = 5;
}
bool add_or = false;
for (auto &ws: list) {
if (!ws.returnIt) break;
if (add_or)
result += " or ";
else
result += " ";
result += "'"+ws.word+"'";
add_or = true;
}
return result+"?";
}
}
| 28.388158 | 92 | 0.504519 | [
"vector"
] |
f2f526bbf3b3a601aaeb27a2c51f6ebe8ccd9532 | 11,534 | cpp | C++ | AAM_PDM.cpp | wuxuef2/face | 377f5d17e0d3500720f4f609c0a4d70fa02fc11b | [
"MIT"
] | 18 | 2015-05-07T13:54:53.000Z | 2020-02-29T05:21:34.000Z | AAM_PDM.cpp | wuxuef2/face | 377f5d17e0d3500720f4f609c0a4d70fa02fc11b | [
"MIT"
] | null | null | null | AAM_PDM.cpp | wuxuef2/face | 377f5d17e0d3500720f4f609c0a4d70fa02fc11b | [
"MIT"
] | 16 | 2015-12-22T05:43:53.000Z | 2019-12-26T02:37:09.000Z | /****************************************************************************
*
* Copyright (c) 2008 by Yao Wei, all rights reserved.
*
* Author: Yao Wei
* Contact: njustyw@gmail.com
*
* This software is partly based on the following open source:
*
* - OpenCV
*
****************************************************************************/
#include "AAM_PDM.h"
using namespace std;
//int aligni = 0;
AAM_PDM::AAM_PDM()
{
__MeanShape = 0;
__ShapesEigenVectors = 0;
__ShapesEigenValues = 0;
__matshape = 0;
}
AAM_PDM::~AAM_PDM()
{
cvReleaseMat(&__MeanShape);
cvReleaseMat(&__ShapesEigenVectors);
cvReleaseMat(&__ShapesEigenValues);
cvReleaseMat(&__matshape);
}
void AAM_PDM::Train(const std::vector<AAM_Shape> &AllShapes, double percentage /* = 0.95 */)
{
printf("################################################\n");
printf("Build Point Distribution Model...\n");
int nSamples = AllShapes.size();
int nPoints = AllShapes[0].NPoints();
__matshape = cvCreateMat(1, nPoints*2, CV_64FC1);
std::vector<AAM_Shape> AlignedShapes = AllShapes;
AAM_PDM::AlignShapes(AlignedShapes);
/*string s;
char c[10];
itoa(aligni,c,10);
std::ofstream alignp;
alignp.open("pts_"+ std::string(c) +".txt");
aligni++;*/
// Assign all points positions from vector<AAM_Shape> to CvMat
CvMat *m_CVShapes = cvCreateMat (nSamples, nPoints * 2, CV_64FC1);
for(int i = 0; i < nSamples; i++)
{
for(int j = 0; j < nPoints; j++)
{
CV_MAT_ELEM(*m_CVShapes, double, i, 2*j ) = AlignedShapes[i][j].x;
CV_MAT_ELEM(*m_CVShapes, double, i, 2*j+1) = AlignedShapes[i][j].y;
//alignp << AlignedShapes[i][j].x << " " << AlignedShapes[i][j].y << " ";
}
//alignp << std::endl;
}
//alignp.close();
DoPCA(m_CVShapes, percentage);
__AAMRefShape.Mat2Point(__MeanShape);
// this step is not necessary!
__AAMRefShape.Translate(-__AAMRefShape.MinX(), -__AAMRefShape.MinY());
cvReleaseMat(&m_CVShapes);
printf("################################################\n\n");
}
void AAM_PDM::Train(const std::vector<AAM_Shape> &AllShapes, std::vector<AAM_Shape> &AlignedShapes, double percentage/* =0.95 */)
{
printf("################################################\n");
printf("Build Point Distribution Model...\n");
int nSamples = AllShapes.size();
int nPoints = AllShapes[0].NPoints();
__matshape = cvCreateMat(1, nPoints*2, CV_64FC1);
AlignedShapes = AllShapes;
AAM_PDM::AlignShapes(AlignedShapes);
// Assign all points positions from vector<AAM_Shape> to CvMat
CvMat *m_CVShapes = cvCreateMat (nSamples, nPoints * 2, CV_64FC1);
for(int i = 0; i < nSamples; i++)
{
for(int j = 0; j < nPoints; j++)
{
CV_MAT_ELEM(*m_CVShapes, double, i, 2*j ) = AlignedShapes[i][j].x;
CV_MAT_ELEM(*m_CVShapes, double, i, 2*j+1) = AlignedShapes[i][j].y;
}
}
DoPCA(m_CVShapes, percentage);
__AAMRefShape.Mat2Point(__MeanShape);
// this step is not necessary!
__AAMRefShape.Translate(-__AAMRefShape.MinX(), -__AAMRefShape.MinY());
cvReleaseMat(&m_CVShapes);
printf("################################################\n\n");
}
void AAM_PDM::AlignShapes(std::vector<AAM_Shape> &AllShapes)
{
printf("Align all shapes...\n");
int nSamples = AllShapes.size();
int nPoints = AllShapes[0].NPoints();
for(int ii=0; ii < nSamples; ii++) AllShapes[ii].Centralize();
// calculate the mean shape
AAM_Shape meanShape;
AAM_PDM::CalcMeanShape(meanShape, AllShapes);
/*************************************************************************************************************/
double thisfacewidth = meanShape.GetWidth();
if(stdwidth < thisfacewidth) meanShape.Scale(stdwidth / thisfacewidth);
// We choose an initial estimate AlignedShapes[0]
AAM_Shape refShape(meanShape);
const AAM_Shape ConstRefShape(meanShape);
AAM_Shape NewMeanShape(meanShape);
// do a number of alignment iterations until the mean shape estimate is stable
double diff, diff_max = 0.001;
const int max_iter = 30;
for(int iter = 0; iter < max_iter; iter++)
{
//align all shapes to the mean shape estimate
for(int i = 0; i < nSamples; i++)
{
// align the i-th shape to the estimate of the mean shape
AllShapes[i].AlignTo(refShape);
}
// Re-estimate new mean shape from aligned shapes
AAM_PDM::CalcMeanShape(NewMeanShape, AllShapes);
// Constrain new mean shape by aligning it to ref shape
NewMeanShape.AlignTo(ConstRefShape);
diff = (NewMeanShape-refShape).GetNorm2();
printf("Alignment iteration #%i, mean shape est. diff. = %g\n", iter, diff );
if(diff <= diff_max) break; //converged
//if not converged, come on iterations
refShape = NewMeanShape;
}
AAM_PDM::CalcMeanShape(meanShape, AllShapes);
}
void AAM_PDM::CalcMeanShape(AAM_Shape &MeanShape, const std::vector<AAM_Shape> &AllShapes)
{
MeanShape.resize(AllShapes[0].NPoints());
MeanShape = 0;
for(int i = 0; i < AllShapes.size(); i++) MeanShape += AllShapes[i];
MeanShape /= AllShapes.size();
}
void AAM_PDM::DoPCA(const CvMat* m_CVShapes, double percentage)
{
printf("Doing PCA of shapes datas...");
int nSamples = m_CVShapes->rows;
int nPointsby2 = m_CVShapes->cols;
int nEigenAtMost = MIN(nSamples, nPointsby2);
CvMat* tmpEigenValues = cvCreateMat(1, nEigenAtMost, CV_64FC1);
CvMat* tmpEigenVectors = cvCreateMat(nEigenAtMost, nPointsby2, CV_64FC1);
__MeanShape = cvCreateMat(1, nPointsby2, CV_64FC1 );
cvCalcPCA(m_CVShapes, __MeanShape,
tmpEigenValues, tmpEigenVectors, CV_PCA_DATA_AS_ROW);
double allSum = cvSum(tmpEigenValues).val[0];
double partSum = 0.0;
int nTruncated = 0;
double largesteigval = cvmGet(tmpEigenValues, 0, 0);
for(int i = 0; i < nEigenAtMost; i++)
{
double thiseigval = cvmGet(tmpEigenValues, 0, i);
if(thiseigval / largesteigval < 0.0001) break; // firstly check
partSum += thiseigval;
++ nTruncated;
if(partSum/allSum >= percentage) break; //secondly check
}
__ShapesEigenValues = cvCreateMat(1, nTruncated, CV_64FC1);
__ShapesEigenVectors = cvCreateMat(nTruncated, nPointsby2, CV_64FC1);
CvMat G;
cvGetCols(tmpEigenValues, &G, 0, nTruncated);
cvCopy(&G, __ShapesEigenValues);
cvGetRows(tmpEigenVectors, &G, 0, nTruncated);
cvCopy(&G, __ShapesEigenVectors);
cvReleaseMat(&tmpEigenVectors);
cvReleaseMat(&tmpEigenValues);
printf("Done (%d/%d)\n", nTruncated, nEigenAtMost);
}
void AAM_PDM::CalcLocalShape(const CvMat* p, CvMat* s)
{
cvBackProjectPCA(p, __MeanShape, __ShapesEigenVectors, s);
}
void AAM_PDM::CalcGlobalShape(const CvMat* q, CvMat* s)
{
int npoints = nPoints();
double* fasts = s->data.db;
double a=cvmGet(q,0,0)+1, b=cvmGet(q,0,1),
tx=cvmGet(q,0,2), ty=cvmGet(q,0,3);
double x, y;
for(int i = 0; i < npoints; i++)
{
x = fasts[2*i ];
y = fasts[2*i+1];
fasts[2*i ] = a*x-b*y+tx;
fasts[2*i+1] = b*x+a*y+ty;
}
}
void AAM_PDM::CalcShape(const CvMat* p, const CvMat* q, CvMat* s)
{
CalcLocalShape(p, s);
CalcGlobalShape(q, s);
}
void AAM_PDM::CalcShape(const CvMat* pq, CvMat* s)
{
int nmodes = nModes(), npoints = nPoints();
// assert(pq->cols == 4+nmodes && s->cols == npoints*2);
CvMat p;
cvGetCols(pq, &p, 4, 4+nmodes);
cvBackProjectPCA(&p, __MeanShape, __ShapesEigenVectors, s);
double* fasts = s->data.db;
double a=cvmGet(pq,0,0)+1, b=cvmGet(pq,0,1),
tx=cvmGet(pq,0,2), ty=cvmGet(pq,0,3);
double x, y;
for(int i = 0; i < npoints; i++)
{
x = fasts[2*i ];
y = fasts[2*i+1];
fasts[2*i ] = a*x-b*y+tx;
fasts[2*i+1] = b*x+a*y+ty;
}
}
void AAM_PDM::CalcShape(const CvMat* pq, AAM_Shape& shape)
{
CalcShape(pq, __matshape);
shape.Mat2Point(__matshape);
}
void AAM_PDM::CalcParams(const CvMat* s, CvMat* pq)
{
__x.Mat2Point(s);
CalcParams(__x, pq);
}
void AAM_PDM::CalcParams(const CvMat* s, CvMat* p, CvMat* q)
{
int nmodes = nModes(), npoints = nPoints();
// assert(pq->cols == 4+nmodes);
double a, b, tx, ty;
double a_, b_, tx_, ty_;
double norm;
__y.Mat2Point(s);
__y.COG(tx, ty);
__y.Translate(-tx, -ty);
cvmSet(q,0,2,tx);
cvmSet(q,0,3,ty);
// do a few iterations to get (s, theta, p)
cvZero(p);
for(int iter = 0; iter < 2; iter++)
{
cvBackProjectPCA(p, __MeanShape, __ShapesEigenVectors, __matshape);
__x.Mat2Point(__matshape);
__x.AlignTransformation(__y, a, b, tx, ty); //in fact, tx = ty = 0
norm = a*a + b*b;
a_ = a / norm;
b_ = -b / norm;
tx_ = (-a*tx - b*ty) / norm;
ty_ = (b*tx - a*ty) / norm;
__x = __y;
__x.TransformPose(a_, b_, tx_, ty_);
__x.Point2Mat(__matshape);
cvProjectPCA(__matshape, __MeanShape, __ShapesEigenVectors, p);
}
cvmSet(q, 0, 0, a -1);
cvmSet(q, 0, 1, b);
Clamp(p, 1.8);
}
void AAM_PDM::CalcParams(const AAM_Shape& shape, CvMat* pq)
{
int nmodes = nModes(), npoints = nPoints();
// assert(pq->cols == 4+nmodes);
double a, b, tx, ty;
double a_, b_, tx_, ty_;
double norm;
__y = shape;
__y.COG(tx, ty);
__y.Translate(-tx, -ty);
cvmSet(pq,0,2,tx);
cvmSet(pq,0,3,ty);
// do a few iterations to get (s, theta, p)
CvMat p;
cvGetCols(pq, &p, 4, 4+nmodes);
cvZero(&p);
for(int iter = 0; iter < 2; iter++)
{
cvBackProjectPCA(&p, __MeanShape, __ShapesEigenVectors, __matshape);
__x.Mat2Point(__matshape);
__x.AlignTransformation(__y, a, b, tx, ty); //in fact, tx = ty = 0
norm = a*a + b*b;
a_ = a / norm;
b_ = -b / norm;
tx_ = (-a*tx - b*ty) / norm;
ty_ = (b*tx - a*ty) / norm;
__x = __y;
__x.TransformPose(a_, b_, tx_, ty_);
__x.Point2Mat(__matshape);
cvProjectPCA(__matshape, __MeanShape, __ShapesEigenVectors, &p);
}
cvmSet(pq, 0, 0, a -1);
cvmSet(pq, 0, 1, b);
Clamp(&p, 1.8);
}
void AAM_PDM::Clamp(CvMat* p, double s_d /* = 3.0 */)
{
double* fastp = p->data.db;
double* fastv = __ShapesEigenValues->data.db;
int nmodes = nModes();
double limit;
for(int i = 0; i < nmodes; i++)
{
limit = s_d*sqrt(fastv[i]);
if(fastp[i] > limit) fastp[i] = limit;
else if(fastp[i] < -limit) fastp[i] = -limit;
}
}
void AAM_PDM::Write(std::ofstream& os)
{
os << nPoints() << " " << nModes() << std::endl;
os << __MeanShape << std::endl;
os << __ShapesEigenValues << std::endl;
os << __ShapesEigenVectors << std::endl;
__AAMRefShape.Write(os);
os << std::endl;
}
void AAM_PDM::Read(std::ifstream& is)
{
int _nPoints, _nModes;
is >> _nPoints >> _nModes;
__MeanShape = cvCreateMat(1, _nPoints*2, CV_64FC1);
__ShapesEigenValues = cvCreateMat(1, _nModes, CV_64FC1);
__ShapesEigenVectors = cvCreateMat(_nModes, _nPoints*2, CV_64FC1);
__AAMRefShape.resize(_nPoints);
is >> __MeanShape;
is >> __ShapesEigenValues;
is >> __ShapesEigenVectors;
__AAMRefShape.Read(is);
__matshape = cvCreateMat(1, nPoints()*2, CV_64FC1);
}
| 28.408867 | 129 | 0.58748 | [
"shape",
"vector",
"model"
] |
f2f784467e340521d771731057aecacc16854381 | 983 | cpp | C++ | android-31/android/net/UrlQuerySanitizer_ParameterValuePair.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/net/UrlQuerySanitizer_ParameterValuePair.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/net/UrlQuerySanitizer_ParameterValuePair.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "./UrlQuerySanitizer.hpp"
#include "../../JString.hpp"
#include "./UrlQuerySanitizer_ParameterValuePair.hpp"
namespace android::net
{
// Fields
JString UrlQuerySanitizer_ParameterValuePair::mParameter()
{
return getObjectField(
"mParameter",
"Ljava/lang/String;"
);
}
JString UrlQuerySanitizer_ParameterValuePair::mValue()
{
return getObjectField(
"mValue",
"Ljava/lang/String;"
);
}
// QJniObject forward
UrlQuerySanitizer_ParameterValuePair::UrlQuerySanitizer_ParameterValuePair(QJniObject obj) : JObject(obj) {}
// Constructors
UrlQuerySanitizer_ParameterValuePair::UrlQuerySanitizer_ParameterValuePair(android::net::UrlQuerySanitizer arg0, JString arg1, JString arg2)
: JObject(
"android.net.UrlQuerySanitizer$ParameterValuePair",
"(Landroid/net/UrlQuerySanitizer;Ljava/lang/String;Ljava/lang/String;)V",
arg0.object(),
arg1.object<jstring>(),
arg2.object<jstring>()
) {}
// Methods
} // namespace android::net
| 25.205128 | 141 | 0.745677 | [
"object"
] |
f2fbc149fb42257359842c120da8ae7dbe03baf1 | 14,096 | cc | C++ | problems/TwoDModel/TwoDModel.cc | ppnathan/HMSHS | ae65c7622cf4b10d710722084d73a2ad8636bc9e | [
"Apache-2.0"
] | null | null | null | problems/TwoDModel/TwoDModel.cc | ppnathan/HMSHS | ae65c7622cf4b10d710722084d73a2ad8636bc9e | [
"Apache-2.0"
] | null | null | null | problems/TwoDModel/TwoDModel.cc | ppnathan/HMSHS | ae65c7622cf4b10d710722084d73a2ad8636bc9e | [
"Apache-2.0"
] | null | null | null | #include "TwoDModel.h"
#include "Utilities.h"
#include <cmath>
#include <cstdlib>
#include <random>
#include <iostream>
#include <array>
using namespace std;
const double Discount_2DMdl = 0.95;
const int NumCStateVar_2DMdl = 2; // number of continuous state variables
const int NumDState_2DMdl = 4; // number of discrete states
const int NumCObsVar_2DMdl = 1; // number of continuous observation variables
const int NumDObs_2DMdl = 2; // number of discrete observations
const int NumDControls_2DMdl = 4; // number of discrete controls
// q: AC0:(Awake, Controller 0); AC1:(Awake, Controller 1); DC0:(Drowsy, Controller 0); DC1:(Drowsy, Controller 1);
enum { AC0 = 0, AC1 = 1, DC0 = 2, DC1 = 3};
// sigma: V00:(Reminder off, Execute C0); V01:(Reminder off, Execute C1); V10:(Reminder on, Execute C0); V11:(Reminder on, Execute C1);
enum {V00 = 0, V01 = 1, V10 = 2, V11 = 3};
TwoDModel::TwoDModel() : Model(NumCStateVar_2DMdl, NumDState_2DMdl, NumCObsVar_2DMdl,
NumDObs_2DMdl, NumDControls_2DMdl, Discount_2DMdl),
deltaT(1), noisemean(0), awakenoisestddev(0.2), drowsynoisestddev(1),
k1(0.0796), k2(0.4068), obserr(0.05)
{
//500 + 0x - x^2 + 0xy + 0y - 0.1y^2
double rewardcoefficient[NumDControls_2DMdl][6] = {{500, 0, -1, 0, 0, -0.1},
{495, 0, -1, 0, 0, -0.1},
{495, 0, -1, 0, 0, -0.1},
{490, 0, -1, 0, 0, -0.1}};
vector<vector<double> > tmpvector(NumDState_2DMdl, vector<double>(6, 0));
for (int i = 0; i < NumDControls_2DMdl; i++) {
for (int j = 0; j < NumDState_2DMdl; j++) {
for (int k = 0; k < 6; k++) {
tmpvector[j][k] = rewardcoefficient[i][k];
}
}
RewardCoeff.push_back(tmpvector);
}
};
DState TwoDModel::sampleDState(const DState &q, const DControl &sigma) const{
array<double,4> init = {this->getDStateTransProb(AC0, q, sigma),
this->getDStateTransProb(AC1, q, sigma),
this->getDStateTransProb(DC0, q, sigma),
this->getDStateTransProb(DC1, q, sigma)};
discrete_distribution<int> distribution(init.begin(), init.end());
return distribution(generator);
};
CState TwoDModel::sampleCState(const DState &q_next, const CState &x_k) const {
normal_distribution<double> awakenormalRand(this->noisemean, this->awakenoisestddev);
normal_distribution<double> drowsynormalRand(this->noisemean, this->drowsynoisestddev);
double awakenoise = awakenormalRand(generator);
double drowsynoise = drowsynormalRand(generator);
CState x_next(x_k.size());
if (q_next == AC0) {
x_next(0) = (1 - this->deltaT * this->deltaT / 2 * k1) * x_k(0) +
(this->deltaT - this->deltaT * this->deltaT / 2 * k2) * x_k(1) +
awakenoise;
x_next(1) = -(this->deltaT) * k1 * x_k(0) + (1 - this->deltaT * k2) * x_k(1);
} else if (q_next == AC1) {
x_next(0) = (1 - this->deltaT * this->deltaT / 2 * 2 * k1) * x_k(0) +
(this->deltaT - this->deltaT * this->deltaT / 2 * 2 * k2) * x_k(1) +
awakenoise;
x_next(1) = -(this->deltaT) * 2 * k1 * x_k(0) + (1 - this->deltaT * 2 * k2) * x_k(1);
} else if (q_next == DC0) {
x_next(0) = x_k(0) + this->deltaT * x_k(1) + drowsynoise;
x_next(1) = x_k(1);
} else if (q_next == DC1) {
x_next(0) = (1 - this->deltaT * this->deltaT / 2 * k1) * x_k(0) +
(this->deltaT - this->deltaT * this->deltaT / 2 * k2) * x_k(1) + drowsynoise;
x_next(1) = -this->deltaT * k1 * x_k(0) + (1 - this->deltaT * k2) * x_k(1);
}
return x_next;
};
DObs TwoDModel::sampleDObs(const DState &q_next) const {
bernoulli_distribution bernlRand(1 - this->obserr);
if(bernlRand(generator))
return q_next>>1;
else
return ((q_next>>1) == 0)? 1:0;
};
double TwoDModel::getCStateTransProb(CState const &x_next,
DState const &q_next,
CState const &x_k) const {
double difference[2];
if(q_next == AC0) {
difference[0] = x_next(0) - (1 - this->deltaT * this->deltaT / 2 * k1) * x_k(0) -
(this->deltaT - this->deltaT * this->deltaT / 2 * k2) * x_k(1);
difference[1] = x_next(1) - (-(this->deltaT) * k1 * x_k(0) +
(1 - this->deltaT * k2 * x_k(1)));
double p1 = 1.0 / (awakenoisestddev * sqrt(2 * PI)) *
exp(-0.5 * (difference[0] - noisemean) * (difference[0] - noisemean) /
(awakenoisestddev * awakenoisestddev));
double p2 = 1.0 / (0.1 * sqrt(2 * PI)) *
exp(-0.5 * (difference[1] - noisemean) * (difference[1] - noisemean) /
(0.1 * 0.1));
return p1 * p2;
}
else if (q_next == AC1) {
difference[0] = x_next(0) - (1 - this->deltaT * this->deltaT / 2 * 2 * k1) * x_k(0) -
(this->deltaT - this->deltaT * this->deltaT / 2 * 2 * k2) * x_k(1);
difference[1] = x_next(1) - (-this->deltaT * 2 * k1 * x_k(0) +
(1 - this->deltaT* 2 * k2 * x_k(1)));
double p1 = 1.0 / (awakenoisestddev * sqrt( 2 * PI)) *
exp(-0.5 * (difference[0] - noisemean) * (difference[0] - noisemean) /
(awakenoisestddev * awakenoisestddev));
double p2 = 1.0 / (0.1 * sqrt(2 * PI)) *
exp(-0.5 * (difference[1] - noisemean) * (difference[1] - noisemean) /
(0.1 * 0.1));
return p1*p2;
}
else if(q_next == DC0) {
difference[0] = x_next(0) - x_k(0) - this->deltaT * x_k(1);
difference[1] = x_next(1) - x_k(1);
double p1 = 1.0 / (drowsynoisestddev * sqrt(2 * PI)) *
exp(-0.5 * (difference[0] - noisemean) * (difference[0] - noisemean) /
(drowsynoisestddev * drowsynoisestddev));
double p2 = 1.0 / (0.1 * sqrt(2 * PI)) *
exp(-0.5 * (difference[1] - noisemean) * (difference[1] - noisemean) /
(0.1 * 0.1));
return p1*p2;
}
else if(q_next == DC1) {
difference[0] = x_next(0) - (1 - this->deltaT * this->deltaT / 2 * k1) * x_k(0) -
(this->deltaT - this->deltaT * this->deltaT / 2 * k2) * x_k(1);
difference[1] = x_next(1) - (-this->deltaT * k1 * x_k(0) +
(1 - this->deltaT * k2 * x_k(1)));
double p1 = 1.0 / (drowsynoisestddev * sqrt(2 * PI)) *
exp(-0.5 * (difference[0] - noisemean) * (difference[0] - noisemean) /
(drowsynoisestddev * drowsynoisestddev));
double p2 = 1.0 / (0.1 * sqrt(2 * PI)) *
exp(-0.5 * (difference[1] - noisemean) * (difference[1] - noisemean) /
(0.1 * 0.1));
return p1 * p2;
}
else {
printf("q_next out of domain\n");
exit(1);
}
};
double TwoDModel::getDStateTransProb(DState const &q_next,
DState const &q_k,
DControl const &sigma_k) const {
double sigma0[2][2] = { {0.95, 0.05},
{0.05, 0.95} };
double sigma1[2][2] = { {0.95, 0.8},
{0.05, 0.2}};
if((sigma_k>>1) == 0) // (sigma_k == V00) || (sigma_k == V01)
{
return sigma0[q_next >> 1][q_k >> 1] * ((q_next & 0x01) == (sigma_k & 0x01));
}
else // (sigma_k == V10) || (sigma_k == V11)
{
return sigma1[q_next >> 1][q_k >> 1] * ((q_next & 0x01) == (sigma_k & 0x01));
}
};
double TwoDModel::getDiscreteObsProb(DObs const &zq_k, DState const &q_k) const {
if(zq_k == (q_k >> 1))
return 1 - obserr;
else
return obserr;
};
CState TwoDModel::getNextCStateNoNoise(const DState &q_next, const CState &x_k) const{
CState x_next(this->getNumCStateVar());
if(q_next == AC0) {
x_next(0) = (1- this->deltaT * this->deltaT / 2 * k1) * x_k(0) +
(this->deltaT - this->deltaT * this->deltaT / 2 * k2) * x_k(1);
x_next(1) = -this->deltaT * k1 * x_k(0) + (1 - this->deltaT * k2) * x_k(1);
}
else if(q_next == AC1) {
x_next(0) = (1- this->deltaT * this->deltaT / 2 * 2 * k1) * x_k(0) +
(this->deltaT - this->deltaT * this->deltaT / 2 * 2 * k2) * x_k(1);
x_next(1) = -this->deltaT * 2 * k1 * x_k(0) + (1 - this->deltaT * 2 * k2) * x_k(1);
}
else if(q_next == DC0) {
x_next(0) = x_k(0) + this->deltaT * x_k(1);
x_next(1) = x_k(1);
}
else if(q_next == DC1) {
x_next(0) = (1 - this->deltaT * this->deltaT / 2 * k1) * x_k(0) +
(this->deltaT - this->deltaT * this->deltaT / 2 * k2) * x_k(1);
x_next(1) = -this->deltaT * k1 * x_k(0) + (1 - this->deltaT * k2) * x_k(1);
}
return x_next;
};
MatrixXd TwoDModel::get1stDerivative(const DState &q, const CState &x) const {
MatrixXd firstderivative(this->getNumCStateVar(), this->getNumCStateVar());
if(q == AC0) {
firstderivative(0, 0) = 1 - this->deltaT * this->deltaT / 2 * k1;
firstderivative(0, 1) = this->deltaT - this->deltaT * this->deltaT / 2 * k2;
firstderivative(1, 0) = -this->deltaT * k1;
firstderivative(1, 1) = 1 - this->deltaT * k2;
return firstderivative;
}
else if(q == AC1) {
firstderivative(0, 0) = 1 - (this->deltaT) * (this->deltaT)/ 2 * 2 * k1;
firstderivative(0, 1) = this->deltaT - (this->deltaT) * (this->deltaT) / 2 * 2 * k2;
firstderivative(1, 0) = -(this->deltaT) * 2 * k1;
firstderivative(1, 1) = 1 - (this->deltaT) * 2 * k2;
return firstderivative;
}
else if(q == DC0) {
firstderivative(0, 0) = 1;
firstderivative(0, 1) = this->deltaT;
firstderivative(1, 0) = 0;
firstderivative(1, 1) = 1;
return firstderivative;
}
else { //if(q_next == DC1)
firstderivative(0, 0) = 1 - (this->deltaT) * (this->deltaT) / 2 * k1;
firstderivative(0, 1) = this->deltaT - (this->deltaT) * (this->deltaT) / 2 * k2;
firstderivative(1, 0) = -(this->deltaT) * k1;
firstderivative(1, 1) = 1 - (this->deltaT) * k2;
return firstderivative;
}
};
double TwoDModel::getReward(const DState &q, const CState &x, const DControl &sigma) const {
return (RewardCoeff[sigma][q][0] +
RewardCoeff[sigma][q][1] * x(0) +
RewardCoeff[sigma][q][2] * x(0) * x(0) +
RewardCoeff[sigma][q][3] * x(0) * x(1) +
RewardCoeff[sigma][q][4] * x(1) +
RewardCoeff[sigma][q][2] * x(1) * x(1));
// double R_sigma1[2] = {0,-5};
// double R_sigma2[2] = {0,-5};
// return (500 - (x(0)*x(0)) - 0.1*(x(1)*x(1))) + R_sigma1[sigma>>1] + R_sigma2[sigma&0x01];
};
VectorXd TwoDModel::getReward1stDeri(const DState &q, const CState &x,
const DControl &sigma) const {
VectorXd reward1stDeri(this->getNumCStateVar());
reward1stDeri(0) = RewardCoeff[sigma][q][1] +
2 * RewardCoeff[sigma][q][2] * x(0) +
RewardCoeff[sigma][q][3] * x(1);
reward1stDeri(1) = RewardCoeff[sigma][q][4] +
2 * RewardCoeff[sigma][q][5] * x(1) +
RewardCoeff[sigma][q][3] * x(0);
return reward1stDeri;
};
MatrixXd TwoDModel::getReward2ndDeri(const DState &q, const CState &x,
const DControl &sigma) const {
MatrixXd Reward2ndDeri(this->getNumCStateVar(), this->getNumCStateVar());
Reward2ndDeri(0, 0) = 2 * RewardCoeff[sigma][q][2];
Reward2ndDeri(0, 1) = RewardCoeff[sigma][q][3];
Reward2ndDeri(1, 0) = RewardCoeff[sigma][q][3];
Reward2ndDeri(1, 1) = 2 * RewardCoeff[sigma][q][5];
return Reward2ndDeri;
};
vector<MatrixXd> TwoDModel::getCovariance() const {
MatrixXd cov_tmp(this->getNumCStateVar(), this->getNumCStateVar());
vector<MatrixXd> covariance;
for (DState q = 0; q < NumDState_2DMdl; q++) {
if (q >> 1 == 0 ) { //A
cov_tmp(0, 0) = awakenoisestddev*awakenoisestddev;
}
else { //D
cov_tmp(0, 0) = drowsynoisestddev*drowsynoisestddev;
}
cov_tmp(0, 1) = 0;
cov_tmp(1, 0) = 0;
cov_tmp(1, 1) = 0;
covariance.push_back(cov_tmp);
}
return covariance;
};
MatrixXd TwoDModel::getCovMatrix(const DState &q) const {
MatrixXd CovMatrix(this->getNumCStateVar(), this->getNumCStateVar());
if (q >> 1 == 0 ) { //A
CovMatrix(0, 0) = awakenoisestddev*awakenoisestddev;
CovMatrix(0, 1) = 0;
CovMatrix(1, 0) = 0;
CovMatrix(1, 1) = 0;
}
else { //D
CovMatrix(0, 0) = drowsynoisestddev*drowsynoisestddev;
CovMatrix(0, 1) = 0;
CovMatrix(1, 0) = 0;
CovMatrix(1, 1) = 0;
}
return CovMatrix;
};
double TwoDModel::sample(const DState &q_k, const CState &x_k, const DControl &sigma_k,
DState &q_next, CState &x_next, DObs &obs_out) const{
q_next = sampleDState(q_k, sigma_k);
// cout<<"q_next = "<<q_next<<" ";
x_next = sampleCState(q_next, x_k);
// cout<<"x_next(0) = "<<x_next(0)<<" ";
obs_out = sampleDObs(q_next);
// cout<<"obs_out = "<<obs_out<<endl;
return this->getDStateTransProb(q_next, q_k, sigma_k) *
this->getCStateTransProb(x_next, q_next, x_k) *
this->getDiscreteObsProb(q_next, obs_out);
};
| 41.952381 | 135 | 0.515253 | [
"vector",
"model"
] |
8406963291ea145182819150ff41485d2ddcd6ca | 409 | hpp | C++ | src/output/matlab_m_output.hpp | michaeldel/portfolio-optimizer | 1cf8e417442b780294ce3ad6009a8712626d8bfd | [
"MIT"
] | null | null | null | src/output/matlab_m_output.hpp | michaeldel/portfolio-optimizer | 1cf8e417442b780294ce3ad6009a8712626d8bfd | [
"MIT"
] | null | null | null | src/output/matlab_m_output.hpp | michaeldel/portfolio-optimizer | 1cf8e417442b780294ce3ad6009a8712626d8bfd | [
"MIT"
] | null | null | null | #ifndef DEFINE_MATLAB_M_OUTPUT_HPP
#define DEFINE_MATLAB_M_OUTPUT_HPP
#include "result_output.hpp"
#include "types.hpp"
class MatlabMOutput: public ResultOutput {
public:
MatlabMOutput(const std::string& path);
void write_result(
const Vector& xs, const Vector& ts,
const Matrix& portfolio_values, const Matrix& alphas
) const;
private:
const std::string m_path;
};
#endif | 20.45 | 60 | 0.728606 | [
"vector"
] |
8409787cc25a399b1691a37471266714e09db4c7 | 1,844 | cpp | C++ | UVa/11496/code.cpp | fspaniol/Competitive-Programming | 5ebd53c9d966750800e16f74273b194c04bb7f70 | [
"MIT"
] | null | null | null | UVa/11496/code.cpp | fspaniol/Competitive-Programming | 5ebd53c9d966750800e16f74273b194c04bb7f70 | [
"MIT"
] | null | null | null | UVa/11496/code.cpp | fspaniol/Competitive-Programming | 5ebd53c9d966750800e16f74273b194c04bb7f70 | [
"MIT"
] | null | null | null | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
vector<int> num;
int main() {
int entrada;
bool cresce = 1;
int cont = 1;
int val, last;
int first;
while (cin >> entrada && entrada != 0) {
while (entrada--){
cin >> val;
num.push_back(val);
}
for (int i = 1; i < num.size(); i++) {
if (num[i] > num[i-1])
if ( i == 1){
cresce = 1;
first = 1;
}
else {
if (cresce == 0) {
cresce = 1;
cont++;
}
}
else {
if ( i == 1) {
cresce = 0;
first = 0;
}
else {
if (cresce == 1) {
cresce = 0;
cont++;
}
}
}
//cout << num[i-1] << ' ' << num[i] << ' ' << cresce << ' ' << cont << endl;
}
if (num[num.size() - 1] > num[0] && cresce == first)
cont++;
if (num[num.size() - 1] < num[0] && cresce == first)
cont++;
//cout << num[num.size()-1] << ' ' << num[0] << ' ' << cresce << ' ' << cont << endl;
cout << cont << endl;
num.clear();
cont = 1;
}
return 0;
}
| 22.765432 | 93 | 0.37961 | [
"vector"
] |
840a006a1cda25036e030c34396a8d08a597bf15 | 13,378 | cpp | C++ | tests/CryptoTest.cpp | Manuvr/ManuvrOS | e3a812c9b609ad69670ff2f8050a07bd423ebc78 | [
"Apache-2.0"
] | 5 | 2015-03-26T22:58:58.000Z | 2021-06-15T05:36:57.000Z | tests/CryptoTest.cpp | Manuvr/ManuvrOS | e3a812c9b609ad69670ff2f8050a07bd423ebc78 | [
"Apache-2.0"
] | 2 | 2016-09-26T09:25:58.000Z | 2017-08-03T05:27:24.000Z | tests/CryptoTest.cpp | Manuvr/ManuvrOS | e3a812c9b609ad69670ff2f8050a07bd423ebc78 | [
"Apache-2.0"
] | 2 | 2016-04-29T07:43:32.000Z | 2020-02-07T06:43:01.000Z | /*
File: CryptoTest.cpp
Author: J. Ian Lindsay
Date: 2016.09.25
Copyright 2016 Manuvr, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This tests the cryptographic system under whatever build options
were provided.
*/
#include <cstdio>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <StringBuilder.h>
#include <Platform/Platform.h>
struct Trips { // <---- Check 'em
size_t deltas[3];
};
static char* err_buf[128] = {0};
/*
* Tests to ensure we have support for what we are about to test.
*/
int CRYPTO_TEST_INIT() {
printf("===< CRYPTO_TEST_INIT >==========================================\n");
if (platform.hasCryptography()) {
// This is a good start....
return 0;
}
return -1;
}
/*
* Tests to ensure the RNG works.
* All implementations are expected to have this most-basic capability.
*/
int CRYPTO_TEST_RNG() {
printf("===< CRYPTO_TEST_RNG >===========================================\n");
uint8_t* result = (uint8_t*) alloca(PLATFORM_RNG_CARRY_CAPACITY*2);
int idx = 0;
size_t size_tests[] = {
(PLATFORM_RNG_CARRY_CAPACITY/2),
(PLATFORM_RNG_CARRY_CAPACITY),
(PLATFORM_RNG_CARRY_CAPACITY),
0
};
while (size_tests[idx] != 0) {
size_t r_len = size_tests[idx];
printf("Requesting %d random bytes...\n\t", r_len);
random_fill(result, r_len);
for (unsigned int i = 0; i < r_len; i++) printf("%02x", *(result + i));
printf("\n");
idx++;
}
return 0;
}
#if defined(__BUILD_HAS_DIGEST)
/*
* Digest algortithm tests.
* Because these are not reversible, this will take the form of
* a known-answer test.
*/
int CRYPTO_TEST_HASHES() {
printf("===< CRYPTO_TEST_HASHES >========================================\n");
const char* hash_in0 = "";
int i_len = 1524;
uint8_t* hash_in1 = (uint8_t*) alloca(i_len);
random_fill(hash_in1, i_len);
Hashes* algs_to_test = list_supported_digests();
int idx = 0;
while (Hashes::NONE != algs_to_test[idx]) {
int o_len = get_digest_output_length(algs_to_test[idx]);
printf("Testing %-14s %3d-byte block\n--------------------------------------\n",
get_digest_label(algs_to_test[idx]),
o_len);
uint8_t* hash_out0 = (uint8_t*) alloca(o_len);
uint8_t* hash_out1 = (uint8_t*) alloca(o_len);
if (wrapped_hash((uint8_t*) hash_in0, strlen(hash_in0), hash_out0, algs_to_test[idx])) {
printf("Failed to hash.\n");
return -1;
}
if (wrapped_hash((uint8_t*) hash_in1, i_len, hash_out1, algs_to_test[idx])) {
printf("Failed to hash.\n");
return -1;
}
printf("0-length: ");
for (int i = 0; i < o_len; i++) printf("%02x", *(hash_out0 + i));
printf("\n");
printf("hash_out: ");
for (int i = 0; i < o_len; i++) printf("%02x", *(hash_out1 + i));
printf("\n\n");
idx++;
}
return 0;
}
#else
int CRYPTO_TEST_HASHES() {
// Build doesn't have asymmetric support.
printf("Build doesn't have digest support. Skipping tests...\n");
return 0;
}
#endif // __BUILD_HAS_DIGEST
#if defined(__BUILD_HAS_SYMMETRIC)
/*
* Symmetric algorthms.
*/
int CRYPTO_TEST_SYMMETRIC() {
printf("===< CRYPTO_TEST_SYMMETRIC >=====================================\n");
int i_len = 30;
Cipher algs_to_test[] = {
Cipher::SYM_AES_128_CBC,
Cipher::SYM_AES_192_CBC,
Cipher::SYM_AES_256_CBC,
Cipher::SYM_BLOWFISH_CBC,
//Cipher::SYM_NULL,
Cipher::NONE
};
int ret = 0;
int idx = 0;
while (Cipher::NONE != algs_to_test[idx]) {
const int block_size = get_cipher_block_size(algs_to_test[idx]);
const int key_size = get_cipher_key_length(algs_to_test[idx]);
int o_len = get_cipher_aligned_size(algs_to_test[idx], i_len);
uint8_t* plaintext_in = (uint8_t*) alloca(o_len);
random_fill(plaintext_in, o_len);
printf("Testing %-14s %3d-byte block, %4d-bit key\n----------------------------------------------------\n",
get_cipher_label(algs_to_test[idx]),
block_size,
key_size);
if (0 != o_len % block_size) {
o_len += (block_size - (o_len % block_size));
}
uint8_t* ciphertext = (uint8_t*) alloca(o_len);
uint8_t* plaintext_out = (uint8_t*) alloca(o_len);
uint8_t iv[16];
uint8_t key[(key_size>>3)];
bzero(iv, 16);
bzero(ciphertext, o_len);
bzero(plaintext_out, o_len);
random_fill(key, (key_size>>3));
printf("Key: ");
for (int i = 0; i < (key_size>>3); i++) printf("%02x", *(key + i));
printf("\n");
printf("Plaintext in: ");
for (int i = 0; i < i_len; i++) printf("%02x", *(plaintext_in + i));
printf("\t(%d bytes)\n", i_len);
ret = wrapped_sym_cipher((uint8_t*) plaintext_in, o_len, ciphertext, o_len, key, key_size, iv, algs_to_test[idx], OP_ENCRYPT);
if (ret) {
printf("Failed to encrypt. Error %d\n", ret);
return -1;
}
printf("Ciphertext: ");
for (int i = 0; i < o_len; i++) printf("%02x", *(ciphertext + i));
printf("\t(%d bytes)\n", o_len);
bzero(iv, 16);
ret = wrapped_sym_cipher(ciphertext, o_len, plaintext_out, o_len, key, key_size, iv, algs_to_test[idx], OP_DECRYPT);
if (ret) {
printf("Failed to decrypt. Error %d\n", ret);
return -1;
}
printf("Plaintext out: ");
for (int i = 0; i < o_len; i++) printf("%02x", *(plaintext_out + i));
printf("\t(%d bytes)\n", o_len);
// Now check that the plaintext versions match...
for (int i = 0; i < i_len; i++) {
if (*(plaintext_in + i) != *(plaintext_out + i)) {
printf("Plaintext mismatch. Test fails.\n");
return -1;
}
}
printf("\n");
idx++;
}
return 0;
}
#else
int CRYPTO_TEST_SYMMETRIC() {
// Build doesn't have asymmetric support.
printf("Build doesn't have symmetric support. Skipping tests...\n");
return 0;
}
#endif // __BUILD_HAS_SYMMETRIC
#if defined(__BUILD_HAS_ASYMMETRIC)
static std::map<CryptoKey, Trips*> asym_estimate_deltas;
/*
* Asymmetric algorthms.
*/
int CRYPTO_TEST_ASYMMETRIC_SET(Cipher c, CryptoKey* pks) {
const int MSG_BUFFER_LEN = 700;
uint8_t* test_message = (uint8_t*) alloca(MSG_BUFFER_LEN);
random_fill(test_message, MSG_BUFFER_LEN);
while (CryptoKey::NONE != *pks) {
size_t public_estimate = 0;
size_t privat_estimate = 0;
uint16_t sigbuf_estimate = 0;
size_t public_len = 0;
size_t privat_len = 0;
size_t sigbuf_len = 0;
if (!estimate_pk_size_requirements(*pks, &public_estimate, &privat_estimate, &sigbuf_estimate)) {
printf("\t Failed to estimate buffer requirements for %s.\n", get_pk_label(*pks));
return -1;
}
uint8_t* public_buf = (uint8_t*) alloca(public_estimate);
uint8_t* privat_buf = (uint8_t*) alloca(privat_estimate);
uint8_t* sig_buffer = (uint8_t*) alloca(sigbuf_estimate);
public_len = public_estimate;
privat_len = privat_estimate;
sigbuf_len = sigbuf_estimate;
int ret = wrapped_asym_keygen(c, *pks, public_buf, &public_len, privat_buf, &privat_len);
if (0 == ret) {
public_buf += (public_estimate - public_len);
privat_buf += (privat_estimate - privat_len);
printf("\t Keygen for %s succeeds. Sizes: %d / %d (pub/priv)\n", get_pk_label(*pks), public_len, privat_len);
printf("\t Public: (%d bytes)\n", public_len);
printf("\t Private: (%d bytes)\n", privat_len);
ret = wrapped_sign_verify(
c, *pks, Hashes::SHA256,
test_message, MSG_BUFFER_LEN,
sig_buffer, &sigbuf_len,
privat_buf, privat_len,
OP_SIGN
);
if (0 == ret) {
printf("\t Signing operation succeeded. Sig is %d bytes.\n", sigbuf_len);
ret = wrapped_sign_verify(
c, *pks, Hashes::SHA256,
test_message, MSG_BUFFER_LEN,
sig_buffer, &sigbuf_len,
public_buf, public_len,
OP_VERIFY
);
if (0 == ret) {
printf("\t Verify operation succeeded.\n");
printf(
"\t Size estimate deltas:\t%d / %d / %d (pub/priv/sig)\n\n",
(public_estimate - public_len),
(privat_estimate - privat_len),
(sigbuf_estimate - sigbuf_len)
);
if (nullptr != asym_estimate_deltas[*pks]) {
asym_estimate_deltas[*pks]->deltas[0] = (strict_min(asym_estimate_deltas[*pks]->deltas[0], (public_estimate - public_len)));
asym_estimate_deltas[*pks]->deltas[1] = (strict_min(asym_estimate_deltas[*pks]->deltas[1], (privat_estimate - privat_len)));
asym_estimate_deltas[*pks]->deltas[2] = (strict_min(asym_estimate_deltas[*pks]->deltas[2], (sigbuf_estimate - sigbuf_len)));
}
else {
asym_estimate_deltas[*pks] = new Trips;
asym_estimate_deltas[*pks]->deltas[0] = (public_estimate - public_len);
asym_estimate_deltas[*pks]->deltas[1] = (privat_estimate - privat_len);
asym_estimate_deltas[*pks]->deltas[2] = (sigbuf_estimate - sigbuf_len);
}
}
else {
crypt_error_string(ret, (char*)&err_buf, 128);
printf("\t Verify for %s failed with err %s (code 0x%04x).\n", get_pk_label(*pks), (char*)&err_buf, ret);
return -1;
}
}
else {
crypt_error_string(ret, (char*)&err_buf, 128);
printf("\t Signing for %s failed with err %s (code 0x%04x).\n", get_pk_label(*pks), (char*)&err_buf, ret);
return -1;
}
}
else {
crypt_error_string(ret, (char*)&err_buf, 128);
printf("\t Keygen for %s failed with err %s (code 0x%04x).\n", get_pk_label(*pks), (char*)&err_buf, ret);
return -1;
}
pks++;
}
return 0;
}
/*
* Asymmetric algorthms.
*/
int CRYPTO_TEST_ASYMMETRIC() {
CryptoKey _pks[] = {CryptoKey::RSA_2048, CryptoKey::RSA_4096, CryptoKey::NONE};
for (int i = 0; i < 1; i++) {
printf("===< CRYPTO_TEST_ASYMMETRIC_ECDSA >==============================\n");
if (CRYPTO_TEST_ASYMMETRIC_SET(Cipher::ASYM_ECDSA, list_supported_curves())) return -1;
printf("===< CRYPTO_TEST_ASYMMETRIC_ECP >================================\n");
if (CRYPTO_TEST_ASYMMETRIC_SET(Cipher::ASYM_ECKEY, list_supported_curves())) return -1;
printf("===< CRYPTO_TEST_ASYMMETRIC_RSA >================================\n");
if (CRYPTO_TEST_ASYMMETRIC_SET(Cipher::ASYM_RSA, &_pks[0])) return -1;
}
// Print the estimate differentials.
std::map<CryptoKey, Trips*>::iterator it;
for (it = asym_estimate_deltas.begin(); it != asym_estimate_deltas.end(); it++) {
printf("\t %s\n", get_pk_label(it->first));
printf("\t Public: %d\n", it->second->deltas[0]);
printf("\t Private: %d\n", it->second->deltas[1]);
printf("\t Sig: %d\n\n", it->second->deltas[2]);
}
return 0;
}
#else
int CRYPTO_TEST_ASYMMETRIC() {
// Build doesn't have asymmetric support.
printf("Build doesn't have asymmetric support. Skipping tests...\n");
return 0;
}
#endif // __BUILD_HAS_ASYMMETRIC
void printTestFailure(const char* test) {
printf("\n");
printf("*********************************************\n");
printf("* %s FAILED tests.\n", test);
printf("*********************************************\n");
}
/*******************************************************************************
* The main function. *
*******************************************************************************/
int main(int argc, char *argv[]) {
int exit_value = 1; // Failure is the default result.
platform.platformPreInit(); // Our test fixture needs random numbers.
platform.bootstrap();
// TODO: This is presently needed to prevent the program from hanging. WHY??
StringBuilder out;
platform.kernel()->printScheduler(&out);
StringBuilder log;
platform.printCryptoOverview(&log);
printf("%s\n", (const char*) log.string());
if (0 == CRYPTO_TEST_INIT()) {
if (0 == CRYPTO_TEST_RNG()) {
if (0 == CRYPTO_TEST_HASHES()) {
if (0 == CRYPTO_TEST_SYMMETRIC()) {
if (0 == CRYPTO_TEST_ASYMMETRIC()) {
printf("**********************************\n");
printf("* Cryptography tests all pass *\n");
printf("**********************************\n");
exit_value = 0;
}
else printTestFailure("CRYPTO_TEST_ASYMMETRIC");
}
else printTestFailure("CRYPTO_TEST_SYMMETRIC");
}
else printTestFailure("CRYPTO_TEST_HASHES");
}
else printTestFailure("CRYPTO_TEST_RNG");
}
else printTestFailure("CRYPTO_TEST_INIT");
#if defined(__BUILD_HAS_ASYMMETRIC)
std::map<CryptoKey, Trips*>::iterator it;
for (it = asym_estimate_deltas.begin(); it != asym_estimate_deltas.end(); it++) {
delete it->second;
}
#endif
exit(exit_value);
}
| 31.477647 | 136 | 0.596427 | [
"3d"
] |
84117a9d1b16847803a057b848cda374eef0053c | 3,369 | cpp | C++ | test/find_dag_equivalence.cpp | mdsudara/percy | b593922b98c9c20fe0a3e4726e50401e54b9cb09 | [
"MIT"
] | 14 | 2018-03-10T21:50:20.000Z | 2021-11-22T04:09:09.000Z | test/find_dag_equivalence.cpp | mdsudara/percy | b593922b98c9c20fe0a3e4726e50401e54b9cb09 | [
"MIT"
] | 3 | 2018-06-12T15:17:22.000Z | 2019-06-20T12:00:45.000Z | test/find_dag_equivalence.cpp | mdsudara/percy | b593922b98c9c20fe0a3e4726e50401e54b9cb09 | [
"MIT"
] | 12 | 2018-03-10T17:02:07.000Z | 2022-01-09T16:04:56.000Z | #include <percy/percy.hpp>
#include <chrono>
#include <thread>
#define MAX_TESTS 512
#if 0
using namespace percy;
using kitty::static_truth_table;
/*******************************************************************************
In this module, we test the equivalence of the sequential and parallel
find_dag implementations.
*******************************************************************************/
template<int nr_in>
auto
get_npn_classes()
{
std::unordered_set<static_truth_table<nr_in>, kitty::hash<static_truth_table<nr_in>>> classes;
static_truth_table<1 << nr_in> map;
std::transform(map.cbegin(), map.cend(), map.begin(),
[]( auto w ) { return ~w; } );
int64_t index = 0;
static_truth_table<nr_in> tt;
while (index != -1) {
kitty::create_from_words(tt, &index, &index + 1);
const auto res = kitty::exact_npn_canonization(
tt, [&map]( const auto& tt ) {
kitty::clear_bit( map, *tt.cbegin() );
}
);
classes.insert( std::get<0>( res ) );
index = find_first_one_bit( map );
}
printf("[i] enumerated %lu functions into %lu classes\n",
map.num_bits(), classes.size());
return classes;
}
template<int nr_in>
void check_npn_equivalence()
{
dag<2> g1, g2;
auto npn_set = get_npn_classes<nr_in>();
const auto num_cpus = std::thread::hardware_concurrency();
int i = 1;
const auto total = npn_set.size();
synth_spec<static_truth_table<nr_in>> spec(nr_in, 1);
auto synth = new_dag_synth();
chain<2> c;
for (auto& npn_tt : npn_set) {
static_truth_table<nr_in> tt = npn_tt;
// We skip the trivial functions
if (is_trivial(tt)) {
printf("(%d/%d)\r", i++, total);
fflush(stdout);
continue;
}
spec.functions[0] = &tt;
auto seq_start = std::chrono::high_resolution_clock::now();
auto seq_result = find_dag(spec, g1, nr_in);
auto seq_stop = std::chrono::high_resolution_clock::now();
auto synth_stat1 = synth->synthesize(spec, g1, c);
assert(seq_result == success);
assert(synth_stat1 == success);
auto qpar_start = std::chrono::high_resolution_clock::now();
auto qpar_result = qpfind_dag(spec, g2, nr_in);
auto qpar_stop = std::chrono::high_resolution_clock::now();
auto synth_stat2 = synth->synthesize(spec, g2, c);
assert(qpar_result == success);
assert(synth_stat2 == success);
assert(g1.get_nr_vertices() == g2.get_nr_vertices());
printf("Time elapsed: %fms (SEQ)\n",
std::chrono::duration<double,std::milli>(
seq_stop-seq_start).count());
printf("Time elapsed: %fms (QPAR)\n",
std::chrono::duration<double,std::milli>(
qpar_stop-qpar_start).count());
printf("(%d/%d)\r", i++, total);
fflush(stdout);
}
printf("\n");
}
int main(void)
{
const auto num_cpus = std::thread::hardware_concurrency();
// TODO: fix Travis errors.
#ifndef TRAVIS_BUILD
check_npn_equivalence<2>();
check_npn_equivalence<3>();
if (num_cpus >= 6) {
check_npn_equivalence<4>();
}
#endif
return 0;
}
#endif
int main() { return 0; } | 27.842975 | 98 | 0.563075 | [
"transform"
] |
8428c1f2d512f5af7015d9a37ea7427f6ad5fbb9 | 4,476 | hpp | C++ | src/Module_trigSeq.hpp | miRackModular/trowaSoft-VCV | 56ab2f95bcd0f788b3eb8714718c972cbb0546d9 | [
"MIT"
] | null | null | null | src/Module_trigSeq.hpp | miRackModular/trowaSoft-VCV | 56ab2f95bcd0f788b3eb8714718c972cbb0546d9 | [
"MIT"
] | null | null | null | src/Module_trigSeq.hpp | miRackModular/trowaSoft-VCV | 56ab2f95bcd0f788b3eb8714718c972cbb0546d9 | [
"MIT"
] | null | null | null | #ifndef MODULE_TRIGSEQ_HPP
#define MODULE_TRIGSEQ_HPP
#include <string.h>
#include <stdio.h>
//#include "trowaSoft.hpp"
//#include "dsp/digital.hpp"
#include "TSSequencerWidgetBase.hpp"
#include "trowaSoftComponents.hpp"
#include "trowaSoftUtilities.hpp"
#include "TSSequencerModuleBase.hpp"
#define trigSeq_GATE_ON_OUTPUT 10.0 // If gate is on, the value to output (port Voltage)
#define trigSeq_GATE_OFF_OUTPUT 0.0 // If gate is off, the value to output (port Voltage)
// Single instance to the trigSeq Models.
// trigSeq (16-step) model
extern Model* modelTrigSeq;
// trigSeq (64-step) model
extern Model* modelTrigSeq64;
//===============================================================================
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeq Module
// trowaSoft pad / trigger sequencer.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//===============================================================================
struct trigSeq : TSSequencerModuleBase
{
trigSeq(int numSteps, int numRows, int numCols) : TSSequencerModuleBase(numSteps, numRows, numCols, false)
{
gateTriggers = new dsp::SchmittTrigger[numSteps]; // maxSteps
selectedOutputValueMode = VALUE_TRIGGER;
lastOutputValueMode = selectedOutputValueMode;
modeStrings[0] = "TRIG";
modeStrings[1] = "RTRG";
modeStrings[2] = "GATE";
// Configure Parameters:
for (int s = 0; s < maxSteps; s++) {
configParam(TSSequencerModuleBase::CHANNEL_PARAM + s, 0.0, 1.0, defaultStateValue, /*label*/ "Step " + std::to_string(s+1));
}
for (int i = 0; i < ValueMode::NUM_VALUE_MODES; i++)
{
dynamic_cast<TS_ParamQuantityEnum*>(this->paramQuantities[TSSequencerModuleBase::ParamIds::SELECTED_OUTPUT_VALUE_MODE_PARAM])->addToEnumMap(i, modeStrings[i]);
}
return;
}
trigSeq() : trigSeq(TROWA_SEQ_NUM_STEPS, TROWA_SEQ_STEP_NUM_ROWS, TROWA_SEQ_STEP_NUM_ROWS)
{
return;
}
~trigSeq()
{
delete [] gateTriggers;
gateTriggers = NULL;
return;
}
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// process()
// [Previously step(void)]
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
void process(const ProcessArgs &args) override;
// Only randomize the current gate/trigger steps.
void onRandomize() override;
// Get the toggle step value
float getToggleStepValue(int step, float val, int channel, int pattern) override;
// Calculate a representation of all channels for this step
float getPlayingStepValue(int step, int pattern) override;
};
//===============================================================================
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeq64 Module
// trowaSoft 64-step pad / trigger sequencer.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//===============================================================================
struct trigSeq64 : trigSeq {
trigSeq64() : trigSeq(N64_NUM_STEPS, N64_NUM_ROWS, N64_NUM_COLS)
{
return;
}
};
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeqWidget
// Widget for the trowaSoft pad / trigger sequencer.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
struct trigSeqWidget : TSSequencerWidgetBase {
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeqWidget()
// Widget for the trowaSoft 16-step pad / trigger sequencer.
// @seqModule : (IN) Pointer to the sequencer module.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
trigSeqWidget(trigSeq* seqModule);
};
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeq64Widget
// Widget for the trowaSoft 64-step sequencer.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
struct trigSeq64Widget : TSSequencerWidgetBase {
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeq64Widget()
// Widget for the trowaSoft 64-step sequencer.
// @seqModule : (IN) Pointer to the sequencer module.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
trigSeq64Widget(trigSeq* seqModule);
};
#endif | 39.964286 | 163 | 0.476765 | [
"model"
] |
842dc1279297664737efb6f74d979c6ed0e46af5 | 880 | cpp | C++ | Algorithms/0929.Unique_Email_Addresses.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0929.Unique_Email_Addresses.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0929.Unique_Email_Addresses.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
int numUniqueEmails(vector<string>& emails) {
unordered_set<string> myset;
int n = emails.size();
for( int i = 0 ; i < n ; i++ ) {
int len = emails[i].size();
int indexDomain = 0;
bool isPlus = false;
string localName = "";
while(indexDomain < len && emails[i][indexDomain] != '@') {
if(!isPlus) {
if(emails[i][indexDomain] == '+')
isPlus = true;
else if(emails[i][indexDomain] != '.')
localName = localName + emails[i][indexDomain];
}
indexDomain++;
}
string email = localName + emails[i].substr(indexDomain,len-indexDomain);
myset.insert(email);
}
return myset.size();
}
}; | 35.2 | 85 | 0.455682 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.