hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6a79ed6d1e35d244ed967fe0902d23a291ffafc7 | 3,909 | hpp | C++ | src/extra/imgui.hpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 12 | 2021-07-11T11:14:14.000Z | 2022-03-28T11:37:29.000Z | src/extra/imgui.hpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 103 | 2021-06-26T17:09:43.000Z | 2022-03-30T12:05:18.000Z | src/extra/imgui.hpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 8 | 2021-07-27T14:45:26.000Z | 2022-03-01T08:07:18.000Z | /* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright © 2019 Fragcolor Pte. Ltd. */
#pragma once
#include "foundation.hpp"
#include "imgui.h"
#include "ImGuizmo.h"
namespace ImGuiExtra {
#include "imgui_memory_editor.h"
};
namespace chainblocks {
namespace ImGui {
constexpr uint32_t ImGuiContextCC = 'gui ';
struct Context {
static inline Type Info{
{CBType::Object,
{.object = {.vendorId = CoreCC, .typeId = ImGuiContextCC}}}};
// Useful to compare with with plugins, they might mismatch!
static inline const char *Version = ::ImGui::GetVersion();
// ImGuiContext *context = ::ImGui::CreateContext();
// ~Context() { ::ImGui::DestroyContext(context); }
// void Set() { ::ImGui::SetCurrentContext(context); }
// void Reset() {
// ::ImGui::DestroyContext(context);
// context = ::ImGui::CreateContext();
// }
};
struct Enums {
#define REGISTER_FLAGS_EX(_NAME_, _CC_) \
REGISTER_FLAGS(_NAME_, _CC_); \
static inline Type _NAME_##SeqType = Type::SeqOf(_NAME_##Type); \
static inline Type _NAME_##VarType = Type::VariableOf(_NAME_##Type); \
static inline Type _NAME_##VarSeqType = Type::VariableOf(_NAME_##SeqType)
enum class GuiButton {
Normal,
Small,
Invisible,
ArrowLeft,
ArrowRight,
ArrowUp,
ArrowDown
};
REGISTER_ENUM(GuiButton, 'guiB'); // FourCC = 0x67756942
enum class GuiTableFlags {
None = ::ImGuiTableFlags_None,
Resizable = ::ImGuiTableFlags_Resizable,
Reorderable = ::ImGuiTableFlags_Reorderable,
Hideable = ::ImGuiTableFlags_Hideable,
Sortable = ::ImGuiTableFlags_Sortable
};
REGISTER_FLAGS_EX(GuiTableFlags, 'guiT'); // FourCC = 0x67756954
enum class GuiTableColumnFlags {
None = ::ImGuiTableColumnFlags_None,
Disabled = ::ImGuiTableColumnFlags_Disabled,
DefaultHide = ::ImGuiTableColumnFlags_DefaultHide,
DefaultSort = ::ImGuiTableColumnFlags_DefaultSort
};
REGISTER_FLAGS_EX(GuiTableColumnFlags, 'guTC'); // FourCC = 0x67755443
enum class GuiTreeNodeFlags {
None = ::ImGuiTreeNodeFlags_None,
Selected = ::ImGuiTreeNodeFlags_Selected,
Framed = ::ImGuiTreeNodeFlags_Framed,
OpenOnDoubleClick = ::ImGuiTreeNodeFlags_OpenOnDoubleClick,
OpenOnArrow = ::ImGuiTreeNodeFlags_OpenOnArrow,
Leaf = ::ImGuiTreeNodeFlags_Leaf,
Bullet = ::ImGuiTreeNodeFlags_Bullet,
SpanAvailWidth = ::ImGuiTreeNodeFlags_SpanAvailWidth,
SpanFullWidth = ::ImGuiTreeNodeFlags_SpanFullWidth
};
REGISTER_FLAGS_EX(GuiTreeNodeFlags, 'guTN'); // FourCC = 0x6775544E
enum class GuiWindowFlags {
None = ::ImGuiWindowFlags_None,
NoTitleBar = ::ImGuiWindowFlags_NoTitleBar,
NoResize = ::ImGuiWindowFlags_NoResize,
NoMove = ::ImGuiWindowFlags_NoMove,
NoScrollbar = ::ImGuiWindowFlags_NoScrollbar,
NoScrollWithMouse = ::ImGuiWindowFlags_NoScrollWithMouse,
NoCollapse = ::ImGuiWindowFlags_NoCollapse,
AlwaysAutoResize = ::ImGuiWindowFlags_AlwaysAutoResize,
NoBackground = ::ImGuiWindowFlags_NoBackground,
NoSavedSettings = ::ImGuiWindowFlags_NoSavedSettings,
NoMouseInputs = ::ImGuiWindowFlags_NoMouseInputs,
MenuBar = ::ImGuiWindowFlags_MenuBar,
HorizontalScrollbar = ::ImGuiWindowFlags_HorizontalScrollbar,
NoFocusOnAppearing = ::ImGuiWindowFlags_NoFocusOnAppearing,
NoBringToFrontOnFocus = ::ImGuiWindowFlags_NoBringToFrontOnFocus,
AlwaysVerticalScrollbar = ::ImGuiWindowFlags_AlwaysVerticalScrollbar,
AlwaysHorizontalScrollbar = ::ImGuiWindowFlags_AlwaysHorizontalScrollbar,
AlwaysUseWindowPadding = ::ImGuiWindowFlags_AlwaysUseWindowPadding,
NoNavInputs = ::ImGuiWindowFlags_NoNavInputs,
NoNavFocus = ::ImGuiWindowFlags_NoNavFocus
};
REGISTER_FLAGS_EX(GuiWindowFlags, 'guiW'); // FourCC = 0x67756957
};
}; // namespace ImGui
}; // namespace chainblocks
| 34.59292 | 80 | 0.718086 | fragcolor-xyz |
6a7d6dfca39b3dc36cafc780f54a6beca726a6b1 | 1,198 | cpp | C++ | 2446.cpp | gabrielld06/Exercicios-URI | 5a8146a0246cd133fac340b9d11dc60d88b8a94b | [
"MIT"
] | null | null | null | 2446.cpp | gabrielld06/Exercicios-URI | 5a8146a0246cd133fac340b9d11dc60d88b8a94b | [
"MIT"
] | null | null | null | 2446.cpp | gabrielld06/Exercicios-URI | 5a8146a0246cd133fac340b9d11dc60d88b8a94b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define False 'N'
#define True 'S'
using namespace std;
char memo[100002][1002];
void resetar_memo(int n, int m) {
for(int i=0;i<=n;i++) {
for(int j=0;j<=m;j++) {
memo[i][j] = 'F';
}
}
}
char coins(int v, int m, vector<int> moedas) {
int troco;
char ans, add, nadd;
if(memo[v][m] == 'F') {
if(m == 0 and v != 0) {
ans = False;
} else if(v == 0) {
ans = True;
} else if(v < 0) {
ans = False;
} else {
troco = v-moedas[m-1];
if(troco == 0) {
ans = True;
} else {
if(troco >= 0) {
add = coins(troco, m-1, moedas);
} else
add = False;
nadd = (add == True ? True : coins(v, m-1, moedas));
ans = (add == True ? add : nadd);
}
}
memo[v][m] = ans;
}
return memo[v][m];
}
int main() {
int v, m, in;
vector<int> moedas;
cin >> v >> m;
for(int i=0;i<m;i++) {
scanf("%d", &in);
moedas.push_back(in);
}
sort(moedas.begin(), moedas.begin()+m);
vector<int>::iterator lb;
lb = lower_bound(moedas.begin(), moedas.end(), v);
if(moedas[lb - moedas.begin()] == v) {
cout << True << "\n";
} else {
resetar_memo(v+1, m+1);
cout << coins(v, lb-moedas.begin()+1, moedas) << "\n";
}
return 0;
} | 19.015873 | 56 | 0.519199 | gabrielld06 |
6a7f445012ee80a87615dba95ec02813158ac857 | 1,506 | cpp | C++ | src/server/piece/Piece.cpp | LB--/ChessPlusPlus | 70b389f0c3f4a5299ed4a2292bed22383ff95ed0 | [
"Apache-1.1"
] | 1 | 2021-07-11T18:04:34.000Z | 2021-07-11T18:04:34.000Z | src/server/piece/Piece.cpp | LB--/ChessPlusPlus | 70b389f0c3f4a5299ed4a2292bed22383ff95ed0 | [
"Apache-1.1"
] | null | null | null | src/server/piece/Piece.cpp | LB--/ChessPlusPlus | 70b389f0c3f4a5299ed4a2292bed22383ff95ed0 | [
"Apache-1.1"
] | 2 | 2017-10-02T23:25:35.000Z | 2019-09-08T10:03:34.000Z | #include "Piece.hpp"
#include "server/board/Board.hpp"
#include <algorithm>
#include <iostream>
namespace chesspp { namespace server
{
namespace piece
{
Piece::Piece(board::Board &b, Position_t const &pos_, Suit_t const &s_, Class_t const &pc)
: board(b) //can't use {}
, p{pos_}
, s{s_}
, c{pc}
{
std::clog << "Creation of " << *this << std::endl;
}
void Piece::addTrajectory(Position_t const &tile)
{
board.pieceTrajectories().add(*this, tile);
}
void Piece::removeTrajectory(Position_t const &tile)
{
board.pieceTrajectories().remove(*this, tile);
}
void Piece::addCapturing(Position_t const &tile)
{
board.pieceCapturings().add(*this, tile);
}
void Piece::removeCapturing(Position_t const &tile)
{
board.pieceCapturings().remove(*this, tile);
}
void Piece::addCapturable(Position_t const &tile)
{
board.pieceCapturables().add(*this, tile);
}
void Piece::removeCapturable(Position_t const &tile)
{
board.pieceCapturables().remove(*this, tile);
}
std::ostream &operator<<(std::ostream &os, Piece const &p)
{
return os << "Piece (" << typeid(p).name() << ") \"" << p.suit << "\" \"" << p.pclass << "\" at " << p.pos << " having made " << p.moves << " moves";
}
}
}}
| 27.888889 | 161 | 0.527224 | LB-- |
6a803adcce9188677525ac3aca370c64bcdc4a90 | 849 | cpp | C++ | data/dailyCodingProblem189.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | 2 | 2020-09-04T20:56:23.000Z | 2021-06-11T07:42:26.000Z | data/dailyCodingProblem189.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | data/dailyCodingProblem189.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
Given an array of elements, return the length of the longest
subarray where all its elements are distinct.
For example, given the array [5, 1, 3, 5, 2, 3, 4, 1],
return 5 as the longest subarray of distinct elements is [5, 2, 3, 4, 1].
*/
int longestSubarrayDistinct(int arr[], int n){
int start = 0, max_len = 0;
unordered_map<int, int> seen;
for(int i=0; i<n; i++){
if(seen.find(arr[i]) != seen.end()){
int last_seen = seen[arr[i]];
if(last_seen >= start){
int length = start - i;
max_len = max(max_len, length);
start = last_seen + 1;
}
}
else{
seen[arr[i]] = i;
}
}
return max_len;
}
// main function
int main(){
int arr[] = {5, 1, 3, 5, 2, 3, 4, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << longestSubarrayDistinct(arr, n) << "\n";
return 0;
} | 21.769231 | 73 | 0.613663 | vidit1999 |
6a857de1c3a9b0b7e45629a7174adcf690b737ed | 2,056 | cpp | C++ | win9x/np2arg.cpp | Tatsuya79/NP2kai | ef8c450135f95bb71a463fe7284ce35107df38d7 | [
"MIT"
] | null | null | null | win9x/np2arg.cpp | Tatsuya79/NP2kai | ef8c450135f95bb71a463fe7284ce35107df38d7 | [
"MIT"
] | null | null | null | win9x/np2arg.cpp | Tatsuya79/NP2kai | ef8c450135f95bb71a463fe7284ce35107df38d7 | [
"MIT"
] | null | null | null | /**
* @file np2arg.cpp
* @brief 引数情報クラスの動作の定義を行います
*/
#include "compiler.h"
#include "np2arg.h"
#include "dosio.h"
#define MAXARG 32 //!< 最大引数エントリ数
#define ARG_BASE 1 //!< win32 の lpszCmdLine の場合の開始エントリ
//! 唯一のインスタンスです
Np2Arg Np2Arg::sm_instance;
/**
* コンストラクタ
*/
Np2Arg::Np2Arg()
{
ZeroMemory(this, sizeof(*this));
}
/**
* デストラクタ
*/
Np2Arg::~Np2Arg()
{
free(m_lpArg);
if(m_lpIniFile) free((TCHAR*)m_lpIniFile); // np21w ver0.86 rev8
}
/**
* パース
*/
void Np2Arg::Parse()
{
// 引数読み出し
free(m_lpArg);
m_lpArg = _tcsdup(::GetCommandLine());
LPTSTR argv[MAXARG];
const int argc = ::milstr_getarg(m_lpArg, argv, _countof(argv));
int nDrive = 0;
for (int i = ARG_BASE; i < argc; i++)
{
LPCTSTR lpArg = argv[i];
if ((lpArg[0] == TEXT('/')) || (lpArg[0] == TEXT('-')))
{
switch (_totlower(lpArg[1]))
{
case 'f':
m_fFullscreen = true;
break;
case 'i':
m_lpIniFile = &lpArg[2];
break;
}
}
else
{
LPCTSTR lpExt = ::file_getext(lpArg);
if (::file_cmpname(lpExt, TEXT("ini")) == 0 || ::file_cmpname(lpExt, TEXT("npc")) == 0 || ::file_cmpname(lpExt, TEXT("npcfg")) == 0 || ::file_cmpname(lpExt, TEXT("np2cfg")) == 0 || ::file_cmpname(lpExt, TEXT("np21cfg")) == 0 || ::file_cmpname(lpExt, TEXT("np21wcfg")) == 0)
{
m_lpIniFile = lpArg;
}
else if (nDrive < _countof(m_lpDisk))
{
m_lpDisk[nDrive++] = lpArg;
}
}
}
if(m_lpIniFile){ // np21w ver0.86 rev8
LPTSTR strbuf;
strbuf = (LPTSTR)calloc(500, sizeof(TCHAR));
if(!(_tcsstr(m_lpIniFile,_T(":"))!=NULL || (m_lpIniFile[0]=='\\'))){
// ファイル名のみの指定っぽかったら現在のディレクトリを結合
//getcwd(pathname, 300);
GetCurrentDirectory(500, strbuf);
if(strbuf[_tcslen(strbuf)-1]!='\\'){
_tcscat(strbuf, _T("\\")); // XXX: Linuxとかだったらスラッシュじゃないと駄目だよね?
}
}
_tcscat(strbuf, m_lpIniFile);
m_lpIniFile = strbuf;
}
}
/**
* ディスク情報をクリア
*/
void Np2Arg::ClearDisk()
{
ZeroMemory(m_lpDisk, sizeof(m_lpDisk));
}
| 20.767677 | 277 | 0.574903 | Tatsuya79 |
6a85da5fb4f57431ce5effe082ea022a6b6b5d64 | 192 | hpp | C++ | TeaGameLib/include/InternalGameLib/InternalGameLib.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 11 | 2020-03-08T03:12:38.000Z | 2020-10-30T14:35:39.000Z | TeaGameLib/include/InternalGameLib/InternalGameLib.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 3 | 2020-03-09T06:46:24.000Z | 2020-03-19T11:00:12.000Z | TeaGameLib/include/InternalGameLib/InternalGameLib.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 1 | 2020-03-19T09:42:45.000Z | 2020-03-19T09:42:45.000Z | #pragma once
#include "../Input/KeyStates.hpp"
#include "../WindowEvent/EventStates.hpp"
namespace teaGameLib {
input::KeyStates GetKeyStates();
windowEvent::EventStates GetEventStates();
} | 24 | 43 | 0.765625 | Perukii |
6a87266706f34dde761fb807eefe35b119d51767 | 4,174 | cpp | C++ | catboost/python-package/ut/medium/canondata/test.test_cpp_export_no_cat_features_CPU_/model.cpp | EkaterinaPogodina/catboost | 4628e86e978da2ec5e4d42f6b8d05e0b5e8aab30 | [
"Apache-2.0"
] | 2 | 2019-07-10T10:49:09.000Z | 2020-06-19T11:40:04.000Z | catboost/python-package/ut/medium/canondata/test.test_cpp_export_no_cat_features_CPU_/model.cpp | EkaterinaPogodina/catboost | 4628e86e978da2ec5e4d42f6b8d05e0b5e8aab30 | [
"Apache-2.0"
] | null | null | null | catboost/python-package/ut/medium/canondata/test.test_cpp_export_no_cat_features_CPU_/model.cpp | EkaterinaPogodina/catboost | 4628e86e978da2ec5e4d42f6b8d05e0b5e8aab30 | [
"Apache-2.0"
] | null | null | null | #include <string>
#include <vector>
/* Model data */
static const struct CatboostModel {
unsigned int FloatFeatureCount = 50;
unsigned int BinaryFeatureCount = 12;
unsigned int TreeCount = 2;
unsigned int TreeDepth[2] = {6, 6};
unsigned int TreeSplits[12] = {7, 5, 0, 4, 9, 3, 11, 6, 1, 10, 2, 8};
unsigned int BorderCounts[50] = {1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0};
float Borders[12] = {0.168183506f, 0.136649996f, 0.5f, 0.645990014f, 0.272549003f, 0.5f, 0.5f, 0.00311657996f, 0.392024517f, 0.163893014f, 0.387494028f, 0.767975509f, };
/* Aggregated array of leaf values for trees. Each tree is represented by a separate line: */
double LeafValues[128] = {
0, 0, 0.001049999981001019, 0, 0.0006999999873340129, 0.0004199999924004077, 0, 0.0003499999936670065, 0.0006999999873340129, 0, 0, 0, 0.0008999999837151595, 0.0008399999848008155, 0, 0.005499108720590722, 0, 0, 0.001310204828003209, 0, 0, 0, 0.002099799992893635, 0.003281666943095616, 0, 0, 0.001081739094670376, 0, 0, 0, 0.001261285375551461, 0.003276219466932844, 0.0001235294095295317, 0, 0.001143749976810068, 0, 0, 0, 0.002145652130229966, 0.001699999969239746, 0.0005409089896827957, 0, 0.0004052632035001316, 0, 0.001076041724695822, 0, 0.001088611397153381, 0.001412068939966888, 0, 0, 0.001978133278083802, 0.001049999981001019, 0, 0, 0.002257627220401316, 0.002847457878670443, 0, 0, 0.002380742281139534, 0, 0, 0, 0.00181075114546265, 0.003175870739941051,
0.0008166451595296908, 0, 0.001435124236388357, 0, 0.002230458559199401, 0, 0.002666874626702434, 0, 0.001534999525103938, 0.001002557986130936, 0.001371602072510968, 0.001025428335548242, 0.002692151343928724, 0.002324272621936243, 0.001188379847259753, 0.002102531171547649, 0.0002273645927514973, 0, 0.002259198170953273, 0, 0.0005932082092034878, 0, 0.001936697595469175, 0, 0.002274218690520189, 0.00329724810179383, 0.003553552019915716, -2.457164545277724e-05, 0.001361408072189387, 0.002058595183732444, 0.002040357509679229, 0.006411161288685438, 0.001238019183794491, 0, 0.0007759661277461006, 0, 0.002378015135461136, 0, 0.0005649959300306291, 0, 0.001080913918043391, 0.005514189264833609, 0.001790046575156435, 0.001103960055365507, 0.002146005492857177, 0.002352553092417847, 0.001165392567571486, 0, 0.0003389142165572722, 0, 0.000740077287450055, 0, 0.0006711111753359577, 0, 0.001173741518772528, 0, 0.0008677387848554152, 0.003458858412712405, 0.001394273280892068, 0.002416533521423629, 0.003145683167659726, 0.002795911932059462, 0.001047576512888525, 0.003163031305315038
};
} CatboostModelStatic;
/* Model applicator */
double ApplyCatboostModel(
const std::vector<float>& features
) {
const struct CatboostModel& model = CatboostModelStatic;
/* Binarise features */
std::vector<unsigned char> binaryFeatures(model.BinaryFeatureCount);
unsigned int binFeatureIndex = 0;
for (unsigned int i = 0; i < model.FloatFeatureCount; ++i) {
for(unsigned int j = 0; j < model.BorderCounts[i]; ++j) {
binaryFeatures[binFeatureIndex] = (unsigned char)(features[i] > model.Borders[binFeatureIndex]);
++binFeatureIndex;
}
}
/* Extract and sum values from trees */
double result = 0.0;
const unsigned int* treeSplitsPtr = model.TreeSplits;
const double* leafValuesForCurrentTreePtr = model.LeafValues;
for (unsigned int treeId = 0; treeId < model.TreeCount; ++treeId) {
const unsigned int currentTreeDepth = model.TreeDepth[treeId];
unsigned int index = 0;
for (unsigned int depth = 0; depth < currentTreeDepth; ++depth) {
index |= (binaryFeatures[treeSplitsPtr[depth]] << depth);
}
result += leafValuesForCurrentTreePtr[index];
treeSplitsPtr += currentTreeDepth;
leafValuesForCurrentTreePtr += (1 << currentTreeDepth);
}
return result;
}
double ApplyCatboostModel(
const std::vector<float>& floatFeatures,
const std::vector<std::string>&
) {
return ApplyCatboostModel(floatFeatures);
}
| 69.566667 | 1,100 | 0.720891 | EkaterinaPogodina |
6a893cfa08fecc79f54d50b783454a0ae24f444d | 5,127 | cpp | C++ | a3/map_metadata_f/Altis/config.cpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | a3/map_metadata_f/Altis/config.cpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | a3/map_metadata_f/Altis/config.cpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | #include "CfgPatches.hpp"
#include "..\CfgAreaCategories.inc"
class MAP_METADATA_ROOTCLASS
{
class Altis
{
class Fotia
{
#include "Fotia.hpp"
};
class KavalaPier
{
#include "KavalaPier.hpp"
};
class Kastro
{
#include "Kastro.hpp"
};
class Kavala
{
#include "Kavala.hpp"
};
class Athanos
{
#include "Athanos.hpp"
};
class Aggelochori
{
#include "Aggelochori.hpp"
};
class AgiosKonstantinos
{
#include "AgiosKonstantinos.hpp"
};
class Neri
{
#include "Neri.hpp"
};
class PowerPlant02
{
#include "PowerPlant02.hpp"
};
class quarry01
{
#include "quarry01.hpp"
};
class Oreokastro
{
#include "Oreokastro.hpp"
};
class Negades
{
#include "Negades.hpp"
};
class castle
{
#include "castle.hpp"
};
class Panochori
{
#include "Panochori.hpp"
};
class factory04
{
#include "factory04.hpp"
};
class Stadium
{
#include "Stadium.hpp"
};
class Gori
{
#include "Gori.hpp"
};
class factory03
{
#include "factory03.hpp"
};
class Faros
{
#include "Faros.hpp"
};
class Kore
{
#include "Kore.hpp"
};
class Edessa
{
#include "Edessa.hpp"
};
class Topolia
{
#include "Topolia.hpp"
};
class Aristi
{
#include "Aristi.hpp"
};
class Syrta
{
#include "Syrta.hpp"
};
class AgiosKosmas
{
#include "AgiosKosmas.hpp"
};
class Zaros
{
#include "Zaros.hpp"
};
class XirolimniDam
{
#include "XirolimniDam.hpp"
};
class AgiosDionysios
{
#include "AgiosDionysios.hpp"
};
class Abdera
{
#include "Abdera.hpp"
};
class KryaNera
{
#include "KryaNera.hpp"
};
class Galati
{
#include "Galati.hpp"
};
class Orino
{
#include "Orino.hpp"
};
class Therisa
{
#include "Therisa.hpp"
};
class Drimea
{
#include "Drimea.hpp"
};
class Poliakko
{
#include "Poliakko.hpp"
};
class Alikampos
{
#include "Alikampos.hpp"
};
class AACairfield
{
#include "AACairfield.hpp"
};
class Eginio
{
#include "Eginio.hpp"
};
class Vikos
{
#include "Vikos.hpp"
};
class Katalaki
{
#include "Katalaki.hpp"
};
class Lakka
{
#include "Lakka.hpp"
};
class Neochori
{
#include "Neochori.hpp"
};
class factory02
{
#include "factory02.hpp"
};
class Ifestiona
{
#include "Ifestiona.hpp"
};
class Stavros
{
#include "Stavros.hpp"
};
class Athira
{
#include "Athira.hpp"
};
class airbase01
{
#include "airbase01.hpp"
};
class Gravia
{
#include "Gravia.hpp"
};
class terminal01
{
#include "terminal01.hpp"
};
class Frini
{
#include "Frini.hpp"
};
class Faronaki
{
#include "Faronaki.hpp"
};
class military02
{
#include "military02.hpp"
};
class PowerPlant01
{
#include "PowerPlant01.hpp"
};
class military03
{
#include "military03.hpp"
};
class Telos
{
#include "Telos.hpp"
};
class Anthrakia
{
#include "Anthrakia.hpp"
};
class ChelonisiIsland
{
#include "ChelonisiIsland.hpp"
};
class AgiaTriada
{
#include "AgiaTriada.hpp"
};
class Pyrgos
{
#include "Pyrgos.hpp"
};
class Nychi
{
#include "Nychi.hpp"
};
class quarry02
{
#include "quarry02.hpp"
};
class Kalithea
{
#include "Kalithea.hpp"
};
class Charkia
{
#include "Charkia.hpp"
};
class storage01
{
#include "storage01.hpp"
};
class Livadi
{
#include "Livadi.hpp"
};
class Mine01
{
#include "Mine01.hpp"
};
class Rodopoli
{
#include "Rodopoli.hpp"
};
class Dorida
{
#include "Dorida.hpp"
};
class AgiosPetros
{
#include "AgiosPetros.hpp"
};
class Nifi
{
#include "Nifi.hpp"
};
class quarry03
{
#include "quarry03.hpp"
};
class Chalkeia
{
#include "Chalkeia.hpp"
};
class Panagia
{
#include "Panagia.hpp"
};
class Selakano
{
#include "Selakano.hpp"
};
class Paros
{
#include "Paros.hpp"
};
class SufrClub
{
#include "SufrClub.hpp"
};
class Kalochori
{
#include "Kalochori.hpp"
};
class Aktinarki
{
#include "Aktinarki.hpp"
};
class Iraklia
{
#include "Iraklia.hpp"
};
class Feres
{
#include "Feres.hpp"
};
class Trachia
{
#include "Trachia.hpp"
};
class AgiaPelagia
{
#include "AgiaPelagia.hpp"
};
class CapKategidis
{
#include "CapKategidis.hpp"
};
class Ioannina
{
#include "Ioannina.hpp"
};
class Sideras
{
#include "Sideras.hpp"
};
class Nidasos
{
#include "Nidasos.hpp"
};
class Delfinaki
{
#include "Delfinaki.hpp"
};
class CapThelos
{
#include "CapThelos.hpp"
};
class Sofia
{
#include "Sofia.hpp"
};
class Limnichori
{
#include "Limnichori.hpp"
};
class Gatolia
{
#include "Gatolia.hpp"
};
class MolosAirfield
{
#include "MolosAirfield.hpp"
};
class Molos
{
#include "Molos.hpp"
};
class Polemistia
{
#include "Polemistia.hpp"
};
class CapStrigla
{
#include "CapStrigla.hpp"
};
};
};
| 13.179949 | 35 | 0.586113 | tom4897 |
6a89b95f2bc2cb559c90d7f33a033c182a99d24e | 3,430 | cpp | C++ | leetcode/docu/522.cpp | sczzq/symmetrical-spoon | aa0c27bb40a482789c7c6a7088307320a007b49b | [
"Unlicense"
] | null | null | null | leetcode/docu/522.cpp | sczzq/symmetrical-spoon | aa0c27bb40a482789c7c6a7088307320a007b49b | [
"Unlicense"
] | null | null | null | leetcode/docu/522.cpp | sczzq/symmetrical-spoon | aa0c27bb40a482789c7c6a7088307320a007b49b | [
"Unlicense"
] | null | null | null | #include "cpp_header.h"
class Solution
{
struct customGreater1 {
bool operator()(const string & a, const string & b) const
{
return a.length() > b.length();
}
} ;
struct {
bool operator()(const string & a, const string & b) const
{
return a.length() > b.length();
}
} customGreater2;
public:
int findLUSlength(vector<string> strs)
{
int res = -1;
if(strs.size() > 0)
{
sort(strs.begin(), strs.end(), customGreater2); // nlgn
unordered_map<string, int> str_count;
for(auto & s : strs)
{
str_count[s]++;
}
auto last = unique(strs.begin(), strs.end()); // n
strs.erase(last, strs.end());
/*
cout << "--------------------------\n";
for(auto x : str_count)
{
cout << x.first << ", " << x.second << "\n";
}
cout << "--------------------------\n";
*/
for(auto it = strs.begin(); it != strs.end(); it++)
{
if(str_count[*it] == 1)
{
bool is_solo = true;
for(auto it2 = strs.begin(); it2 != it; it2++)
{
if(is_contained(*it, *it2))
{
is_solo = false;
break;
}
}
if(is_solo)
{
res = it->length();
break;
}
}
}
}
return res;
}
// time: O(n)
// memory: O(1)
bool is_contained(const string & s1, const string & s2)
{
int m = 0, n = 0;
bool res = false;
while( m < s1.length() && n < s2.length() )
{
if(s1[m] != s2[n])
{
n++;
}
else
{
m++;
n++;
}
}
if(m == s1.length())
{
res = true;
}
return res;
}
};
bool testcase(vector<string> strs, int res, int casenum)
{
Solution sol;
if( sol.findLUSlength(strs) == res )
{
cout << casenum << " pass\n";
}
else
{
cout << casenum << " no pass\n";
cout << "detail:\n";
for(auto & s : strs)
{
cout << s << "-- ";
}
cout << "\n";
}
cout << "-----------------------------------------\n";
}
int main()
{
vector<pair<vector<string>, int>> cases;
vector<string> strs;
strs = {"abc", "abd", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "ab", "bc", "abc", "b", "c", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "ab", "bc", "abc", "b", "c", "bcd", "abc", "bcd"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "a", "a", "a", "a"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "a", "v", "v", "v"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "a", "b", "v", "v"};
cases.push_back(make_pair(strs, 1));
strs = {"aaa", "aaa", "ba", "va", "vaaaaaaaaaaaaaaaaaaaa"};
cases.push_back(make_pair(strs, 21));
strs = {"aaa", "aaa", "ba", "va", "vaaaa", "vaaaa", "ab"};
cases.push_back(make_pair(strs, 2));
strs = {"", ""};
cases.push_back(make_pair(strs, -1));
strs = {"a", "", ""};
cases.push_back(make_pair(strs, 1));
strs = {"aa", "ab"};
cases.push_back(make_pair(strs, 2));
int num = 1;
for(auto & x : cases)
{
testcase(x.first, x.second, num);
num++;
}
/*
strs = {"a", "b", "c", "d", "e",
"ab", "ac", "ad", "ae", "bc", "bd", "be", "cd", "ce",
"ba", "ca", "da", "ea", "cb", "db", "eb", "dc", "ec",
"abc", "abd", "abe", "acd", "ace", "ade",
"acb", "adb", "aeb", "adc", "aec", "aed",
"bca", "bad", "bae", "cad", "cae", "dae",
"bac", "bda", "bea",
"cab", "dab", "eab",
"cba", "dba", "eba",
"abcd", "abce", "aced",
"abcde", "abcde"
};
testcase(strs, -1, 3);
*/
}
| 18.148148 | 64 | 0.481633 | sczzq |
6a8c962f0b62ca08cdf9a9ad1d16a79ab2939e1d | 2,497 | cpp | C++ | 2. Рекуррентные соотношения/59.2. Репортаж #2962/[OK]233028.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 19 | 2018-05-19T16:37:14.000Z | 2022-03-23T20:13:43.000Z | 2. Рекуррентные соотношения/59.2. Репортаж #2962/[OK]233028.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 6 | 2020-05-07T21:06:48.000Z | 2020-06-05T17:52:57.000Z | 2. Рекуррентные соотношения/59.2. Репортаж #2962/[OK]233028.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 <limits>
#include <algorithm>
#include <vector>
#include <iterator>
#include <ctime>
#include <cstdio>
using namespace std;
int minimum(int a, int b) {
return a > b ? b : a;
}
void findMax(vector<int> v, vector<int> &indexes, vector<int> &prev) {
int n = v.size();
vector<int> p;
vector<int> d;
vector<int> answer;
d.push_back(-2);
for (int i = 0; i <= n; ++i) {
p.push_back(0);
d.push_back(100001);
prev.push_back(-1);
indexes.push_back(1);
}
int buf;
for (int i = 0; i < n; i++) {
int j = int(upper_bound(d.begin(), d.end(), v[i]) - d.begin());
if (d[j - 1] == v[i]) {
indexes[i] = j - 1;
}
else {
indexes[i] = j;
}
if (d[j - 1] < v[i] && v[i] < d[j]) {
d[j] = v[i];
if (j == 1) {
prev[i] = -1;
p[j] = i;
}
else {
prev[i] = p[j - 1];
p[j] = i;
}
}
else if(d[j - 1] == v[i]){
if (j == 2) {
prev[i] = -1;
}
else {
prev[i] = p[j - 2];
}
}
}
}
int main()
{
FILE *fin = fopen("report.in","r");
FILE *fout = fopen("report.out", "w");
int n;
int k;
int max = -1;
int index;
fscanf(fin, "%d", &n);
vector<int> numbers;
vector<int> indexInc;
vector<int> prevInc;
vector<int> reversed;
vector<int> indexDec;
vector<int> prevDec;
vector<int> answer;
for (int i = 0; i < n; i++)
{
fscanf(fin, "%d", &k);
numbers.push_back(k);
}
copy(numbers.begin(), numbers.end(), back_inserter(reversed));
reverse(reversed.begin(), reversed.end());
findMax(numbers, indexInc, prevInc);
findMax(reversed, indexDec, prevDec);
indexInc.pop_back();
prevInc.pop_back();
indexDec.pop_back();
prevDec.pop_back();
reverse(indexDec.begin(), indexDec.end());
reverse(prevDec.begin(), prevDec.end());
for (int i = 0; i < n; i++)
{
if (minimum(indexInc[i] - 1, indexDec[i] - 1) > max) {
max = minimum(indexInc[i] - 1, indexDec[i] - 1);
index = i;
}
}
int j = index;
for (int i = 0; i < max; i++)
{
answer.push_back(prevInc[j] + 1);
j = prevInc[j];
}
reverse(answer.begin(), answer.end());
answer.push_back(index + 1);
j = index;
for (int i = 0; i < max; i++)
{
answer.push_back(n - prevDec[j]);
j = n - prevDec[j] - 1;
}
fprintf(fout, "%d\n", max);
for (int i = 0; i < answer.size(); i++)
{
fprintf(fout, "%d ", answer[i]);
}
fclose(fin);
fclose(fout);
system("pause");
return 0;
}
| 19.81746 | 71 | 0.526231 | godnoTA |
6a90bf634e7d7df76f2056a146085b940571809b | 1,075 | hpp | C++ | include/das.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | 5 | 2021-01-02T19:06:37.000Z | 2022-03-11T23:56:03.000Z | include/das.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | null | null | null | include/das.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | null | null | null | #pragma once
namespace nestris_x86 {
class Das {
public:
constexpr static int NTSC_FULL_CHARGE = 16;
constexpr static int NTSC_MIN_CHARGE = 10;
constexpr static int PAL_FULL_CHARGE = 12;
constexpr static int PAL_MIN_CHARGE = 8;
Das(const int das_full_charge, const int das_min_charge)
: das_full_charge_{das_full_charge}, das_min_charge_{das_min_charge} {}
inline void fullyChargeDas(int& das_counter) const { das_counter = das_full_charge_; }
inline void softResetDas(int& das_counter) const { das_counter = das_min_charge_; }
inline void hardResetDas(int& das_counter) const { das_counter = 0; }
inline bool dasFullyCharged(const int das_counter) const {
return das_counter >= das_full_charge_;
}
inline bool dasSoftlyCharged(const int das_counter) const {
return das_counter >= das_min_charge_;
}
inline int getFullDasChargeCount() const { return das_full_charge_; }
inline int getMinDasChargeCount() const { return das_min_charge_; }
private:
int das_full_charge_;
int das_min_charge_;
};
} // namespace nestris_x86
| 32.575758 | 88 | 0.763721 | rosskidson |
6a916445e96ae6271d525d688afe1d842b843903 | 893 | cpp | C++ | Sources/SolarTears/Core/Scene/SceneObjectLocation.cpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | 4 | 2021-06-30T16:00:20.000Z | 2021-10-13T06:17:56.000Z | Sources/SolarTears/Core/Scene/SceneObjectLocation.cpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | Sources/SolarTears/Core/Scene/SceneObjectLocation.cpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | #include "SceneObjectLocation.hpp"
#include "../Math/QuaternionUtils.hpp"
void SceneObjectLocation::SetPrincipalRight(DirectX::XMVECTOR right)
{
DirectX::XMVECTOR defaultRight = DirectX::XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultRight, right));
}
void SceneObjectLocation::SetPrincipalUp(DirectX::XMVECTOR newUpNrm)
{
DirectX::XMVECTOR defaultUp = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultUp, newUpNrm));
}
void SceneObjectLocation::SetPrincipalForward(DirectX::XMVECTOR newForwardNrm)
{
DirectX::XMVECTOR defaultForward = DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultForward, newForwardNrm));
} | 44.65 | 122 | 0.805151 | Sixshaman |
6a91d8d047e690a02d7a7a727a2b3bf6e57b9a49 | 6,581 | cpp | C++ | src/Win32ThreadSupport.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | src/Win32ThreadSupport.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | src/Win32ThreadSupport.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#ifndef DISABLE_MULTITHREADED
#include "StringConv.h"
#include "Win32ThreadSupport.h"
MultiThreaded::Win32ThreadConstructionInfo::~Win32ThreadConstructionInfo()
{
this->!Win32ThreadConstructionInfo();
}
MultiThreaded::Win32ThreadConstructionInfo::!Win32ThreadConstructionInfo()
{
if (_native) {
StringConv::FreeUnmanagedString(_uniqueName);
delete _native;
_native = NULL;
}
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc, int numThreads,
int threadStackSize)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc, numThreads, threadStackSize);
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc, int numThreads)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc, numThreads);
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc);
}
BulletSharp::Win32LSMemorySetupFunc MultiThreaded::Win32ThreadConstructionInfo::LSMemorySetupFunc::get()
{
if (_native->m_lsMemoryFunc == createCollisionLocalStoreMemory) {
return Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory;
} else if (_native->m_lsMemoryFunc == SolverlsMemoryFunc) {
return Win32LSMemorySetupFunc::SolverLSMemoryFunc;
}
throw gcnew NotImplementedException();
}
void MultiThreaded::Win32ThreadConstructionInfo::LSMemorySetupFunc::set(BulletSharp::Win32LSMemorySetupFunc value)
{
if (value == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
_native->m_lsMemoryFunc = createCollisionLocalStoreMemory;
} else if (value == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
_native->m_lsMemoryFunc = SolverlsMemoryFunc;
}
}
int MultiThreaded::Win32ThreadConstructionInfo::NumThreads::get()
{
return _native->m_numThreads;
}
void MultiThreaded::Win32ThreadConstructionInfo::NumThreads::set(int value)
{
_native->m_numThreads = value;
}
int MultiThreaded::Win32ThreadConstructionInfo::ThreadStackSize::get()
{
return _native->m_threadStackSize;
}
void MultiThreaded::Win32ThreadConstructionInfo::ThreadStackSize::set(int value)
{
_native->m_threadStackSize = value;
}
String^ MultiThreaded::Win32ThreadConstructionInfo::UniqueName::get()
{
return StringConv::UnmanagedToManaged(_native->m_uniqueName);
}
void MultiThreaded::Win32ThreadConstructionInfo::UniqueName::set(String^ value)
{
StringConv::FreeUnmanagedString(_uniqueName);
_uniqueName = StringConv::ManagedToUnmanaged(value);
}
BulletSharp::Win32ThreadFunc MultiThreaded::Win32ThreadConstructionInfo::UserThreadFunc::get()
{
if (_native->m_userThreadFunc == processCollisionTask) {
return Win32ThreadFunc::ProcessCollisionTask;
} else if (_native->m_userThreadFunc == SolverThreadFunc) {
return Win32ThreadFunc::SolverThreadFunc;
}
throw gcnew NotImplementedException();
}
void MultiThreaded::Win32ThreadConstructionInfo::UserThreadFunc::set(BulletSharp::Win32ThreadFunc value)
{
if (value == Win32ThreadFunc::ProcessCollisionTask) {
_native->m_userThreadFunc = processCollisionTask;
} else if (value == Win32ThreadFunc::SolverThreadFunc) {
_native->m_userThreadFunc = SolverThreadFunc;
}
}
#define Native static_cast<::Win32ThreadSupport*>(_native)
MultiThreaded::Win32ThreadSupport::Win32ThreadSupport(Win32ThreadConstructionInfo^ threadConstructionInfo)
: ThreadSupportInterface(new ::Win32ThreadSupport(*threadConstructionInfo->_native))
{
}
/*
bool MultiThreaded::Win32ThreadSupport::IsTaskCompleted(unsigned int^ puiArgument0, unsigned int^ puiArgument1,
int timeOutInMilliseconds)
{
return Native->isTaskCompleted(puiArgument0->_native, puiArgument1->_native, timeOutInMilliseconds);
}
*/
void MultiThreaded::Win32ThreadSupport::StartThreads(Win32ThreadConstructionInfo^ threadInfo)
{
Native->startThreads(*threadInfo->_native);
}
#endif
| 35.005319 | 115 | 0.787114 | yoshinoToylogic |
6a93553c23bd705a101085f190f72efa0c6db371 | 7,143 | cpp | C++ | TabGraph/src/Light/SkyLight.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-08-28T09:35:18.000Z | 2020-08-28T09:35:18.000Z | TabGraph/src/Light/SkyLight.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | null | null | null | TabGraph/src/Light/SkyLight.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-10-08T11:21:13.000Z | 2020-10-08T11:21:13.000Z | /*
* @Author: gpinchon
* @Date: 2021-03-12 16:08:58
* @Last Modified by: gpinchon
* @Last Modified time: 2021-05-18 18:26:25
*/
#include <Camera/Camera.hpp>
#include <Light/SkyLight.hpp>
#include <Renderer/Renderer.hpp>
#include <Renderer/Surface/GeometryRenderer.hpp>
#include <Scene/Scene.hpp>
#include <Shader/Program.hpp>
#include <SphericalHarmonics.hpp>
#include <Surface/CubeMesh.hpp>
#include <Surface/Geometry.hpp>
#include <Texture/Texture2D.hpp>
#include <Texture/TextureCubemap.hpp>
#if RENDERINGAPI == OpenGL
#include <Driver/OpenGL/Renderer/Light/SkyLightRenderer.hpp>
#endif
#define num_samples 16
#define num_samples_light 8
/// \private
struct ray_t {
glm::vec3 origin;
glm::vec3 direction;
};
/// \private
struct sphere_t {
glm::vec3 origin;
float radius;
};
bool isect_sphere(const ray_t ray, const sphere_t sphere, float& t0, float& t1)
{
glm::vec3 rc = sphere.origin - ray.origin;
float radius2 = sphere.radius * sphere.radius;
float tca = dot(rc, ray.direction);
float d2 = dot(rc, rc) - tca * tca;
if (d2 > radius2)
return false;
float thc = sqrt(radius2 - d2);
t0 = tca - thc;
t1 = tca + thc;
return true;
}
float rayleigh_phase_func(float mu)
{
return 3. * (1. + mu * mu)
/ //------------------------
(16. * M_PI);
}
float henyey_greenstein_phase_func(float mu)
{
const float g = 0.76;
return (1. - g * g)
/ //---------------------------------------------
((4. * M_PI) * pow(1. + g * g - 2. * g * mu, 1.5));
}
bool get_sun_light(const ray_t& ray, float& optical_depthR, float& optical_depthM, const SkyLight& sky)
{
float t0, t1;
const sphere_t atmosphere = sphere_t {
glm::vec3(0, 0, 0), sky.GetAtmosphereRadius()
};
isect_sphere(ray, atmosphere, t0, t1);
float march_pos = 0.;
float march_step = t1 / float(num_samples_light);
for (int i = 0; i < num_samples_light; i++) {
glm::vec3 s = ray.origin + ray.direction * float(march_pos + 0.5 * march_step);
float height = length(s) - sky.GetPlanetRadius();
if (height < 0.)
return false;
optical_depthR += exp(-height / sky.GetHRayleigh()) * march_step;
optical_depthM += exp(-height / sky.GetHMie()) * march_step;
march_pos += march_step;
}
return true;
}
static inline glm::vec3 GetIncidentLight(ray_t ray, const SkyLight& sky)
{
const sphere_t atmosphere = sphere_t {
glm::vec3(0, 0, 0), sky.GetAtmosphereRadius()
};
// "pierce" the atmosphere with the viewing ray
float t0, t1;
if (!isect_sphere(
ray, atmosphere, t0, t1)) {
return glm::vec3(0);
}
float march_step = t1 / float(num_samples);
// cosine of angle between view and light directions
float mu = glm::dot(ray.direction, sky.GetSunDirection());
// Rayleigh and Mie phase functions
// A black box indicating how light is interacting with the material
// Similar to BRDF except
// * it usually considers a single angle
// (the phase angle between 2 directions)
// * integrates to 1 over the entire sphere of directions
float phaseR = rayleigh_phase_func(mu);
float phaseM = henyey_greenstein_phase_func(mu);
// optical depth (or "average density")
// represents the accumulated extinction coefficients
// along the path, multiplied by the length of that path
float optical_depthR = 0.;
float optical_depthM = 0.;
glm::vec3 sumR = glm::vec3(0);
glm::vec3 sumM = glm::vec3(0);
float march_pos = 0.;
for (int i = 0; i < num_samples; i++) {
glm::vec3 s = ray.origin + ray.direction * float(march_pos + 0.5 * march_step);
float height = glm::length(s) - sky.GetPlanetRadius();
// integrate the height scale
float hr = exp(-height / sky.GetHRayleigh()) * march_step;
float hm = exp(-height / sky.GetHMie()) * march_step;
optical_depthR += hr;
optical_depthM += hm;
// gather the sunlight
ray_t light_ray {
s,
sky.GetSunDirection()
};
float optical_depth_lightR = 0.;
float optical_depth_lightM = 0.;
bool overground = get_sun_light(
light_ray,
optical_depth_lightR,
optical_depth_lightM,
sky);
if (overground) {
glm::vec3 tau = sky.GetBetaRayleigh() * (optical_depthR + optical_depth_lightR) + sky.GetBetaMie() * 1.1f * (optical_depthM + optical_depth_lightM);
glm::vec3 attenuation = exp(-tau);
sumR += hr * attenuation;
sumM += hm * attenuation;
}
march_pos += march_step;
}
return sky.GetSunPower() * (sumR * phaseR * sky.GetBetaRayleigh() + sumM * phaseM * sky.GetBetaMie());
}
SkyLight::SkyLight()
: DirectionalLight()
{
}
glm::vec3 SkyLight::GetSunDirection() const
{
return GetDirection();
}
void SkyLight::SetSunDirection(const glm::vec3& sunDir)
{
if (sunDir != GetSunDirection())
GetRenderer().FlagDirty();
SetDirection(sunDir);
}
float SkyLight::GetSunPower() const
{
return _sunPower;
}
void SkyLight::SetSunPower(const float sunPower)
{
if (sunPower != _sunPower)
GetRenderer().FlagDirty();
_sunPower = sunPower;
}
float SkyLight::GetPlanetRadius() const
{
return _planetRadius;
}
void SkyLight::SetPlanetRadius(float planetRadius)
{
if (planetRadius != _planetRadius)
GetRenderer().FlagDirty();
_planetRadius = planetRadius;
}
float SkyLight::GetAtmosphereRadius() const
{
return _atmosphereRadius;
}
void SkyLight::SetAtmosphereRadius(float atmosphereRadius)
{
if (atmosphereRadius != _atmosphereRadius)
GetRenderer().FlagDirty();
_atmosphereRadius = atmosphereRadius;
}
float SkyLight::GetHRayleigh() const
{
return _hRayleigh;
}
void SkyLight::SetHRayleigh(float hRayleigh)
{
if (hRayleigh != _hRayleigh)
GetRenderer().FlagDirty();
_hRayleigh = hRayleigh;
}
float SkyLight::GetHMie() const
{
return _hMie;
}
void SkyLight::SetHMie(float hMie)
{
if (hMie != _hMie)
GetRenderer().FlagDirty();
_hMie = hMie;
}
glm::vec3 SkyLight::GetBetaRayleigh() const
{
return _betaRayleigh;
}
void SkyLight::SetBetaRayleigh(glm::vec3 betaRayleigh)
{
if (betaRayleigh != _betaRayleigh)
GetRenderer().FlagDirty();
_betaRayleigh = betaRayleigh;
}
glm::vec3 SkyLight::GetBetaMie() const
{
return _betaMie;
}
void SkyLight::SetBetaMie(glm::vec3 betaMie)
{
if (betaMie != _betaMie)
GetRenderer().FlagDirty();
_betaMie = betaMie;
}
glm::vec3 SkyLight::GetIncidentLight(glm::vec3 direction) const
{
return ::GetIncidentLight({ glm::vec3(0, GetPlanetRadius() + 1, 0),
direction },
*this);
}
| 25.974545 | 161 | 0.607168 | Gpinchon |
6a9a00f3cc4bf4af7d1df8d2312eb795f3482e3d | 7,404 | cpp | C++ | search/result.cpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | search/result.cpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | search/result.cpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | #include "search/result.hpp"
#include "search/common.hpp"
#include "search/geometry_utils.hpp"
namespace search
{
Result::Result(FeatureID const & id, m2::PointD const & pt, string const & str,
string const & address, string const & type, uint32_t featureType,
Metadata const & meta)
: m_id(id)
, m_center(pt)
, m_str(str.empty() ? type : str) //!< Features with empty names can be found after suggestion.
, m_address(address)
, m_type(type)
, m_featureType(featureType)
, m_metadata(meta)
{
}
Result::Result(m2::PointD const & pt, string const & latlon, string const & address)
: m_center(pt), m_str(latlon), m_address(address)
{
}
Result::Result(string const & str, string const & suggest)
: m_str(str), m_suggestionStr(suggest)
{
}
Result::Result(Result const & res, string const & suggest)
: m_id(res.m_id)
, m_center(res.m_center)
, m_str(res.m_str)
, m_address(res.m_address)
, m_type(res.m_type)
, m_featureType(res.m_featureType)
, m_suggestionStr(suggest)
, m_hightlightRanges(res.m_hightlightRanges)
{
}
Result::ResultType Result::GetResultType() const
{
bool const idValid = m_id.IsValid();
if (!m_suggestionStr.empty())
return (idValid ? RESULT_SUGGEST_FROM_FEATURE : RESULT_SUGGEST_PURE);
if (idValid)
return RESULT_FEATURE;
else
return RESULT_LATLON;
}
bool Result::IsSuggest() const
{
return !m_suggestionStr.empty();
}
bool Result::HasPoint() const
{
return (GetResultType() != RESULT_SUGGEST_PURE);
}
FeatureID const & Result::GetFeatureID() const
{
#if defined(DEBUG)
auto const type = GetResultType();
ASSERT(type == RESULT_FEATURE, (type));
#endif
return m_id;
}
m2::PointD Result::GetFeatureCenter() const
{
ASSERT(HasPoint(), ());
return m_center;
}
char const * Result::GetSuggestionString() const
{
ASSERT(IsSuggest(), ());
return m_suggestionStr.c_str();
}
bool Result::IsEqualSuggest(Result const & r) const
{
return (m_suggestionStr == r.m_suggestionStr);
}
bool Result::IsEqualFeature(Result const & r) const
{
ResultType const type = GetResultType();
if (type != r.GetResultType())
return false;
ASSERT_EQUAL(type, Result::RESULT_FEATURE, ());
ASSERT(m_id.IsValid() && r.m_id.IsValid(), ());
if (m_id == r.m_id)
return true;
// This function is used to filter duplicate results in cases:
// - emitted World.mwm and Country.mwm
// - after additional search in all mwm
// so it's suitable here to test for 500m
return (m_str == r.m_str && m_address == r.m_address &&
m_featureType == r.m_featureType &&
PointDistance(m_center, r.m_center) < 500.0);
}
void Result::AddHighlightRange(pair<uint16_t, uint16_t> const & range)
{
m_hightlightRanges.push_back(range);
}
pair<uint16_t, uint16_t> const & Result::GetHighlightRange(size_t idx) const
{
ASSERT(idx < m_hightlightRanges.size(), ());
return m_hightlightRanges[idx];
}
void Result::AppendCity(string const & name)
{
// Prepend only if city is absent in region (mwm) name.
if (m_address.find(name) == string::npos)
m_address = name + ", " + m_address;
}
string Result::ToStringForStats() const
{
string s;
s.append(GetString());
s.append("|");
s.append(GetFeatureType());
s.append("|");
s.append(IsSuggest() ? "1" : "0");
return s;
}
bool Results::AddResult(Result && res)
{
// Find first feature result.
auto it = find_if(m_vec.begin(), m_vec.end(), [](Result const & r)
{
switch (r.GetResultType())
{
case Result::RESULT_FEATURE:
return true;
default:
return false;
}
});
if (res.IsSuggest())
{
if (distance(m_vec.begin(), it) >= MAX_SUGGESTS_COUNT)
return false;
for (auto i = m_vec.begin(); i != it; ++i)
if (res.IsEqualSuggest(*i))
return false;
for (auto i = it; i != m_vec.end(); ++i)
{
auto & r = *i;
auto const oldPos = r.GetPositionInResults();
r.SetPositionInResults(oldPos + 1);
}
res.SetPositionInResults(distance(m_vec.begin(), it));
m_vec.insert(it, move(res));
}
else
{
for (; it != m_vec.end(); ++it)
if (res.IsEqualFeature(*it))
return false;
res.SetPositionInResults(m_vec.size());
m_vec.push_back(move(res));
}
return true;
}
size_t Results::GetSuggestsCount() const
{
size_t res = 0;
for (size_t i = 0; i < GetCount(); i++)
{
if (m_vec[i].IsSuggest())
++res;
else
{
// Suggests always go first, so we can exit here.
break;
}
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////
// AddressInfo implementation
////////////////////////////////////////////////////////////////////////////////////
bool AddressInfo::IsEmptyName() const
{
return m_name.empty() && m_house.empty();
}
string AddressInfo::GetPinName() const
{
if (IsEmptyName() && !m_types.empty())
return m_types[0];
else
return m_name.empty() ? m_house : m_name;
}
string AddressInfo::GetPinType() const
{
return GetBestType();
}
string AddressInfo::FormatPinText() const
{
// select name or house if name is empty
string const & ret = (m_name.empty() ? m_house : m_name);
string const type = GetBestType();
if (type.empty())
return ret;
return (ret.empty() ? type : (ret + " (" + type + ')'));
}
string AddressInfo::FormatHouseAndStreet(AddressType type /* = DEFAULT */) const
{
// Check whether we can format address according to the query type and actual address distance.
/// @todo We can add "Near" prefix here in future according to the distance.
if (m_distanceMeters > 0.0)
{
if (type == SEARCH_RESULT && m_distanceMeters > 50.0)
return string();
if (m_distanceMeters > 200.0)
return string();
}
string result = m_street;
if (!m_house.empty())
{
if (!result.empty())
result += ", ";
result += m_house;
}
return result;
}
string AddressInfo::FormatAddress(AddressType type /* = DEFAULT */) const
{
string result = FormatHouseAndStreet(type);
if (!m_city.empty())
{
if (!result.empty())
result += ", ";
result += m_city;
}
if (!m_country.empty())
{
if (!result.empty())
result += ", ";
result += m_country;
}
return result;
}
string AddressInfo::FormatNameAndAddress(AddressType type /* = DEFAULT */) const
{
string const addr = FormatAddress(type);
return (m_name.empty() ? addr : m_name + ", " + addr);
}
string AddressInfo::FormatTypes() const
{
string result;
for (size_t i = 0; i < m_types.size(); ++i)
{
ASSERT ( !m_types.empty(), () );
if (!result.empty())
result += ' ';
result += m_types[i];
}
return result;
}
string AddressInfo::GetBestType() const
{
if (m_types.empty())
return string();
/// @todo Probably, we should skip some "common" types here like in TypesHolder::SortBySpec.
ASSERT(!m_types[0].empty(), ());
return m_types[0];
}
void AddressInfo::Clear()
{
m_country.clear();
m_city.clear();
m_street.clear();
m_house.clear();
m_name.clear();
m_types.clear();
}
string DebugPrint(AddressInfo const & info)
{
return info.FormatNameAndAddress();
}
string DebugPrint(Result const & result)
{
return "Result { Name: " + result.GetString() + "; Type: " + result.GetFeatureType() +
"; Info: " + DebugPrint(result.GetRankingInfo()) + " }";
}
} // namespace search
| 22.504559 | 98 | 0.63101 | Dushistov |
6a9b187a3af75b5366f46adc54f060be5e1e11f9 | 122,528 | cpp | C++ | src/libbrep/boolean.cpp | dservin/brlcad | 34b72d3efd24ac2c84abbccf9452323231751cd1 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/libbrep/boolean.cpp | dservin/brlcad | 34b72d3efd24ac2c84abbccf9452323231751cd1 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/libbrep/boolean.cpp | dservin/brlcad | 34b72d3efd24ac2c84abbccf9452323231751cd1 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* B O O L E A N . C P P
* BRL-CAD
*
* Copyright (c) 2013-2022 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file boolean.cpp
*
* Evaluate NURBS booleans (union, intersection and difference).
*
* Additional documentation can be found in the "NURBS Boolean Evaluation
* Development Guide" docbook article (bool_eval_development.html).
*/
#include "common.h"
#include <assert.h>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
#include "bio.h"
#include "vmath.h"
#include "bu/log.h"
#include "brep/defines.h"
#include "brep/boolean.h"
#include "brep/intersect.h"
#include "brep/pullback.h"
#include "brep/ray.h"
#include "brep/util.h"
#include "debug_plot.h"
#include "brep_except.h"
#include "brep_defines.h"
DebugPlot *dplot = NULL;
// Whether to output the debug messages about b-rep booleans.
#define DEBUG_BREP_BOOLEAN 0
struct IntersectPoint {
ON_3dPoint m_pt; // 3D intersection point
double m_seg_t; // param on the loop curve
int m_loop_seg; // which curve of the loop
int m_ssx_curve; // which intersection curve
int m_curve_pos; // rank on the chain
double m_curve_t; // param on the SSI curve
enum {
UNSET,
IN_HIT,
OUT_HIT,
TANGENT
} m_dir; // dir is going inside/outside
int m_split_li; // between clx_points[m_split_li] and
// clx_points[m_split_li+1]
// after the outerloop is split
};
// A structure to represent the curve segments generated from surface-surface
// intersections, including some information needed by the connectivity graph
struct SSICurve {
ON_Curve *m_curve;
SSICurve()
{
m_curve = NULL;
}
SSICurve(ON_Curve *curve)
{
m_curve = curve;
}
SSICurve *Duplicate() const
{
SSICurve *out = new SSICurve();
if (out != NULL) {
*out = *this;
out->m_curve = m_curve->Duplicate();
}
return out;
}
};
void
append_to_polycurve(ON_Curve *curve, ON_PolyCurve &polycurve);
// We link the SSICurves that share an endpoint, and form this new structure,
// which has many similar behaviors as ON_Curve, e.g. PointAt(), Reverse().
struct LinkedCurve {
private:
ON_Curve *m_curve; // an explicit storage of the whole curve
public:
// The curves contained in this LinkedCurve, including
// the information needed by the connectivity graph
ON_SimpleArray<SSICurve> m_ssi_curves;
// Default constructor
LinkedCurve()
{
m_curve = NULL;
}
void Empty()
{
m_ssi_curves.Empty();
delete m_curve;
m_curve = NULL;
}
~LinkedCurve()
{
Empty();
}
LinkedCurve &operator= (const LinkedCurve &_lc)
{
Empty();
m_curve = _lc.m_curve ? _lc.m_curve->Duplicate() : NULL;
m_ssi_curves = _lc.m_ssi_curves;
return *this;
}
ON_3dPoint PointAtStart() const
{
if (m_ssi_curves.Count()) {
return m_ssi_curves[0].m_curve->PointAtStart();
} else {
return ON_3dPoint::UnsetPoint;
}
}
ON_3dPoint PointAtEnd() const
{
if (m_ssi_curves.Count()) {
return m_ssi_curves.Last()->m_curve->PointAtEnd();
} else {
return ON_3dPoint::UnsetPoint;
}
}
bool IsClosed() const
{
if (m_ssi_curves.Count() == 0) {
return false;
}
return PointAtStart().DistanceTo(PointAtEnd()) < ON_ZERO_TOLERANCE;
}
bool IsValid() const
{
// Check whether the curve has "gaps".
for (int i = 1; i < m_ssi_curves.Count(); i++) {
if (m_ssi_curves[i].m_curve->PointAtStart().DistanceTo(m_ssi_curves[i - 1].m_curve->PointAtEnd()) >= ON_ZERO_TOLERANCE) {
bu_log("The LinkedCurve is not valid.\n");
return false;
}
}
return true;
}
bool Reverse()
{
ON_SimpleArray<SSICurve> new_array;
for (int i = m_ssi_curves.Count() - 1; i >= 0; i--) {
if (!m_ssi_curves[i].m_curve->Reverse()) {
return false;
}
new_array.Append(m_ssi_curves[i]);
}
m_ssi_curves = new_array;
return true;
}
void Append(const LinkedCurve &lc)
{
m_ssi_curves.Append(lc.m_ssi_curves.Count(), lc.m_ssi_curves.Array());
}
void Append(const SSICurve &sc)
{
m_ssi_curves.Append(sc);
}
void AppendCurvesToArray(ON_SimpleArray<ON_Curve *> &arr) const
{
for (int i = 0; i < m_ssi_curves.Count(); i++) {
arr.Append(m_ssi_curves[i].m_curve->Duplicate());
}
}
const ON_Curve *Curve()
{
if (m_curve != NULL) {
return m_curve;
}
if (m_ssi_curves.Count() == 0 || !IsValid()) {
return NULL;
}
ON_PolyCurve *polycurve = new ON_PolyCurve;
for (int i = 0; i < m_ssi_curves.Count(); i++) {
append_to_polycurve(m_ssi_curves[i].m_curve->Duplicate(), *polycurve);
}
m_curve = polycurve;
return m_curve;
}
const ON_3dPoint PointAt(double t)
{
const ON_Curve *c = Curve();
if (c == NULL) {
return ON_3dPoint::UnsetPoint;
}
return c->PointAt(t);
}
const ON_Interval Domain()
{
const ON_Curve *c = Curve();
if (c == NULL) {
return ON_Interval::EmptyInterval;
}
return c->Domain();
}
ON_Curve *SubCurve(double t1, double t2)
{
const ON_Curve *c = Curve();
if (c == NULL) {
return NULL;
}
try {
return sub_curve(c, t1, t2);
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
return NULL;
}
}
};
struct TrimmedFace {
// curve segments in the face's outer loop
ON_SimpleArray<ON_Curve *> m_outerloop;
// several inner loops, each has some curves
std::vector<ON_SimpleArray<ON_Curve *> > m_innerloop;
const ON_BrepFace *m_face;
enum {
UNKNOWN = -1,
NOT_BELONG = 0,
BELONG = 1
} m_belong_to_final;
bool m_rev;
// Default constructor
TrimmedFace()
{
m_face = NULL;
m_belong_to_final = UNKNOWN;
m_rev = false;
}
// Destructor
~TrimmedFace()
{
// Delete the curve segments if it's not belong to the result.
if (m_belong_to_final != BELONG) {
for (int i = 0; i < m_outerloop.Count(); i++) {
if (m_outerloop[i]) {
delete m_outerloop[i];
m_outerloop[i] = NULL;
}
}
for (unsigned int i = 0; i < m_innerloop.size(); i++) {
for (int j = 0; j < m_innerloop[i].Count(); j++) {
if (m_innerloop[i][j]) {
delete m_innerloop[i][j];
m_innerloop[i][j] = NULL;
}
}
}
}
}
TrimmedFace *Duplicate() const
{
TrimmedFace *out = new TrimmedFace();
out->m_face = m_face;
for (int i = 0; i < m_outerloop.Count(); i++) {
if (m_outerloop[i]) {
out->m_outerloop.Append(m_outerloop[i]->Duplicate());
}
}
out->m_innerloop = m_innerloop;
for (unsigned int i = 0; i < m_innerloop.size(); i++) {
for (int j = 0; j < m_innerloop[i].Count(); j++) {
if (m_innerloop[i][j]) {
out->m_innerloop[i][j] = m_innerloop[i][j]->Duplicate();
}
}
}
return out;
}
};
HIDDEN int
loop_t_compare(const IntersectPoint *p1, const IntersectPoint *p2)
{
// Use for sorting an array. Use strict FP comparison.
if (p1->m_loop_seg != p2->m_loop_seg) {
return p1->m_loop_seg - p2->m_loop_seg;
}
return p1->m_seg_t > p2->m_seg_t ? 1 : (p1->m_seg_t < p2->m_seg_t ? -1 : 0);
}
HIDDEN int
curve_t_compare(const IntersectPoint *p1, const IntersectPoint *p2)
{
// Use for sorting an array. Use strict FP comparison.
return p1->m_curve_t > p2->m_curve_t ? 1 : (p1->m_curve_t < p2->m_curve_t ? -1 : 0);
}
void
append_to_polycurve(ON_Curve *curve, ON_PolyCurve &polycurve)
{
// use this function rather than ON_PolyCurve::Append() to avoid
// getting nested polycurves, which makes ON_Brep::IsValid() to fail.
ON_PolyCurve *nested = ON_PolyCurve::Cast(curve);
if (nested != NULL) {
// The input curve is a polycurve
const ON_CurveArray &segments = nested->SegmentCurves();
for (int i = 0; i < segments.Count(); i++) {
append_to_polycurve(segments[i]->Duplicate(), polycurve);
}
delete nested;
} else {
polycurve.Append(curve);
}
}
HIDDEN bool
is_loop_valid(const ON_SimpleArray<ON_Curve *> &loop, double tolerance, ON_PolyCurve *polycurve = NULL)
{
bool delete_curve = false;
bool ret = true;
if (loop.Count() == 0) {
bu_log("The input loop is empty.\n");
ret = false;
}
// First, use a ON_PolyCurve to represent the loop.
if (ret) {
if (polycurve == NULL) {
polycurve = new ON_PolyCurve;
if (polycurve) {
delete_curve = true;
} else {
ret = false;
}
}
}
// Check the loop is continuous and closed or not.
if (ret) {
if (loop[0] != NULL) {
append_to_polycurve(loop[0]->Duplicate(), *polycurve);
}
for (int i = 1 ; i < loop.Count(); i++) {
if (loop[i] && loop[i - 1] && loop[i]->PointAtStart().DistanceTo(loop[i - 1]->PointAtEnd()) < ON_ZERO_TOLERANCE) {
append_to_polycurve(loop[i]->Duplicate(), *polycurve);
} else {
bu_log("The input loop is not continuous.\n");
ret = false;
}
}
}
if (ret && (polycurve->PointAtStart().DistanceTo(polycurve->PointAtEnd()) >= ON_ZERO_TOLERANCE ||
!polycurve->IsClosed()))
{
bu_log("The input loop is not closed.\n");
ret = false;
}
if (ret) {
// Check whether the loop is degenerated.
ON_BoundingBox bbox = polycurve->BoundingBox();
ret = !ON_NearZero(bbox.Diagonal().Length(), tolerance)
&& !polycurve->IsLinear(tolerance);
}
if (delete_curve) {
delete polycurve;
}
return ret;
}
enum {
OUTSIDE_OR_ON_LOOP,
INSIDE_OR_ON_LOOP
};
// Returns whether the point is inside/on or outside/on the loop
// boundary.
//
// Throws InvalidGeometry if loop is invalid.
//
// If you want to know whether this point is on the loop boundary,
// call is_point_on_loop().
HIDDEN int
point_loop_location(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
ON_PolyCurve polycurve;
if (!is_loop_valid(loop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("point_loop_location() given invalid loop\n");
}
ON_BoundingBox bbox = polycurve.BoundingBox();
if (!bbox.IsPointIn(pt)) {
return OUTSIDE_OR_ON_LOOP;
}
// The input point is inside the loop's bounding box.
// out must be outside the closed region (and the bbox).
ON_2dPoint out = pt + ON_2dVector(bbox.Diagonal());
ON_LineCurve linecurve(pt, out);
ON_3dVector line_dir = linecurve.m_line.Direction();
ON_SimpleArray<ON_X_EVENT> tmp_x;
for (int i = 0; i < loop.Count(); ++i) {
ON_SimpleArray<ON_X_EVENT> li_x;
ON_Intersect(&linecurve, loop[i], li_x, INTERSECTION_TOL);
for (int j = 0; j < li_x.Count(); ++j) {
// ignore tangent and overlap intersections
if (li_x[j].m_type != ON_X_EVENT::ccx_overlap &&
!loop[i]->TangentAt(li_x[j].m_b[0]).IsParallelTo(line_dir, ANGLE_TOL))
{
tmp_x.Append(li_x[j]);
}
}
}
ON_SimpleArray<ON_X_EVENT> x_event;
for (int i = 0; i < tmp_x.Count(); i++) {
int j;
for (j = 0; j < x_event.Count(); j++) {
if (tmp_x[i].m_A[0].DistanceTo(x_event[j].m_A[0]) < INTERSECTION_TOL &&
tmp_x[i].m_A[1].DistanceTo(x_event[j].m_A[1]) < INTERSECTION_TOL &&
tmp_x[i].m_B[0].DistanceTo(x_event[j].m_B[0]) < INTERSECTION_TOL &&
tmp_x[i].m_B[1].DistanceTo(x_event[j].m_B[1]) < INTERSECTION_TOL)
{
break;
}
}
if (j == x_event.Count()) {
x_event.Append(tmp_x[i]);
}
}
return (x_event.Count() % 2) ? INSIDE_OR_ON_LOOP : OUTSIDE_OR_ON_LOOP;
}
// Returns whether or not point is on the loop boundary.
// Throws InvalidGeometry if loop is invalid.
HIDDEN bool
is_point_on_loop(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
ON_PolyCurve polycurve;
if (!is_loop_valid(loop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("is_point_on_loop() given invalid loop\n");
}
ON_3dPoint pt3d(pt);
for (int i = 0; i < loop.Count(); ++i) {
ON_ClassArray<ON_PX_EVENT> px_event;
if (ON_Intersect(pt3d, *loop[i], px_event, INTERSECTION_TOL)) {
return true;
}
}
return false;
}
HIDDEN bool
is_point_inside_loop(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
return (point_loop_location(pt, loop) == INSIDE_OR_ON_LOOP) && !is_point_on_loop(pt, loop);
}
HIDDEN bool
is_point_outside_loop(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
return (point_loop_location(pt, loop) == OUTSIDE_OR_ON_LOOP) && !is_point_on_loop(pt, loop);
}
HIDDEN ON_SimpleArray<ON_Interval>
get_curve_intervals_inside_or_on_face(
ON_Curve *curve2D,
const ON_ClassArray<ON_SimpleArray<ON_Curve *> > &face_loops,
double isect_tol)
{
// get curve-loop intersections
ON_SimpleArray<double> isect_curve_t;
ON_SimpleArray<ON_X_EVENT> ccx_events;
for (int i = 0; i < face_loops.Count(); ++i) {
for (int j = 0; j < face_loops[i].Count(); ++j) {
ON_Intersect(curve2D, face_loops[i][j], ccx_events, isect_tol);
}
}
// get a sorted list of just the parameters on the first curve
// where it intersects the outerloop
for (int i = 0; i < ccx_events.Count(); i++) {
isect_curve_t.Append(ccx_events[i].m_a[0]);
if (ccx_events[i].m_type == ON_X_EVENT::ccx_overlap) {
isect_curve_t.Append(ccx_events[i].m_a[1]);
}
}
isect_curve_t.QuickSort(ON_CompareIncreasing);
// insert start and end parameters so every part of the curve is tested
isect_curve_t.Insert(0, curve2D->Domain().Min());
isect_curve_t.Append(curve2D->Domain().Max());
// if the midpoint of an interval is inside/on the face, keep the
// entire interval
ON_SimpleArray<ON_Interval> included_intervals;
for (int i = 0; i < isect_curve_t.Count() - 1; i++) {
ON_Interval interval(isect_curve_t[i], isect_curve_t[i + 1]);
if (ON_NearZero(interval.Length(), isect_tol)) {
continue;
}
ON_2dPoint pt = curve2D->PointAt(interval.Mid());
bool point_included = false;
try {
// inside/on outerloop
if (!is_point_outside_loop(pt, face_loops[0])) {
// outside/on innerloops
point_included = true;
for (int j = 1; j < face_loops.Count(); ++j) {
if (is_point_inside_loop(pt, face_loops[j])) {
point_included = false;
break;
}
}
}
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
}
if (point_included) {
included_intervals.Append(interval);
}
}
// merge continuous intervals
ON_SimpleArray<ON_Interval> final_intervals;
for (int j, i = 0; i < included_intervals.Count(); i = j) {
ON_Interval merged_interval = included_intervals[i];
for (j = i + 1; j < included_intervals.Count(); ++j) {
ON_Interval &next = included_intervals[j];
if (ON_NearZero(next.Min() - merged_interval.Max(), isect_tol)) {
ON_Interval new_interval = merged_interval;
if (new_interval.Union(next)) {
merged_interval = new_interval;
} else {
break;
}
} else {
break;
}
}
final_intervals.Append(merged_interval);
}
return final_intervals;
}
struct IntervalPoints {
ON_3dPoint min;
ON_3dPoint mid;
ON_3dPoint max;
};
class IntervalParams {
public:
double min;
double mid;
double max;
void
MakeIncreasing(void)
{
if (min > mid) {
std::swap(min, mid);
}
if (mid > max) {
std::swap(mid, max);
if (min > mid) {
std::swap(min, mid);
}
}
}
};
// given parameters in a curve interval, create new interval
// parameters that reflect the the non-degenerate (different
// dimensioned) curve interval used to generate the curve parameters
HIDDEN IntervalParams
curve_interval_from_params(
IntervalParams interval_t,
const ON_Curve *curve)
{
if (!curve->IsClosed()) {
return interval_t;
}
if (interval_t.min > interval_t.max) {
std::swap(interval_t.min, interval_t.max);
}
double min_t = interval_t.min;
double max_t = interval_t.max;
ON_Interval cdom = curve->Domain();
if (!(min_t < max_t || min_t > max_t)) {
// if endpoints are both at closed curve joint, put them at
// either end of the curve domain
if (ON_NearZero(cdom.Min() - min_t, ON_ZERO_TOLERANCE)) {
interval_t.max = cdom.Max();
} else if (ON_NearZero(cdom.Max() - min_t, ON_ZERO_TOLERANCE)) {
interval_t.min = cdom.Min();
}
} else {
// if interval doesn't include midpt, assume the point nearest
// the seam needs to be on the opposite side of the domain
ON_Interval curr(min_t, max_t);
if (!curr.Includes(interval_t.mid)) {
if (fabs(cdom.Min() - min_t) > fabs(cdom.Max() - max_t)) {
interval_t.max = cdom.Min();
} else {
interval_t.min = cdom.Max();
}
}
}
interval_t.MakeIncreasing();
return interval_t;
}
enum seam_location {SEAM_NONE, SEAM_ALONG_V, SEAM_ALONG_U, SEAM_ALONG_UV};
// given interval points in surface uv space, create new interval
// points that reflect the non-degenerate curve parameter interval
// used to generate the input points
HIDDEN IntervalPoints
uv_interval_from_points(
IntervalPoints interval_pts,
const ON_Surface *surf)
{
ON_3dPoint &min_uv = interval_pts.min;
ON_3dPoint &max_uv = interval_pts.max;
ON_Interval udom = surf->Domain(0);
ON_Interval vdom = surf->Domain(1);
int seam_min = IsAtSeam(surf, min_uv, ON_ZERO_TOLERANCE);
int seam_max = IsAtSeam(surf, max_uv, ON_ZERO_TOLERANCE);
if ((seam_min && seam_max) && (min_uv == max_uv)) {
// if uv endpoints are identical and on a seam
// they need to be on opposite sides of the domain
if (ON_NearZero(udom.Min() - min_uv[0], ON_ZERO_TOLERANCE) ||
ON_NearZero(udom.Max() - min_uv[0], ON_ZERO_TOLERANCE))
{
// point on west/east edge becomes one point on west
// edge, one point on east edge
min_uv[0] = udom.Min();
max_uv[0] = udom.Max();
} else if (ON_NearZero(vdom.Min() - min_uv[1], ON_ZERO_TOLERANCE) ||
ON_NearZero(vdom.Max() - min_uv[1], ON_ZERO_TOLERANCE))
{
// point on south/north edge becomes one point on
// south edge, one point on north edge
min_uv[1] = vdom.Min();
max_uv[1] = vdom.Max();
}
} else if (!seam_min != !seam_max) { // XOR
// if just one point is on a seam, make sure it's on the
// correct side of the domain
// get interval midpoint in uv space
ON_ClassArray<ON_PX_EVENT> events;
ON_3dPoint midpt = surf->PointAt(interval_pts.mid.x,
interval_pts.mid.y);
ON_Intersect(midpt, *surf, events, INTERSECTION_TOL);
if (events.Count() == 1) {
// Check that the non-seam parameter of the
// midpoint is between the non-seam parameters of
// the interval uv on the seam and the other
// interval uv. If the midpoint non-seam parameter
// is outside the interval we'll move the seam_uv
// to the other side of the domain.
//
// For example, if the surface has a seam at the
// west/east edge and we have seam_uv (0.0, .1)
// and other_uv (.5, .6) we'll check that the
// interval midpoint uv has a u in [0.0, .5].
//
// A midpoint of (.25, .25) would be okay. A
// midpoint of (.75, .25) would necessitate us
// moving the seam_uv from the west edge to the
// east edge, e.g (1.0, .1).
int seam = seam_min ? seam_min : seam_max;
ON_3dPoint &seam_uv = seam_min ? min_uv : max_uv;
ON_3dPoint other_uv = seam_min ? max_uv : min_uv;
double *seam_t = &seam_uv[1];
double seam_opp_t = vdom.Max() - seam_uv[1];
double other_t = other_uv[1];
double midpt_t = events[0].m_b[1];
if (seam != SEAM_ALONG_U) {
seam_t = &seam_uv[0];
seam_opp_t = udom.Max() - seam_uv[0];
other_t = other_uv[0];
midpt_t = events[0].m_b[0];
}
ON_Interval curr(*seam_t, other_t);
if (!curr.Includes(midpt_t)) {
// need to flip the seam point to the other
// side of the domain
*seam_t = seam_opp_t;
}
}
}
return interval_pts;
}
HIDDEN IntervalPoints
interval_2d_to_uv(
const ON_Interval &interval_2d,
const ON_Curve *curve2d,
const ON_Surface *surf)
{
// initialize endpoints from evaluated surface uv points
IntervalPoints pts;
pts.min = curve2d->PointAt(interval_2d.Min());
pts.mid = curve2d->PointAt(interval_2d.Mid());
pts.max = curve2d->PointAt(interval_2d.Max());
return uv_interval_from_points(pts, surf);
}
HIDDEN std::pair<IntervalPoints, IntervalPoints>
interval_2d_to_2uv(
const ON_Interval &interval_2d,
const ON_Curve *curve2d,
const ON_Surface *surf,
double split_t)
{
std::pair<IntervalPoints, IntervalPoints> out;
ON_Interval left(interval_2d.Min(), split_t);
ON_Interval right(split_t, interval_2d.Max());
out.first = interval_2d_to_uv(left, curve2d, surf);
out.second = interval_2d_to_uv(right, curve2d, surf);
return out;
}
HIDDEN IntervalPoints
points_uv_to_3d(
const IntervalPoints &interval_uv,
const ON_Surface *surf)
{
// evaluate surface at uv points to get 3d interval points
IntervalPoints pts_3d;
pts_3d.min = surf->PointAt(interval_uv.min.x, interval_uv.min.y);
pts_3d.mid = surf->PointAt(interval_uv.mid.x, interval_uv.mid.y);
pts_3d.max = surf->PointAt(interval_uv.max.x, interval_uv.max.y);
return pts_3d;
}
HIDDEN IntervalParams
points_3d_to_params_3d(
const IntervalPoints &pts_3d,
const ON_Curve *curve3d)
{
ON_ClassArray<ON_PX_EVENT> events;
ON_Intersect(pts_3d.min, *curve3d, events, INTERSECTION_TOL);
ON_Intersect(pts_3d.mid, *curve3d, events, INTERSECTION_TOL);
ON_Intersect(pts_3d.max, *curve3d, events, INTERSECTION_TOL);
if (events.Count() != 3) {
throw AlgorithmError("points_3d_to_params_3d: conversion failed\n");
}
IntervalParams params_3d;
params_3d.min = events[0].m_b[0];
params_3d.mid = events[1].m_b[0];
params_3d.max = events[2].m_b[0];
return params_3d;
}
HIDDEN std::vector<ON_Interval>
interval_2d_to_3d(
const ON_Interval &interval,
const ON_Curve *curve2d,
const ON_Curve *curve3d,
const ON_Surface *surf)
{
std::vector<ON_Interval> intervals_3d;
ON_Interval c2_dom = curve2d->Domain();
ON_Interval c3_dom = curve3d->Domain();
c2_dom.MakeIncreasing();
if (ON_NearZero(interval.Min() - c2_dom.Min(), ON_ZERO_TOLERANCE) &&
ON_NearZero(interval.Max() - c2_dom.Max(), ON_ZERO_TOLERANCE))
{
// entire 2d domain equates to entire 3d domain
c3_dom.MakeIncreasing();
if (c3_dom.IsValid()) {
intervals_3d.push_back(c3_dom);
}
} else {
// get 2d curve interval points as uv points
IntervalPoints interval_uv =
interval_2d_to_uv(interval, curve2d, surf);
// evaluate surface at uv points to get 3d interval points
IntervalPoints pts_3d = points_uv_to_3d(interval_uv, surf);
// convert 3d points into 3d curve parameters
try {
std::vector<IntervalParams> int_params;
IntervalParams curve_t = points_3d_to_params_3d(pts_3d, curve3d);
if (curve3d->IsClosed()) {
// get 3d seam point as surf point
ON_3dPoint seam_pt = curve3d->PointAt(c3_dom.Min());
ON_ClassArray<ON_PX_EVENT> events;
ON_Intersect(seam_pt, *surf, events, INTERSECTION_TOL);
if (events.Count() == 1) {
ON_3dPoint surf_pt = events[0].m_b;
std::vector<double> split_t;
// get surf point as 2d curve t
events.Empty();
ON_Intersect(surf_pt, *curve2d, events, INTERSECTION_TOL);
if (events.Count() == 1) {
split_t.push_back(events[0].m_b[0]);
}
int surf_seam = IsAtSeam(surf, surf_pt, ON_ZERO_TOLERANCE);
if (surf_seam != SEAM_NONE) {
// move surf_pt to other side of seam
if (surf_seam == SEAM_ALONG_U || surf_seam == SEAM_ALONG_UV) {
ON_Interval vdom = surf->Domain(1);
if (ON_NearZero(surf_pt.y - vdom.Min(),
ON_ZERO_TOLERANCE)) {
surf_pt.y = vdom.Max();
} else {
surf_pt.y = vdom.Min();
}
}
if (surf_seam == SEAM_ALONG_V || surf_seam == SEAM_ALONG_UV) {
ON_Interval udom = surf->Domain(0);
if (ON_NearZero(surf_pt.x - udom.Min(),
ON_ZERO_TOLERANCE)) {
surf_pt.x = udom.Max();
} else {
surf_pt.x = udom.Min();
}
}
// get alternative surf point as 2d curve t
events.Empty();
ON_Intersect(surf_pt, *curve2d, events, INTERSECTION_TOL);
if (events.Count() == 1) {
split_t.push_back(events[0].m_b[0]);
}
}
// see if 3d curve seam point is in the 2d curve interval
for (size_t i = 0; i < split_t.size(); ++i) {
double min2split = fabs(curve_t.min - split_t[i]);
double max2split = fabs(curve_t.max - split_t[i]);
if (min2split > ON_ZERO_TOLERANCE ||
max2split > ON_ZERO_TOLERANCE)
{
// split 2d interval at seam point
std::pair<IntervalPoints, IntervalPoints> halves =
interval_2d_to_2uv(interval, curve2d, surf,
split_t[i]);
// convert new intervals to 3d curve intervals
IntervalPoints left_3d, right_3d;
IntervalParams left_t, right_t;
left_3d = points_uv_to_3d(halves.first, surf);
left_t = points_3d_to_params_3d(left_3d, curve3d);
int_params.push_back(left_t);
right_3d = points_uv_to_3d(halves.second, surf);
right_t = points_3d_to_params_3d(right_3d, curve3d);
int_params.push_back(right_t);
}
}
}
}
if (int_params.empty()) {
int_params.push_back(curve_t);
}
// get final 3d intervals
for (size_t i = 0; i < int_params.size(); ++i) {
curve_t = curve_interval_from_params(int_params[i], curve3d);
ON_Interval interval_3d(curve_t.min, curve_t.max);
if (interval_3d.IsValid()) {
intervals_3d.push_back(interval_3d);
}
}
} catch (AlgorithmError &e) {
bu_log("%s", e.what());
}
}
return intervals_3d;
}
// Convert parameter interval of a 3d curve into the equivalent parameter
// interval on a matching 2d face curve.
HIDDEN ON_Interval
interval_3d_to_2d(
const ON_Interval &interval,
const ON_Curve *curve2d,
const ON_Curve *curve3d,
const ON_BrepFace *face)
{
ON_Interval interval_2d;
ON_Interval whole_domain = curve3d->Domain();
whole_domain.MakeIncreasing();
if (ON_NearZero(interval.Min() - whole_domain.Min(), ON_ZERO_TOLERANCE) &&
ON_NearZero(interval.Max() - whole_domain.Max(), ON_ZERO_TOLERANCE))
{
interval_2d = curve2d->Domain();
interval_2d.MakeIncreasing();
} else {
const ON_Surface *surf = face->SurfaceOf();
IntervalPoints pts;
pts.min = curve3d->PointAt(interval.Min());
pts.mid = curve3d->PointAt(interval.Mid());
pts.max = curve3d->PointAt(interval.Max());
ON_ClassArray<ON_PX_EVENT> events;
ON_Intersect(pts.min, *surf, events, INTERSECTION_TOL);
ON_Intersect(pts.mid, *surf, events, INTERSECTION_TOL);
ON_Intersect(pts.max, *surf, events, INTERSECTION_TOL);
if (events.Count() == 3) {
IntervalPoints interval_uv;
interval_uv.min = events[0].m_b;
interval_uv.mid = events[1].m_b;
interval_uv.max = events[2].m_b;
interval_uv = uv_interval_from_points(interval_uv, surf);
// intersect surface uv parameters with 2d curve to convert
// surface uv parameters to 2d curve parameters
events.Empty();
ON_Intersect(interval_uv.min, *curve2d, events, INTERSECTION_TOL);
ON_Intersect(interval_uv.mid, *curve2d, events, INTERSECTION_TOL);
ON_Intersect(interval_uv.max, *curve2d, events, INTERSECTION_TOL);
if (events.Count() == 3) {
IntervalParams curve_t;
curve_t.min = events[0].m_b[0];
curve_t.mid = events[1].m_b[0];
curve_t.max = events[2].m_b[0];
curve_t = curve_interval_from_params(curve_t, curve2d);
interval_2d.Set(curve_t.min, curve_t.max);
}
}
}
return interval_2d;
}
HIDDEN void
get_subcurves_inside_faces(
ON_SimpleArray<ON_Curve *> &subcurves_on1,
ON_SimpleArray<ON_Curve *> &subcurves_on2,
const ON_Brep *brep1,
const ON_Brep *brep2,
int face_i1,
int face_i2,
ON_SSX_EVENT *event)
{
// The ON_SSX_EVENT from SSI is the intersection of two whole surfaces.
// We need to get the part that lies inside both trimmed patches.
// (brep1's face[face_i1] and brep2's face[face_i2])
ON_SimpleArray<ON_SSX_EVENT *> out;
if (event == NULL) {
return;
}
if (event->m_curve3d == NULL || event->m_curveA == NULL || event->m_curveB == NULL) {
return;
}
// get the face loops
if (face_i1 < 0 || face_i1 >= brep1->m_F.Count() || brep1->m_F[face_i1].m_li.Count() <= 0) {
bu_log("get_subcurves_inside_faces(): invalid face_i1 (%d).\n", face_i1);
return;
}
if (face_i2 < 0 || face_i2 >= brep2->m_F.Count() || brep2->m_F[face_i2].m_li.Count() <= 0) {
bu_log("get_subcurves_inside_faces(): invalid face_i2 (%d).\n", face_i2);
return;
}
const ON_SimpleArray<int> &face1_li = brep1->m_F[face_i1].m_li;
ON_ClassArray<ON_SimpleArray<ON_Curve *> > face1_loops;
for (int i = 0; i < face1_li.Count(); ++i) {
const ON_BrepLoop &brep_loop = brep1->m_L[face1_li[i]];
ON_SimpleArray<ON_Curve *> loop_curves;
for (int j = 0; j < brep_loop.m_ti.Count(); ++j) {
ON_Curve *trim2d =
brep1->m_C2[brep1->m_T[brep_loop.m_ti[j]].m_c2i];
loop_curves.Append(trim2d);
}
face1_loops.Append(loop_curves);
}
const ON_SimpleArray<int> &face2_li = brep2->m_F[face_i2].m_li;
ON_ClassArray<ON_SimpleArray<ON_Curve *> > face2_loops;
for (int i = 0; i < face2_li.Count(); ++i) {
const ON_BrepLoop &brep_loop = brep2->m_L[face2_li[i]];
ON_SimpleArray<ON_Curve *> loop_curves;
for (int j = 0; j < brep_loop.m_ti.Count(); ++j) {
ON_Curve *trim2d =
brep2->m_C2[brep2->m_T[brep_loop.m_ti[j]].m_c2i];
loop_curves.Append(trim2d);
}
face2_loops.Append(loop_curves);
}
// find the intervals of the curves that are inside/on each face
ON_SimpleArray<ON_Interval> intervals1, intervals2;
intervals1 = get_curve_intervals_inside_or_on_face(event->m_curveA,
face1_loops, INTERSECTION_TOL);
intervals2 = get_curve_intervals_inside_or_on_face(event->m_curveB,
face2_loops, INTERSECTION_TOL);
// get subcurves for each face
for (int i = 0; i < intervals1.Count(); ++i) {
// convert interval on face 1 to equivalent interval on face 2
std::vector<ON_Interval> intervals_3d;
intervals_3d = interval_2d_to_3d(intervals1[i], event->m_curveA,
event->m_curve3d, &brep1->m_F[face_i1]);
for (size_t j = 0; j < intervals_3d.size(); ++j) {
ON_Interval interval_on2 = interval_3d_to_2d(intervals_3d[j],
event->m_curveB, event->m_curve3d, &brep2->m_F[face_i2]);
if (interval_on2.IsValid()) {
// create subcurve from interval
try {
ON_Curve *subcurve_on2 = sub_curve(event->m_curveB,
interval_on2.Min(), interval_on2.Max());
subcurves_on2.Append(subcurve_on2);
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
}
}
}
for (int i = 0; i < intervals2.Count(); ++i) {
// convert interval on face 1 to equivalent interval on face 2
std::vector<ON_Interval> intervals_3d;
intervals_3d = interval_2d_to_3d(intervals2[i], event->m_curveB,
event->m_curve3d, &brep2->m_F[face_i2]);
for (size_t j = 0; j < intervals_3d.size(); ++j) {
ON_Interval interval_on1 = interval_3d_to_2d(intervals_3d[j],
event->m_curveA, event->m_curve3d, &brep1->m_F[face_i1]);
if (interval_on1.IsValid()) {
// create subcurve from interval
try {
ON_Curve *subcurve_on1 = sub_curve(event->m_curveA,
interval_on1.Min(), interval_on1.Max());
subcurves_on1.Append(subcurve_on1);
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
}
}
}
}
HIDDEN double
bbox_diagonal_length(ON_Curve *curve)
{
double len = 0.0;
if (curve) {
ON_BoundingBox bbox;
if (curve->GetTightBoundingBox(bbox)) {
len = bbox.Diagonal().Length();
} else {
len = curve->PointAtStart().DistanceTo(curve->PointAtEnd());
}
}
return len;
}
HIDDEN void
split_curve(ON_Curve *&left, ON_Curve *&right, const ON_Curve *in, double t)
{
try {
left = sub_curve(in, in->Domain().m_t[0], t);
} catch (InvalidInterval &) {
left = NULL;
}
try {
right = sub_curve(in, t, in->Domain().m_t[1]);
} catch (InvalidInterval &) {
right = NULL;
}
}
HIDDEN double
configure_for_linking(
LinkedCurve *&first,
LinkedCurve *&second,
LinkedCurve &in1,
LinkedCurve &in2)
{
double dist_s1s2 = in1.PointAtStart().DistanceTo(in2.PointAtStart());
double dist_s1e2 = in1.PointAtStart().DistanceTo(in2.PointAtEnd());
double dist_e1s2 = in1.PointAtEnd().DistanceTo(in2.PointAtStart());
double dist_e1e2 = in1.PointAtEnd().DistanceTo(in2.PointAtEnd());
double min_dist = std::min(dist_s1s2, dist_s1e2);
min_dist = std::min(min_dist, dist_e1s2);
min_dist = std::min(min_dist, dist_e1e2);
first = second = NULL;
if (dist_s1e2 <= min_dist) {
first = &in2;
second = &in1;
} else if (dist_e1s2 <= min_dist) {
first = &in1;
second = &in2;
} else if (dist_s1s2 <= min_dist) {
if (in1.Reverse()) {
first = &in1;
second = &in2;
}
} else if (dist_e1e2 <= min_dist) {
if (in2.Reverse()) {
first = &in1;
second = &in2;
}
}
return min_dist;
}
struct LinkedCurveX {
int ssi_idx_a;
int ssi_idx_b;
ON_SimpleArray<ON_X_EVENT> events;
};
HIDDEN ON_ClassArray<LinkedCurve>
get_joinable_ssi_curves(const ON_SimpleArray<SSICurve> &in)
{
ON_SimpleArray<SSICurve> curves;
for (int i = 0; i < in.Count(); ++i) {
curves.Append(in[i]);
}
for (int i = 0; i < curves.Count(); ++i) {
if (curves[i].m_curve == NULL || curves[i].m_curve->IsClosed()) {
continue;
}
for (int j = i + 1; j < curves.Count(); j++) {
if (curves[j].m_curve == NULL || curves[j].m_curve->IsClosed()) {
continue;
}
ON_Curve *icurve = curves[i].m_curve;
ON_Curve *jcurve = curves[j].m_curve;
ON_SimpleArray<ON_X_EVENT> events;
ON_Intersect(icurve, jcurve, events, INTERSECTION_TOL);
if (events.Count() != 1) {
if (events.Count() > 1) {
bu_log("unexpected intersection between curves\n");
}
continue;
}
ON_X_EVENT event = events[0];
if (event.m_type == ON_X_EVENT::ccx_overlap) {
// curves from adjacent surfaces may overlap and have
// common endpoints, but we don't want the linked
// curve to double back on itself creating a
// degenerate section
ON_Interval dom[2], range[2];
dom[0] = icurve->Domain();
dom[1] = jcurve->Domain();
range[0].Set(event.m_a[0], event.m_a[1]);
range[1].Set(event.m_b[0], event.m_b[1]);
// overlap endpoints that are near the endpoints
// should be snapped to the endpoints
for (int k = 0; k < 2; ++k) {
dom[k].MakeIncreasing();
range[k].MakeIncreasing();
for (int l = 0; l < 2; ++l) {
if (ON_NearZero(dom[k].m_t[l] - range[k].m_t[l],
ON_ZERO_TOLERANCE)) {
range[k].m_t[l] = dom[k].m_t[l];
}
}
}
if (dom[0].Includes(range[0], true) ||
dom[1].Includes(range[1], true))
{
// overlap is in the middle of one or both curves
continue;
}
// if one curve is completely contained by the other,
// keep just the larger curve (or the first curve if
// they're the same)
if (dom[1] == range[1]) {
curves[j].m_curve = NULL;
continue;
}
if (dom[0] == range[0]) {
curves[i].m_curve = NULL;
continue;
}
// remove the overlapping portion from the end of one
// curve so the curves meet at just a single point
try {
double start = dom[0].m_t[0];
double end = range[0].m_t[0];
if (ON_NearZero(start - end, ON_ZERO_TOLERANCE)) {
start = range[0].m_t[1];
end = dom[0].m_t[1];
}
ON_Curve *isub = sub_curve(icurve, start, end);
delete curves[i].m_curve;
curves[i] = isub;
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
} else {
// For a single intersection, assume that one or both
// curve endpoints is just a little past where it
// should be. Split the curves at the intersection,
// and discard the portion with the smaller bbox
// diagonal.
ON_Curve *ileft, *iright, *jleft, *jright;
ileft = iright = jleft = jright = NULL;
split_curve(ileft, iright, icurve, event.m_a[0]);
split_curve(jleft, jright, jcurve, event.m_b[0]);
if (bbox_diagonal_length(ileft) <
bbox_diagonal_length(iright))
{
std::swap(ileft, iright);
}
ON_Curve *isub = ileft;
delete iright;
if (bbox_diagonal_length(jleft) <
bbox_diagonal_length(jright))
{
std::swap(jleft, jright);
}
ON_Curve *jsub = jleft;
delete jright;
if (isub && jsub) {
// replace the original ssi curves with the
// trimmed versions
curves[i].m_curve = isub;
curves[j].m_curve = jsub;
isub = jsub = NULL;
}
delete isub;
delete jsub;
}
}
}
ON_ClassArray<LinkedCurve> out;
for (int i = 0; i < curves.Count(); ++i) {
if (curves[i].m_curve != NULL) {
LinkedCurve linked;
linked.Append(curves[i]);
out.Append(linked);
}
}
return out;
}
HIDDEN ON_ClassArray<LinkedCurve>
link_curves(const ON_SimpleArray<SSICurve> &in)
{
// There might be two reasons why we need to link these curves.
// 1) They are from intersections with two different surfaces.
// 2) They are not continuous in the other surface's UV domain.
ON_ClassArray<LinkedCurve> tmp = get_joinable_ssi_curves(in);
// As usual, we use a greedy approach.
for (int i = 0; i < tmp.Count(); i++) {
for (int j = 0; j < tmp.Count(); j++) {
if (tmp[i].m_ssi_curves.Count() == 0 || tmp[i].IsClosed()) {
break;
}
if (tmp[j].m_ssi_curves.Count() == 0 || tmp[j].IsClosed() || j == i) {
continue;
}
LinkedCurve *c1 = NULL, *c2 = NULL;
double dist = configure_for_linking(c1, c2, tmp[i], tmp[j]);
if (dist > INTERSECTION_TOL) {
continue;
}
if (c1 != NULL && c2 != NULL) {
LinkedCurve new_curve;
new_curve.Append(*c1);
if (dist > ON_ZERO_TOLERANCE) {
new_curve.Append(SSICurve(new ON_LineCurve(c1->PointAtEnd(), c2->PointAtStart())));
}
new_curve.Append(*c2);
tmp[i] = new_curve;
tmp[j].m_ssi_curves.Empty();
}
// Check whether tmp[i] is closed within a tolerance
if (tmp[i].PointAtStart().DistanceTo(tmp[i].PointAtEnd()) < INTERSECTION_TOL && !tmp[i].IsClosed()) {
// make IsClosed() true
tmp[i].Append(SSICurve(new ON_LineCurve(tmp[i].PointAtEnd(), tmp[i].PointAtStart())));
}
}
}
// Append the remaining curves to out.
ON_ClassArray<LinkedCurve> out;
for (int i = 0; i < tmp.Count(); i++) {
if (tmp[i].m_ssi_curves.Count() != 0) {
out.Append(tmp[i]);
}
}
if (DEBUG_BREP_BOOLEAN) {
bu_log("link_curves(): %d curves remaining.\n", out.Count());
}
return out;
}
class CurvePoint {
public:
int source_loop;
int loop_index;
double curve_t;
ON_2dPoint pt;
enum Location {
BOUNDARY,
INSIDE,
OUTSIDE
} location;
static CurvePoint::Location
PointLoopLocation(ON_2dPoint pt, const ON_SimpleArray<ON_Curve *> &loop);
CurvePoint(
int loop,
int li,
double pt_t,
ON_Curve *curve,
const ON_SimpleArray<ON_Curve *> &other_loop)
: source_loop(loop), loop_index(li), curve_t(pt_t)
{
pt = curve->PointAt(curve_t);
location = PointLoopLocation(pt, other_loop);
}
CurvePoint(
int loop,
int li,
double t,
ON_2dPoint p,
CurvePoint::Location l)
: source_loop(loop), loop_index(li), curve_t(t), pt(p), location(l)
{
}
bool
operator<(const CurvePoint &other) const
{
// for points not on the same loop, compare the actual points
if (source_loop != other.source_loop) {
if (ON_NearZero(pt.DistanceTo(other.pt), INTERSECTION_TOL)) {
return false;
}
return pt < other.pt;
}
// for points on the same loop, compare loop position
if (loop_index == other.loop_index) {
if (ON_NearZero(curve_t - other.curve_t, INTERSECTION_TOL)) {
return false;
}
return curve_t < other.curve_t;
}
return loop_index < other.loop_index;
}
bool
operator==(const CurvePoint &other) const
{
return ON_NearZero(pt.DistanceTo(other.pt), INTERSECTION_TOL);
}
bool
operator!=(const CurvePoint &other) const
{
return !ON_NearZero(pt.DistanceTo(other.pt), INTERSECTION_TOL);
}
};
class CurvePointAbsoluteCompare {
public:
bool
operator()(const CurvePoint &a, const CurvePoint &b) const
{
if (ON_NearZero(a.pt.DistanceTo(b.pt), INTERSECTION_TOL)) {
return false;
}
return a.pt < b.pt;
}
};
CurvePoint::Location
CurvePoint::PointLoopLocation(
ON_2dPoint point,
const ON_SimpleArray<ON_Curve *> &loop)
{
if (is_point_on_loop(point, loop)) {
return CurvePoint::BOUNDARY;
}
if (point_loop_location(point, loop) == OUTSIDE_OR_ON_LOOP) {
return CurvePoint::OUTSIDE;
}
return CurvePoint::INSIDE;
}
class CurveSegment {
public:
ON_SimpleArray<ON_Curve *> orig_loop;
CurvePoint from, to;
enum Location {
BOUNDARY,
INSIDE,
OUTSIDE
} location;
CurveSegment(
ON_SimpleArray<ON_Curve *> &loop,
CurvePoint f,
CurvePoint t,
CurveSegment::Location l)
: orig_loop(loop), from(f), to(t), location(l)
{
if (!orig_loop.Capacity()) {
size_t c = (from.loop_index > to.loop_index) ? from.loop_index : to.loop_index;
orig_loop.SetCapacity(c + 1);
}
}
void
Reverse(void)
{
std::swap(from, to);
}
ON_Curve *
Curve(void) const
{
ON_Curve *from_curve = orig_loop[from.loop_index];
ON_Curve *to_curve = orig_loop[to.loop_index];
ON_Interval from_dom = from_curve->Domain();
ON_Interval to_dom = to_curve->Domain();
// if endpoints are on the same curve, just get the part between them
if (from.loop_index == to.loop_index) {
ON_Curve *seg_curve =
sub_curve(from_curve, from.curve_t, to.curve_t);
return seg_curve;
}
// if endpoints are on different curves, we may need a subcurve of
// just the 'from' curve, just the 'to' curve, or both
if (ON_NearZero(from.curve_t - from_dom.m_t[1], INTERSECTION_TOL)) {
// starting at end of 'from' same as starting at start of 'to'
ON_Curve *seg_curve = sub_curve(to_curve, to_dom.m_t[0],
to.curve_t);
return seg_curve;
}
if (ON_NearZero(to.curve_t - to_dom.m_t[0], INTERSECTION_TOL)) {
// ending at start of 'to' same as ending at end of 'from'
ON_Curve *seg_curve = sub_curve(from_curve, from.curve_t,
from_dom.m_t[1]);
return seg_curve;
}
ON_PolyCurve *pcurve = new ON_PolyCurve();
append_to_polycurve(sub_curve(from_curve, from.curve_t,
from_dom.m_t[1]), *pcurve);
append_to_polycurve(sub_curve(to_curve, to_dom.m_t[0], to.curve_t),
*pcurve);
return pcurve;
}
bool
IsDegenerate(void)
{
ON_Curve *seg_curve = NULL;
try {
seg_curve = Curve();
} catch (InvalidInterval &) {
return true;
}
double length = 0.0;
if (seg_curve->IsLinear(INTERSECTION_TOL)) {
length = seg_curve->PointAtStart().DistanceTo(
seg_curve->PointAtEnd());
} else {
double min[3] = {0.0, 0.0, 0.0};
double max[3] = {0.0, 0.0, 0.0};
seg_curve->GetBBox(min, max, true);
length = DIST_PNT_PNT(min, max);
}
delete seg_curve;
return length < INTERSECTION_TOL;
}
bool
operator<(const CurveSegment &other) const
{
return from < other.from;
}
};
class LoopBooleanResult {
public:
std::vector<ON_SimpleArray<ON_Curve *> > outerloops;
std::vector<ON_SimpleArray<ON_Curve *> > innerloops;
void ClearOuterloops() {
for (size_t i = 0; i < outerloops.size(); ++i) {
for (int j = 0; j < outerloops[i].Count(); ++j) {
delete outerloops[i][j];
}
}
}
void ClearInnerloops() {
for (size_t i = 0; i < innerloops.size(); ++i) {
for (int j = 0; j < innerloops[i].Count(); ++j) {
delete innerloops[i][j];
}
}
}
};
#define LOOP_DIRECTION_CCW 1
#define LOOP_DIRECTION_CW -1
#define LOOP_DIRECTION_NONE 0
HIDDEN bool
close_small_gap(ON_SimpleArray<ON_Curve *> &loop, int curr, int next)
{
ON_3dPoint end_curr = loop[curr]->PointAtEnd();
ON_3dPoint start_next = loop[next]->PointAtStart();
double gap = end_curr.DistanceTo(start_next);
if (gap <= INTERSECTION_TOL && gap >= ON_ZERO_TOLERANCE) {
ON_Curve *closing_seg = new ON_LineCurve(end_curr, start_next);
loop.Insert(next, closing_seg);
return true;
}
return false;
}
HIDDEN void
close_small_gaps(ON_SimpleArray<ON_Curve *> &loop)
{
if (loop.Count() == 0) {
return;
}
for (int i = 0; i < loop.Count() - 1; ++i) {
if (close_small_gap(loop, i, i + 1)) {
++i;
}
}
close_small_gap(loop, loop.Count() - 1, 0);
}
ON_Curve *
get_loop_curve(const ON_SimpleArray<ON_Curve *> &loop)
{
ON_PolyCurve *pcurve = new ON_PolyCurve();
for (int i = 0; i < loop.Count(); ++i) {
append_to_polycurve(loop[i]->Duplicate(), *pcurve);
}
return pcurve;
}
std::list<ON_SimpleArray<ON_Curve *> >::iterator
find_innerloop(std::list<ON_SimpleArray<ON_Curve *> > &loops)
{
std::list<ON_SimpleArray<ON_Curve *> >::iterator k;
for (k = loops.begin(); k != loops.end(); ++k) {
ON_Curve *loop_curve = get_loop_curve(*k);
if (ON_ClosedCurveOrientation(*loop_curve, NULL) == LOOP_DIRECTION_CW) {
delete loop_curve;
return k;
}
delete loop_curve;
}
return loops.end();
}
bool
set_loop_direction(ON_SimpleArray<ON_Curve *> &loop, int dir)
{
ON_Curve *curve = get_loop_curve(loop);
int curr_dir = ON_ClosedCurveOrientation(*curve, NULL);
delete curve;
if (curr_dir == LOOP_DIRECTION_NONE) {
// can't set the correct direction
return false;
}
if (curr_dir != dir) {
// need reverse
for (int i = 0; i < loop.Count(); ++i) {
if (!loop[i]->Reverse()) {
return false;
}
}
loop.Reverse();
}
// curve already has the correct direction
return true;
}
void
add_point_to_set(std::multiset<CurvePoint> &set, CurvePoint pt)
{
if (set.count(pt) < 2) {
set.insert(pt);
}
}
std::multiset<CurveSegment>
make_segments(
std::multiset<CurvePoint> &curve1_points,
ON_SimpleArray<ON_Curve *> &loop1,
ON_SimpleArray<ON_Curve *> &loop2)
{
std::multiset<CurveSegment> out;
std::multiset<CurvePoint>::iterator first = curve1_points.begin();
std::multiset<CurvePoint>::iterator curr = first;
std::multiset<CurvePoint>::iterator next = ++curve1_points.begin();
for (; next != curve1_points.end(); ++curr, ++next) {
CurvePoint from = *curr;
CurvePoint to = *next;
CurveSegment new_seg(loop1, from, to, CurveSegment::BOUNDARY);
if (new_seg.IsDegenerate()) {
continue;
}
if (from.location == CurvePoint::BOUNDARY &&
to.location == CurvePoint::BOUNDARY)
{
ON_Curve *seg_curve = loop1[from.loop_index];
double end_t = to.curve_t;
if (from.loop_index != to.loop_index) {
end_t = seg_curve->Domain().m_t[1];
}
ON_2dPoint seg_midpt = seg_curve->PointAt(
ON_Interval(from.curve_t, end_t).Mid());
CurvePoint::Location midpt_location =
CurvePoint::PointLoopLocation(seg_midpt, loop2);
if (midpt_location == CurvePoint::INSIDE) {
new_seg.location = CurveSegment::INSIDE;
} else if (midpt_location == CurvePoint::OUTSIDE) {
new_seg.location = CurveSegment::OUTSIDE;
}
} else if (from.location == CurvePoint::INSIDE ||
to.location == CurvePoint::INSIDE)
{
new_seg.location = CurveSegment::INSIDE;
} else if (from.location == CurvePoint::OUTSIDE ||
to.location == CurvePoint::OUTSIDE)
{
new_seg.location = CurveSegment::OUTSIDE;
}
out.insert(new_seg);
}
return out;
}
void
set_append_segment(
std::multiset<CurveSegment> &out,
const CurveSegment &seg)
{
std::multiset<CurveSegment>::iterator i;
for (i = out.begin(); i != out.end(); ++i) {
if ((i->from == seg.to) && (i->to == seg.from)) {
// if this segment is a reversed version of an existing
// segment, it cancels the existing segment out
ON_Curve *prev_curve = i->Curve();
ON_Curve *seg_curve = seg.Curve();
ON_SimpleArray<ON_X_EVENT> events;
ON_Intersect(prev_curve, seg_curve, events, INTERSECTION_TOL);
if (events.Count() == 1 && events[0].m_type == ON_X_EVENT::ccx_overlap) {
out.erase(i);
return;
}
}
}
out.insert(seg);
}
void
set_append_segments_at_location(
std::multiset<CurveSegment> &out,
std::multiset<CurveSegment> &in,
CurveSegment::Location location,
bool reversed_segs_cancel)
{
std::multiset<CurveSegment>::iterator i;
if (reversed_segs_cancel) {
for (i = in.begin(); i != in.end(); ++i) {
if (i->location == location) {
set_append_segment(out, *i);
}
}
} else {
for (i = in.begin(); i != in.end(); ++i) {
if (i->location == location) {
out.insert(*i);
}
}
}
}
std::multiset<CurveSegment>
find_similar_segments(
std::multiset<CurveSegment> &set,
const CurveSegment &seg)
{
std::multiset<CurveSegment> out;
std::multiset<CurveSegment>::iterator i;
for (i = set.begin(); i != set.end(); ++i) {
if (((i->from == seg.from) && (i->to == seg.to)) ||
((i->from == seg.to) && (i->to == seg.from)))
{
out.insert(*i);
}
}
return out;
}
HIDDEN std::multiset<CurveSegment>
get_op_segments(
std::multiset<CurveSegment> &curve1_segments,
std::multiset<CurveSegment> &curve2_segments,
op_type op)
{
std::multiset<CurveSegment> out;
std::multiset<CurveSegment> c1_boundary_segs;
set_append_segments_at_location(c1_boundary_segs, curve1_segments,
CurveSegment::BOUNDARY, false);
std::multiset<CurveSegment> c2_boundary_segs;
set_append_segments_at_location(c2_boundary_segs, curve2_segments,
CurveSegment::BOUNDARY, false);
if (op == BOOLEAN_INTERSECT) {
set_append_segments_at_location(out, curve1_segments,
CurveSegment::INSIDE, true);
set_append_segments_at_location(out, curve2_segments,
CurveSegment::INSIDE, true);
std::multiset<CurveSegment>::iterator i;
for (i = c1_boundary_segs.begin(); i != c1_boundary_segs.end(); ++i) {
std::multiset<CurveSegment> curve1_matches =
find_similar_segments(c1_boundary_segs, *i);
std::multiset<CurveSegment> curve2_matches =
find_similar_segments(c2_boundary_segs, *i);
if (curve1_matches.size() > 1 || curve2_matches.size() > 1) {
continue;
}
if (curve1_matches.begin()->from == curve2_matches.begin()->from) {
out.insert(*i);
}
}
} else if (op == BOOLEAN_DIFF) {
set_append_segments_at_location(out, curve1_segments,
CurveSegment::OUTSIDE, true);
set_append_segments_at_location(out, curve2_segments,
CurveSegment::INSIDE, true);
std::multiset<CurveSegment>::iterator i;
for (i = c1_boundary_segs.begin(); i != c1_boundary_segs.end(); ++i) {
std::multiset<CurveSegment> curve1_matches =
find_similar_segments(c1_boundary_segs, *i);
std::multiset<CurveSegment> curve2_matches =
find_similar_segments(c2_boundary_segs, *i);
if (curve1_matches.size() > 1) {
continue;
}
if (curve1_matches.begin()->from == curve2_matches.begin()->from ||
curve2_matches.size() > 1)
{
out.insert(*i);
}
}
} else if (op == BOOLEAN_UNION) {
set_append_segments_at_location(out, curve1_segments,
CurveSegment::OUTSIDE, true);
set_append_segments_at_location(out, curve2_segments,
CurveSegment::OUTSIDE, true);
std::multiset<CurveSegment>::iterator i;
for (i = c1_boundary_segs.begin(); i != c1_boundary_segs.end(); ++i) {
std::multiset<CurveSegment> curve1_matches =
find_similar_segments(c1_boundary_segs, *i);
std::multiset<CurveSegment> curve2_matches =
find_similar_segments(c2_boundary_segs, *i);
if (curve1_matches.size() > 1 && curve2_matches.size() > 1) {
continue;
}
std::multiset<CurveSegment>::iterator a, b;
for (a = curve1_matches.begin(); a != curve1_matches.end(); ++a) {
b = curve2_matches.begin();
for (; b != curve2_matches.end(); ++b) {
if (a->from == b->from) {
out.insert(*i);
}
}
}
}
}
return out;
}
std::list<ON_SimpleArray<ON_Curve *> >
construct_loops_from_segments(
std::multiset<CurveSegment> &segments)
{
std::list<ON_SimpleArray<ON_Curve *> > out;
while (!segments.empty()) {
std::vector<std::multiset<CurveSegment>::iterator> loop_segs;
std::multiset<CurvePoint, CurvePointAbsoluteCompare> visited_points;
std::multiset<CurveSegment>::iterator curr_seg, prev_seg;
curr_seg = segments.begin();
loop_segs.push_back(curr_seg);
visited_points.insert(curr_seg->from);
visited_points.insert(curr_seg->to);
bool closed_curve = (curr_seg->from == curr_seg->to);
while (!closed_curve) {
// look for a segment that connects to the previous
prev_seg = curr_seg;
for (curr_seg = segments.begin(); curr_seg != segments.end(); ++curr_seg) {
if (curr_seg->from == prev_seg->to) {
break;
}
}
if (curr_seg == segments.end()) {
// no segment connects to the prev one
break;
} else {
// Extend our loop with the joining segment.
// If we've visited its endpoint before, then the loop
// is now closed.
loop_segs.push_back(curr_seg);
visited_points.insert(curr_seg->to);
closed_curve = (visited_points.count(curr_seg->to) > 1);
}
}
if (closed_curve) {
// find the segment the closing segment connected to (it
// may not be the first segment)
size_t i;
for (i = 0; i < loop_segs.size(); ++i) {
if (loop_segs[i]->from == loop_segs.back()->to) {
break;
}
}
// Form a curve from the closed chain of segments.
// Remove the used segments from the available set.
ON_SimpleArray<ON_Curve *> loop;
for (; i < loop_segs.size(); ++i) {
try {
loop.Append(loop_segs[i]->Curve());
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
segments.erase(loop_segs[i]);
}
out.push_back(loop);
} else {
// couldn't join to the last segment, discard it
segments.erase(loop_segs.back());
bu_log("construct_loops_from_segments: found unconnected segment\n");
}
loop_segs.clear();
visited_points.clear();
}
return out;
}
std::multiset<CurvePoint>
get_loop_points(
int source_loop,
ON_SimpleArray<ON_Curve *> loop1,
ON_SimpleArray<ON_Curve *> loop2)
{
std::multiset<CurvePoint> out;
if (loop1.Count() <= 0)
return out;
ON_Curve *loop1_seg = loop1[0];
out.insert(CurvePoint(source_loop, 0, loop1_seg->Domain().m_t[0], loop1_seg,
loop2));
for (int i = 0; i < loop1.Count(); ++i) {
loop1_seg = loop1[i];
out.insert(CurvePoint(source_loop, i, loop1_seg->Domain().m_t[1],
loop1_seg, loop2));
}
return out;
}
// separate outerloops and innerloops
HIDDEN LoopBooleanResult
make_result_from_loops(const std::list<ON_SimpleArray<ON_Curve *> > &loops)
{
LoopBooleanResult out;
std::list<ON_SimpleArray<ON_Curve *> >::const_iterator li;
for (li = loops.begin(); li != loops.end(); ++li) {
ON_Curve *loop_curve = get_loop_curve(*li);
int dir = ON_ClosedCurveOrientation(*loop_curve, NULL);
if (dir == LOOP_DIRECTION_CCW) {
out.outerloops.push_back(*li);
} else if (dir == LOOP_DIRECTION_CW) {
out.innerloops.push_back(*li);
}
delete loop_curve;
}
return out;
}
// Get the result of a boolean combination of two loops. Based on the
// algorithm from this paper:
//
// Margalit, Avraham and Gary D. Knott. 1989. "An Algorithm for
// Computing the Union, Intersection or Difference of two Polygons."
// Computers & Graphics 13:167-183.
//
// gvu.gatech.edu/people/official/jarek/graphics/papers/04PolygonBooleansMargalit.pdf
LoopBooleanResult
loop_boolean(
const ON_SimpleArray<ON_Curve *> &l1,
const ON_SimpleArray<ON_Curve *> &l2,
op_type op)
{
LoopBooleanResult out;
if (op != BOOLEAN_INTERSECT &&
op != BOOLEAN_DIFF &&
op != BOOLEAN_UNION)
{
bu_log("loop_boolean: unsupported operation\n");
return out;
}
if (l1.Count() <= 0 || l2.Count() <= 0) {
bu_log("loop_boolean: one or more empty loops\n");
return out;
}
// copy input loops
ON_SimpleArray<ON_Curve *> loop1, loop2;
for (int i = 0; i < l1.Count(); ++i) {
loop1.Append(l1[i]->Duplicate());
}
for (int i = 0; i < l2.Count(); ++i) {
loop2.Append(l2[i]->Duplicate());
}
// set curve directions based on operation
int loop1_dir, loop2_dir;
loop1_dir = loop2_dir = LOOP_DIRECTION_CCW;
if (op == BOOLEAN_DIFF) {
loop2_dir = LOOP_DIRECTION_CW;
}
if (!set_loop_direction(loop1, loop1_dir) ||
!set_loop_direction(loop2, loop2_dir))
{
bu_log("loop_boolean: couldn't standardize curve directions\n");
for (int i = 0; i < l1.Count(); ++i) {
delete loop1[i];
}
for (int i = 0; i < l2.Count(); ++i) {
delete loop2[i];
}
return out;
}
// get curve endpoints and intersection points for each loop
std::multiset<CurvePoint> loop1_points, loop2_points;
loop1_points = get_loop_points(1, loop1, loop2);
loop2_points = get_loop_points(2, loop2, loop1);
for (int i = 0; i < loop1.Count(); ++i) {
for (int j = 0; j < loop2.Count(); ++j) {
ON_SimpleArray<ON_X_EVENT> x_events;
ON_Intersect(loop1[i], loop2[j], x_events, INTERSECTION_TOL);
for (int k = 0; k < x_events.Count(); ++k) {
add_point_to_set(loop1_points, CurvePoint(1, i,
x_events[k].m_a[0], x_events[k].m_A[0],
CurvePoint::BOUNDARY));
add_point_to_set(loop2_points, CurvePoint(2, j,
x_events[k].m_b[0], x_events[k].m_B[0],
CurvePoint::BOUNDARY));
if (x_events[k].m_type == ON_X_EVENT::ccx_overlap) {
add_point_to_set(loop1_points, CurvePoint(1, i,
x_events[k].m_a[1], x_events[k].m_A[1],
CurvePoint::BOUNDARY));
add_point_to_set(loop2_points, CurvePoint(2, j,
x_events[k].m_b[1], x_events[k].m_B[1],
CurvePoint::BOUNDARY));
}
}
}
}
// classify segments and determine which belong in the result
std::multiset<CurveSegment> loop1_segments, loop2_segments;
loop1_segments = make_segments(loop1_points, loop1, loop2);
loop2_segments = make_segments(loop2_points, loop2, loop1);
std::multiset<CurveSegment> out_segments =
get_op_segments(loop1_segments, loop2_segments, op);
// build result
std::list<ON_SimpleArray<ON_Curve *> > new_loops;
new_loops = construct_loops_from_segments(out_segments);
for (int i = 0; i < l1.Count(); ++i) {
delete loop1[i];
}
for (int i = 0; i < l2.Count(); ++i) {
delete loop2[i];
}
std::list<ON_SimpleArray<ON_Curve *> >::iterator li;
for (li = new_loops.begin(); li != new_loops.end(); ++li) {
close_small_gaps(*li);
}
out = make_result_from_loops(new_loops);
return out;
}
std::list<ON_SimpleArray<ON_Curve *> >
innerloops_inside_outerloop(
const ON_SimpleArray<ON_Curve *> &outerloop_curve,
const std::vector<ON_SimpleArray<ON_Curve *> > &innerloop_curves)
{
std::list<ON_SimpleArray<ON_Curve *> > out;
for (size_t i = 0; i < innerloop_curves.size(); ++i) {
LoopBooleanResult new_loops;
new_loops = loop_boolean(outerloop_curve, innerloop_curves[i],
BOOLEAN_INTERSECT);
// grab outerloops
for (size_t j = 0; j < new_loops.outerloops.size(); ++j) {
set_loop_direction(new_loops.outerloops[j], LOOP_DIRECTION_CW);
out.push_back(new_loops.outerloops[j]);
}
new_loops.ClearInnerloops();
}
return out;
}
TrimmedFace *
make_face_from_loops(
const TrimmedFace *orig_face,
const ON_SimpleArray<ON_Curve *> &outerloop,
const std::vector<ON_SimpleArray<ON_Curve *> > &innerloops)
{
TrimmedFace *face = new TrimmedFace();
face->m_face = orig_face->m_face;
face->m_outerloop.Append(outerloop.Count(), outerloop.Array());
// TODO: the innerloops found here can't be inside any other
// outerloop, and should be removed from the innerloop set in the
// interest of efficiency
std::list<ON_SimpleArray<ON_Curve *> > new_innerloops;
new_innerloops = innerloops_inside_outerloop(outerloop, innerloops);
std::list<ON_SimpleArray<ON_Curve *> >::iterator i;
for (i = new_innerloops.begin(); i != new_innerloops.end(); ++i) {
face->m_innerloop.push_back(*i);
}
return face;
}
HIDDEN LoopBooleanResult
combine_loops(
const TrimmedFace *orig_face,
const LoopBooleanResult &new_loops)
{
// Intersections always produce a single outerloop.
//
// Subtractions may produce multiple outerloops, or a single
// outerloop that optionally includes a single innerloop.
//
// So, the possible results are:
// 1) Single outerloop.
// 2) Multiple outerloops.
// 3) Single outerloop with single innerloop.
// First we'll combine the old and new innerloops.
std::vector<ON_SimpleArray<ON_Curve *> > merged_innerloops;
if (new_loops.innerloops.size() == 1) {
// If the result has an innerloop, it may overlap any of the
// original innerloops. We'll union all overlapping loops with
// the new innerloop.
ON_SimpleArray<ON_Curve *> candidate_innerloop(new_loops.innerloops[0]);
for (size_t i = 0; i < orig_face->m_innerloop.size(); ++i) {
LoopBooleanResult merged = loop_boolean(candidate_innerloop,
orig_face->m_innerloop[i], BOOLEAN_UNION);
if (merged.outerloops.size() == 1) {
candidate_innerloop = merged.outerloops[0];
} else {
merged_innerloops.push_back(orig_face->m_innerloop[i]);
merged.ClearOuterloops();
}
}
merged_innerloops.push_back(candidate_innerloop);
} else if (!orig_face->m_innerloop.empty()) {
for (size_t i = 0; i < orig_face->m_innerloop.size(); ++i) {
merged_innerloops.push_back(orig_face->m_innerloop[i]);
}
}
// Next we'll attempt to subtract all merged innerloops from each
// new outerloop to get the final set of loops. For each
// subtraction, there are four possibilities:
// 1) The innerloop is outside the outerloop, and the result is
// the original outerloop.
// 2) The innerloop completely encloses the outerloop, and the
// result is empty.
// 3) The innerloop is completely contained by the outerloop, and
// the result is the input outerloop and innerloop.
// 4) The innerloop overlaps the outerloop, and the result is one
// or more outerloops.
LoopBooleanResult out;
for (size_t i = 0; i < new_loops.outerloops.size(); ++i) {
std::list<ON_SimpleArray<ON_Curve *> >::iterator part, next_part;
std::list<ON_SimpleArray<ON_Curve *> > outerloop_parts;
// start with the original outerloop
outerloop_parts.push_back(new_loops.outerloops[i]);
// attempt to subtract all innerloops from it, and from
// whatever subparts of it are created along the way
for (size_t j = 0; j < merged_innerloops.size(); ++j) {
part = outerloop_parts.begin();
for (; part != outerloop_parts.end(); part = next_part) {
LoopBooleanResult diffed = loop_boolean(*part,
merged_innerloops[j], BOOLEAN_DIFF);
next_part = part;
++next_part;
if (diffed.innerloops.size() == 1) {
// The outerloop part contains the innerloop, so
// the innerloop belongs in the final set.
//
// Note that any innerloop added here will remains
// completely inside an outerloop part even if the
// part list changes. In order for a subsequent
// subtraction to put any part of it outside an
// outerloop, that later innerloop would have to
// overlap this one, in which case, the innerloops
// would have been unioned together in the
// previous merging step.
out.innerloops.push_back(diffed.innerloops[0]);
} else {
// outerloop part has been erased, modified, or
// split, so we need to remove it
for (int k = 0; k < part->Count(); ++k) {
delete (*part)[k];
}
outerloop_parts.erase(part);
// add any new parts for subsequent subtractions
for (size_t k = 0; k < diffed.outerloops.size(); ++k) {
outerloop_parts.push_front(diffed.outerloops[k]);
}
}
}
}
// whatever parts of the outerloop that remain after
// subtracting all innerloops belong in the final set
part = outerloop_parts.begin();
for (; part != outerloop_parts.end(); ++part) {
out.outerloops.push_back(*part);
}
}
return out;
// Only thing left to do is make a face from each outerloop. If
// one of the innerloops is inside the outerloop, make it part of
// the face and remove it for consideration for other faces.
}
HIDDEN void
append_faces_from_loops(
ON_SimpleArray<TrimmedFace *> &out,
const TrimmedFace *orig_face,
const LoopBooleanResult &new_loops)
{
std::vector<TrimmedFace *> o;
LoopBooleanResult combined_loops = combine_loops(orig_face, new_loops);
// make a face from each outerloop, using appropriate innerloops
for (size_t i = 0; i < combined_loops.outerloops.size(); ++i) {
o.push_back(make_face_from_loops(orig_face,
combined_loops.outerloops[i],
combined_loops.innerloops));
}
for (size_t i = 0; i < o.size(); i++) {
out.Append(o[i]);
}
}
/* Turn an open curve into a closed curve by using segments from the
* face outerloop to connect its endpoints.
*
* Returns false on failure, true otherwise.
*/
std::vector<ON_SimpleArray<ON_Curve *> >
split_face_into_loops(
const TrimmedFace *orig_face,
LinkedCurve &linked_curve)
{
std::vector<ON_SimpleArray<ON_Curve *> > out;
if (linked_curve.IsClosed()) {
ON_SimpleArray<ON_Curve *> loop;
for (int i = 0; i < orig_face->m_outerloop.Count(); ++i) {
loop.Append(orig_face->m_outerloop[i]->Duplicate());
}
out.push_back(loop);
return out;
}
/* We followed the algorithms described in:
* S. Krishnan, A. Narkhede, and D. Manocha. BOOLE: A System to Compute
* Boolean Combinations of Sculptured Solids. Technical Report TR95-008,
* Department of Computer Science, University of North Carolina, 1995.
* Appendix B: Partitioning a Simple Polygon using Non-Intersecting
* Chains.
*/
// Get the intersection points between the SSI curves and the outerloop.
ON_SimpleArray<IntersectPoint> clx_points;
bool intersects_outerloop = false;
for (int i = 0; i < orig_face->m_outerloop.Count(); i++) {
ON_SimpleArray<ON_X_EVENT> x_events;
ON_Intersect(orig_face->m_outerloop[i], linked_curve.Curve(),
x_events, INTERSECTION_TOL);
for (int j = 0; j < x_events.Count(); j++) {
IntersectPoint tmp_pt;
tmp_pt.m_pt = x_events[j].m_A[0];
tmp_pt.m_seg_t = x_events[j].m_a[0];
tmp_pt.m_curve_t = x_events[j].m_b[0];
tmp_pt.m_loop_seg = i;
clx_points.Append(tmp_pt);
if (x_events[j].m_type == ON_X_EVENT::ccx_overlap) {
tmp_pt.m_pt = x_events[j].m_A[1];
tmp_pt.m_seg_t = x_events[j].m_a[1];
tmp_pt.m_curve_t = x_events[j].m_b[1];
clx_points.Append(tmp_pt);
}
if (x_events.Count()) {
intersects_outerloop = true;
}
}
}
// can't close curves that don't partition the face
if (!intersects_outerloop || clx_points.Count() < 2) {
ON_SimpleArray<ON_Curve *> loop;
for (int i = 0; i < orig_face->m_outerloop.Count(); ++i) {
loop.Append(orig_face->m_outerloop[i]->Duplicate());
}
out.push_back(loop);
return out;
}
// rank these intersection points
clx_points.QuickSort(curve_t_compare);
for (int i = 0; i < clx_points.Count(); i++) {
clx_points[i].m_curve_pos = i;
}
// classify intersection points
ON_SimpleArray<IntersectPoint> new_pts;
double curve_min_t = linked_curve.Domain().Min();
double curve_max_t = linked_curve.Domain().Max();
for (int i = 0; i < clx_points.Count(); i++) {
bool is_first_ipt = (i == 0);
bool is_last_ipt = (i == (clx_points.Count() - 1));
IntersectPoint *ipt = &clx_points[i];
double curve_t = ipt->m_curve_t;
ON_3dPoint prev = linked_curve.PointAtStart();
if (!is_first_ipt) {
double prev_curve_t = clx_points[i - 1].m_curve_t;
prev = linked_curve.PointAt((curve_t + prev_curve_t) * .5);
}
ON_3dPoint next = linked_curve.PointAtEnd();
if (!is_last_ipt) {
double next_curve_t = clx_points[i + 1].m_curve_t;
next = linked_curve.PointAt((curve_t + next_curve_t) * .5);
}
// If the point is on the boundary, we treat it with the same
// way as it's outside.
// For example, the prev side is inside, and the next's on
// boundary, that point should be IntersectPoint::OUT, the
// same as the next's outside the loop.
// Other cases are similar.
bool prev_in, next_in;
try {
prev_in = is_point_inside_loop(prev, orig_face->m_outerloop);
next_in = is_point_inside_loop(next, orig_face->m_outerloop);
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
// not a loop
ipt->m_dir = IntersectPoint::UNSET;
continue;
}
if (is_first_ipt && ON_NearZero(curve_t - curve_min_t)) {
ipt->m_dir = next_in ? IntersectPoint::IN_HIT : IntersectPoint::OUT_HIT;
continue;
}
if (is_last_ipt && ON_NearZero(curve_t - curve_max_t)) {
ipt->m_dir = prev_in ? IntersectPoint::OUT_HIT : IntersectPoint::IN_HIT;
continue;
}
if (prev_in && next_in) {
// tangent point, both sides in, duplicate that point
new_pts.Append(*ipt);
new_pts.Last()->m_dir = IntersectPoint::TANGENT;
new_pts.Last()->m_curve_pos = ipt->m_curve_pos;
ipt->m_dir = IntersectPoint::TANGENT;
} else if (!prev_in && !next_in) {
// tangent point, both sides out, useless
ipt->m_dir = IntersectPoint::UNSET;
} else if (prev_in && !next_in) {
// transversal point, going outside
ipt->m_dir = IntersectPoint::OUT_HIT;
} else {
// transversal point, going inside
ipt->m_dir = IntersectPoint::IN_HIT;
}
}
clx_points.Append(new_pts.Count(), new_pts.Array());
clx_points.QuickSort(loop_t_compare);
// Split the outer loop.
ON_SimpleArray<ON_Curve *> outerloop_segs;
int clx_i = 0;
for (int loop_seg = 0; loop_seg < orig_face->m_outerloop.Count(); loop_seg++) {
ON_Curve *remainder = orig_face->m_outerloop[loop_seg]->Duplicate();
if (remainder == NULL) {
bu_log("ON_Curve::Duplicate() failed.\n");
return out;
}
for (; clx_i < clx_points.Count() && clx_points[clx_i].m_loop_seg == loop_seg; clx_i++) {
IntersectPoint &ipt = clx_points[clx_i];
ON_Curve *portion_before_ipt = NULL;
if (remainder) {
double start_t = remainder->Domain().Min();
double end_t = remainder->Domain().Max();
if (ON_NearZero(ipt.m_seg_t - end_t)) {
// Can't call Split() if ipt is at start (that
// case is handled by the initialization) or ipt
// is at end (handled here).
portion_before_ipt = remainder;
remainder = NULL;
} else if (!ON_NearZero(ipt.m_seg_t - start_t)) {
if (!remainder->Split(ipt.m_seg_t, portion_before_ipt, remainder)) {
bu_log("Split failed.\n");
bu_log("Domain: [%f, %f]\n", end_t, start_t);
bu_log("m_seg_t: %f\n", ipt.m_seg_t);
}
}
}
if (portion_before_ipt) {
outerloop_segs.Append(portion_before_ipt);
}
ipt.m_split_li = outerloop_segs.Count() - 1;
}
outerloop_segs.Append(remainder);
}
// Append the first element at the last to handle some special cases.
if (clx_points.Count()) {
clx_points.Append(clx_points[0]);
clx_points.Last()->m_loop_seg += orig_face->m_outerloop.Count();
for (int i = 0; i <= clx_points[0].m_split_li; i++) {
ON_Curve *dup = outerloop_segs[i]->Duplicate();
if (dup == NULL) {
bu_log("ON_Curve::Duplicate() failed.\n");
}
outerloop_segs.Append(dup);
}
clx_points.Last()->m_split_li = outerloop_segs.Count() - 1;
}
if (DEBUG_BREP_BOOLEAN) {
for (int i = 0; i < clx_points.Count(); i++) {
IntersectPoint &ipt = clx_points[i];
bu_log("clx_points[%d](count = %d): ", i, clx_points.Count());
bu_log("m_curve_pos = %d, m_dir = %d\n", ipt.m_curve_pos, ipt.m_dir);
}
}
std::stack<int> s;
for (int i = 0; i < clx_points.Count(); i++) {
if (clx_points[i].m_dir == IntersectPoint::UNSET) {
continue;
}
if (s.empty()) {
s.push(i);
continue;
}
const IntersectPoint &p = clx_points[s.top()];
const IntersectPoint &q = clx_points[i];
if (loop_t_compare(&p, &q) > 0 || q.m_split_li < p.m_split_li) {
bu_log("stack error or sort failure.\n");
bu_log("s.top() = %d, i = %d\n", s.top(), i);
bu_log("p->m_split_li = %d, q->m_split_li = %d\n", p.m_split_li, q.m_split_li);
bu_log("p->m_loop_seg = %d, q->m_loop_seg = %d\n", p.m_loop_seg, q.m_loop_seg);
bu_log("p->m_seg_t = %g, q->m_seg_t = %g\n", p.m_seg_t, q.m_seg_t);
continue;
}
if (q.m_curve_pos - p.m_curve_pos == 1 &&
q.m_dir != IntersectPoint::IN_HIT &&
p.m_dir != IntersectPoint::OUT_HIT)
{
s.pop();
} else if (p.m_curve_pos - q.m_curve_pos == 1 &&
p.m_dir != IntersectPoint::IN_HIT &&
q.m_dir != IntersectPoint::OUT_HIT)
{
s.pop();
} else {
s.push(i);
continue;
}
// need to form a new loop
ON_SimpleArray<ON_Curve *> newloop;
int curve_count = q.m_split_li - p.m_split_li;
for (int j = p.m_split_li + 1; j <= q.m_split_li; j++) {
// No need to duplicate the curve, because the pointer
// in the array 'outerloop_segs' will be moved out later.
newloop.Append(outerloop_segs[j]);
}
// The curves on the outer loop is from p to q, so the curves on the
// SSI curve should be from q to p (to form a loop)
double t1 = p.m_curve_t, t2 = q.m_curve_t;
bool need_reverse = true;
if (t1 > t2) {
std::swap(t1, t2);
need_reverse = false;
}
ON_Curve *seg_on_SSI = linked_curve.SubCurve(t1, t2);
if (seg_on_SSI == NULL) {
bu_log("sub_curve() failed.\n");
continue;
}
if (need_reverse) {
if (!seg_on_SSI->Reverse()) {
bu_log("Reverse failed.\n");
continue;
}
}
newloop.Append(seg_on_SSI);
close_small_gaps(newloop);
ON_Curve *rev_seg_on_SSI = seg_on_SSI->Duplicate();
if (!rev_seg_on_SSI || !rev_seg_on_SSI->Reverse()) {
bu_log("Reverse failed.\n");
continue;
} else {
// Update the outerloop
outerloop_segs[p.m_split_li + 1] = rev_seg_on_SSI;
int k = p.m_split_li + 2;
for (int j = q.m_split_li + 1; j < outerloop_segs.Count(); j++) {
outerloop_segs[k++] = outerloop_segs[j];
}
while (k < outerloop_segs.Count()) {
outerloop_segs[outerloop_segs.Count() - 1] = NULL;
outerloop_segs.Remove();
}
// Update m_split_li
for (int j = i + 1; j < clx_points.Count(); j++) {
clx_points[j].m_split_li -= curve_count - 1;
}
}
// append the new loop if it's valid
if (is_loop_valid(newloop, ON_ZERO_TOLERANCE)) {
ON_SimpleArray<ON_Curve *> loop;
loop.Append(newloop.Count(), newloop.Array());
out.push_back(loop);
} else {
for (int j = 0; j < newloop.Count(); j++) {
delete newloop[j];
}
}
}
// Remove the duplicated segments before the first intersection point.
if (clx_points.Count()) {
for (int i = 0; i <= clx_points[0].m_split_li; i++) {
delete outerloop_segs[0];
outerloop_segs[0] = NULL;
outerloop_segs.Remove(0);
}
}
if (!out.empty()) {
// The remaining part after splitting some parts out.
close_small_gaps(outerloop_segs);
if (is_loop_valid(outerloop_segs, ON_ZERO_TOLERANCE)) {
ON_SimpleArray<ON_Curve *> loop;
loop.Append(outerloop_segs.Count(), outerloop_segs.Array());
out.push_back(loop);
} else {
for (int i = 0; i < outerloop_segs.Count(); i++)
if (outerloop_segs[i]) {
delete outerloop_segs[i];
}
}
}
return out;
}
void
free_loops(std::vector<ON_SimpleArray<ON_Curve *> > &loops)
{
for (size_t i = 0; i < loops.size(); ++i) {
for (int j = 0; j < loops[i].Count(); ++j) {
delete loops[i][j];
loops[i][j] = NULL;
}
}
}
bool
loop_is_degenerate(const ON_SimpleArray<ON_Curve *> &loop)
{
if (loop.Count() < 1) {
return true;
}
// want sufficient distance between non-adjacent curve points
ON_Curve *loop_curve = get_loop_curve(loop);
ON_Interval dom = loop_curve->Domain();
ON_3dPoint pt1 = loop_curve->PointAt(dom.ParameterAt(.25));
ON_3dPoint pt2 = loop_curve->PointAt(dom.ParameterAt(.75));
delete loop_curve;
return pt1.DistanceTo(pt2) < INTERSECTION_TOL;
}
// It might be worth investigating the following approach to building a set of faces from the splitting
// in order to achieve robustness in the final result:
//
// A) trim the raw SSI curves with the trimming loops from both faces and get "final" curve segments in
// 3D and both 2D parametric spaces. Consolidate curves where different faces created the same curve.
// B) assemble the new 2D segments and whatever pieces are needed from the existing trimming curves to
// form new 2D loops (which must be non-self-intersecting), whose roles in A and B respectively
// would be determined by the boolean op and each face's role within it.
// C) build "representative polygons" for all the 2D loops in each face, new and old - representative in
// this case meaning that the intersection behavior of the general loops is accurately duplicated
// by the polygons, which should be assurable by identifying and using all 2D curve intersections and possibly
// horizontal and vertical tangents - and use clipper to perform the boolean ops. Using the resulting polygons,
// deduce and assemble the final trimming loops (and face or faces) created from A and B respectively.
// Note that the 2D information alone cannot be enough to decide *which* faces created from these splits
// end up in the final brep. A case to think about here is the case of two spheres intersecting -
// depending on A, the exact trimming
// loop in B may need to either define the small area as a new face, or everything BUT the small area
// as a new face - different A spheres may either almost fully contain B or just intersect it. That case
// would seem to suggest that we do need some sort of inside/outside test, since B doesn't have enough
// information to determine which face is to be saved without consulting A. Likewise, A may either save
// just the piece inside the loop or everything outside it, depending on B. This is the same situation we
// were in with the original face sets.
//
// A possible improvement here might be to calculate the best fit plane of the intersection curve and rotate
// both the faces in question and A so that that plane is centered at the origin with the normal in z+.
// In that orientation, axis aligned bounding box tests can be made that will be as informative
// as possible, and may allow many inside/outside decisions to be made without an explicit raytrace. Coplanar
// faces will have to be handled differently, but for convex cases there should be enough information to decide.
// Concave cases may require a raytrace, but there is one other possible approach - if, instead of using the
// whole brep and face bounding boxes we start with the bounding box of the intersection curve and construct
// the sub-box that 'slices' through the parent bbox to the furthest wall in the opposite direction from the
// surface normal, then see which of the two possible
// faces' bounding boxes removes the most volume from that box when subtracted, we may be able to decide
// (say, for a subtraction) which face is cutting deeper. It's not clear to me yet if such an approach would
// work or would scale to complex cases, but it may be worth thinking about.
HIDDEN ON_SimpleArray<TrimmedFace *>
split_trimmed_face(
const TrimmedFace *orig_face,
ON_ClassArray<LinkedCurve> &ssx_curves)
{
ON_SimpleArray<TrimmedFace *> out;
out.Append(orig_face->Duplicate());
if (ssx_curves.Count() == 0) {
// no curves, no splitting
return out;
}
ON_Curve *face_outerloop = get_loop_curve(orig_face->m_outerloop);
if (!face_outerloop->IsClosed()) {
// need closed outerloop
delete face_outerloop;
return out;
}
delete face_outerloop;
for (int i = 0; i < ssx_curves.Count(); ++i) {
std::vector<ON_SimpleArray<ON_Curve *> > ssx_loops;
// get current ssx curve as closed loops
if (ssx_curves[i].IsClosed()) {
ON_SimpleArray<ON_Curve *> loop;
loop.Append(ssx_curves[i].Curve()->Duplicate());
ssx_loops.push_back(loop);
} else {
ssx_loops = split_face_into_loops(orig_face, ssx_curves[i]);
}
// combine each intersection loop with the original face (or
// the previous iteration of split faces) to create new split
// faces
ON_SimpleArray<TrimmedFace *> next_out;
for (size_t j = 0; j < ssx_loops.size(); ++j) {
if (loop_is_degenerate(ssx_loops[j])) {
continue;
}
for (int k = 0; k < out.Count(); ++k) {
LoopBooleanResult intersect_loops, diff_loops;
// get the portion of the face outerloop inside the
// ssx loop
intersect_loops = loop_boolean(out[k]->m_outerloop,
ssx_loops[j], BOOLEAN_INTERSECT);
if (ssx_curves[i].IsClosed()) {
if (intersect_loops.outerloops.empty()) {
// no intersection, just keep the face as-is
next_out.Append(out[k]->Duplicate());
continue;
}
// for a naturally closed ssx curve, we also need
// the portion outside the loop
diff_loops = loop_boolean(out[k]->m_outerloop, ssx_loops[j],
BOOLEAN_DIFF);
append_faces_from_loops(next_out, out[k], diff_loops);
diff_loops.ClearInnerloops();
}
append_faces_from_loops(next_out, out[k], intersect_loops);
intersect_loops.ClearInnerloops();
}
}
free_loops(ssx_loops);
if (next_out.Count() > 0) {
// replace previous faces with the new ones
for (int j = 0; j < out.Count(); ++j) {
delete out[j];
}
out.Empty();
out.Append(next_out.Count(), next_out.Array());
}
}
for (int i = 0; i < out.Count(); ++i) {
close_small_gaps(out[i]->m_outerloop);
for (size_t j = 0; j < out[i]->m_innerloop.size(); ++j) {
close_small_gaps(out[i]->m_innerloop[j]);
}
}
if (DEBUG_BREP_BOOLEAN) {
bu_log("Split to %d faces.\n", out.Count());
for (int i = 0; i < out.Count(); i++) {
bu_log("Trimmed Face %d:\n", i);
bu_log("outerloop:\n");
ON_wString wstr;
ON_TextLog textlog(wstr);
textlog.PushIndent();
for (int j = 0; j < out[i]->m_outerloop.Count(); j++) {
textlog.Print("Curve %d\n", j);
out[i]->m_outerloop[j]->Dump(textlog);
}
if (ON_String(wstr).Array()) {
bu_log("%s", ON_String(wstr).Array());
}
for (unsigned int j = 0; j < out[i]->m_innerloop.size(); j++) {
bu_log("innerloop %d:\n", j);
ON_wString wstr2;
ON_TextLog textlog2(wstr2);
textlog2.PushIndent();
for (int k = 0; k < out[i]->m_innerloop[j].Count(); k++) {
textlog2.Print("Curve %d\n", k);
out[i]->m_innerloop[j][k]->Dump(textlog2);
}
if (ON_String(wstr2).Array()) {
bu_log("%s", ON_String(wstr2).Array());
}
}
}
}
return out;
}
HIDDEN bool
is_same_surface(const ON_Surface *surf1, const ON_Surface *surf2)
{
// Approach: Get their NURBS forms, and compare their CVs.
// If their CVs are all the same (location and weight), they are
// regarded as the same surface.
if (surf1 == NULL || surf2 == NULL) {
return false;
}
/*
// Deal with two planes, if that's what we have - in that case
// the determination can be more general than the CV comparison
ON_Plane surf1_plane, surf2_plane;
if (surf1->IsPlanar(&surf1_plane) && surf2->IsPlanar(&surf2_plane)) {
ON_3dVector surf1_normal = surf1_plane.Normal();
ON_3dVector surf2_normal = surf2_plane.Normal();
if (surf1_normal.IsParallelTo(surf2_normal) == 1) {
if (surf1_plane.DistanceTo(surf2_plane.Origin()) < ON_ZERO_TOLERANCE) {
return true;
} else {
return false;
}
} else {
return false;
}
}
*/
ON_NurbsSurface nurbs_surf1, nurbs_surf2;
if (!surf1->GetNurbForm(nurbs_surf1) || !surf2->GetNurbForm(nurbs_surf2)) {
return false;
}
if (nurbs_surf1.Degree(0) != nurbs_surf2.Degree(0)
|| nurbs_surf1.Degree(1) != nurbs_surf2.Degree(1)) {
return false;
}
if (nurbs_surf1.CVCount(0) != nurbs_surf2.CVCount(0)
|| nurbs_surf1.CVCount(1) != nurbs_surf2.CVCount(1)) {
return false;
}
for (int i = 0; i < nurbs_surf1.CVCount(0); i++) {
for (int j = 0; j < nurbs_surf2.CVCount(1); j++) {
ON_4dPoint cvA, cvB;
nurbs_surf1.GetCV(i, j, cvA);
nurbs_surf2.GetCV(i, j, cvB);
if (cvA != cvB) {
return false;
}
}
}
if (nurbs_surf1.KnotCount(0) != nurbs_surf2.KnotCount(0)
|| nurbs_surf1.KnotCount(1) != nurbs_surf2.KnotCount(1)) {
return false;
}
for (int i = 0; i < nurbs_surf1.KnotCount(0); i++) {
if (!ON_NearZero(nurbs_surf1.m_knot[0][i] - nurbs_surf2.m_knot[0][i])) {
return false;
}
}
for (int i = 0; i < nurbs_surf1.KnotCount(1); i++) {
if (!ON_NearZero(nurbs_surf1.m_knot[1][i] - nurbs_surf2.m_knot[1][i])) {
return false;
}
}
return true;
}
HIDDEN void
add_elements(ON_Brep *brep, ON_BrepFace &face, const ON_SimpleArray<ON_Curve *> &loop, ON_BrepLoop::TYPE loop_type)
{
if (!loop.Count()) {
return;
}
ON_BrepLoop &breploop = brep->NewLoop(loop_type, face);
const ON_Surface *srf = face.SurfaceOf();
// Determine whether a segment should be a seam trim, according to the
// requirements in ON_Brep::IsValid() (See opennurbs_brep.cpp)
for (int k = 0; k < loop.Count(); k++) {
ON_BOOL32 bClosed[2];
bClosed[0] = srf->IsClosed(0);
bClosed[1] = srf->IsClosed(1);
if (bClosed[0] || bClosed[1]) {
ON_Surface::ISO iso1, iso2, iso_type;
int endpt_index = -1;
iso1 = srf->IsIsoparametric(*loop[k]);
if (ON_Surface::E_iso == iso1 && bClosed[0]) {
iso_type = ON_Surface::W_iso;
endpt_index = 1;
} else if (ON_Surface::W_iso == iso1 && bClosed[0]) {
iso_type = ON_Surface::E_iso;
endpt_index = 1;
} else if (ON_Surface::S_iso == iso1 && bClosed[1]) {
iso_type = ON_Surface::N_iso;
endpt_index = 0;
} else if (ON_Surface::N_iso == iso1 && bClosed[1]) {
iso_type = ON_Surface::S_iso;
endpt_index = 0;
}
if (endpt_index != -1) {
ON_Interval side_interval;
const double side_tol = 1.0e-4;
double s0, s1;
bool seamed = false;
side_interval.Set(loop[k]->PointAtStart()[endpt_index], loop[k]->PointAtEnd()[endpt_index]);
if (((ON_Surface::N_iso == iso_type || ON_Surface::W_iso == iso_type) && side_interval.IsIncreasing())
|| ((ON_Surface::S_iso == iso_type || ON_Surface::E_iso == iso_type) && side_interval.IsDecreasing())) {
for (int i = 0; i < breploop.m_ti.Count(); i++) {
ON_BrepTrim &trim = brep->m_T[breploop.m_ti[i]];
if (ON_BrepTrim::boundary != trim.m_type) {
continue;
}
iso2 = srf->IsIsoparametric(trim);
if (iso2 != iso_type) {
continue;
}
s1 = side_interval.NormalizedParameterAt(trim.PointAtStart()[endpt_index]);
if (fabs(s1 - 1.0) > side_tol) {
continue;
}
s0 = side_interval.NormalizedParameterAt(trim.PointAtEnd()[endpt_index]);
if (fabs(s0) > side_tol) {
continue;
}
// Check 3D distances - not included in ON_Brep::IsValid().
// So with this check, we only add seam trims if their end points
// are the same within ON_ZERO_TOLERANCE. This will cause IsValid()
// reporting "they should be seam trims connected to the same edge",
// because the 2D tolerance (side_tol) are hardcoded to 1.0e-4.
// We still add this check because we treat two vertexes to be the
// same only if their distance < ON_ZERO_TOLERANCE. (Maybe 3D dist
// should also be added to ON_Brep::IsValid()?)
if (srf->PointAt(trim.PointAtStart().x, trim.PointAtStart().y).DistanceTo(
srf->PointAt(loop[k]->PointAtEnd().x, loop[k]->PointAtEnd().y)) >= ON_ZERO_TOLERANCE) {
continue;
}
if (srf->PointAt(trim.PointAtEnd().x, trim.PointAtEnd().y).DistanceTo(
srf->PointAt(loop[k]->PointAtStart().x, loop[k]->PointAtStart().y)) >= ON_ZERO_TOLERANCE) {
continue;
}
// We add another checking, which is not included in ON_Brep::IsValid()
// - they should be iso boundaries of the surface.
double s2 = srf->Domain(1 - endpt_index).NormalizedParameterAt(loop[k]->PointAtStart()[1 - endpt_index]);
double s3 = srf->Domain(1 - endpt_index).NormalizedParameterAt(trim.PointAtStart()[1 - endpt_index]);
if ((fabs(s2 - 1.0) < side_tol && fabs(s3) < side_tol) ||
(fabs(s2) < side_tol && fabs(s3 - 1.0) < side_tol)) {
// Find a trim that should share the same edge
int ti = brep->AddTrimCurve(loop[k]);
ON_BrepTrim &newtrim = brep->NewTrim(brep->m_E[trim.m_ei], true, breploop, ti);
// newtrim.m_type = ON_BrepTrim::seam;
newtrim.m_tolerance[0] = newtrim.m_tolerance[1] = MAX_FASTF;
seamed = true;
break;
}
}
if (seamed) {
continue;
}
}
}
}
ON_Curve *c3d = NULL;
// First, try the ON_Surface::Pushup() method.
// If Pushup() does not succeed, use sampling method.
c3d = face.SurfaceOf()->Pushup(*(loop[k]), INTERSECTION_TOL);
if (!c3d) {
ON_3dPointArray ptarray(101);
for (int l = 0; l <= 100; l++) {
ON_3dPoint pt2d;
pt2d = loop[k]->PointAt(loop[k]->Domain().ParameterAt(l / 100.0));
ptarray.Append(face.SurfaceOf()->PointAt(pt2d.x, pt2d.y));
}
c3d = new ON_PolylineCurve(ptarray);
}
if (c3d->BoundingBox().Diagonal().Length() < ON_ZERO_TOLERANCE) {
// The trim is singular
int i;
ON_3dPoint vtx = c3d->PointAtStart();
for (i = brep->m_V.Count() - 1; i >= 0; i--) {
if (brep->m_V[i].Point().DistanceTo(vtx) < ON_ZERO_TOLERANCE) {
break;
}
}
if (i < 0) {
i = brep->m_V.Count();
brep->NewVertex(c3d->PointAtStart(), 0.0);
}
int ti = brep->AddTrimCurve(loop[k]);
ON_BrepTrim &trim = brep->NewSingularTrim(brep->m_V[i], breploop, srf->IsIsoparametric(*loop[k]), ti);
trim.m_tolerance[0] = trim.m_tolerance[1] = MAX_FASTF;
delete c3d;
continue;
}
ON_2dPoint start = loop[k]->PointAtStart(), end = loop[k]->PointAtEnd();
int start_idx, end_idx;
// Get the start vertex index
if (k > 0) {
start_idx = brep->m_T.Last()->m_vi[1];
} else {
ON_3dPoint vtx = face.SurfaceOf()->PointAt(start.x, start.y);
int i;
for (i = 0; i < brep->m_V.Count(); i++) {
if (brep->m_V[i].Point().DistanceTo(vtx) < ON_ZERO_TOLERANCE) {
break;
}
}
start_idx = i;
if (i == brep->m_V.Count()) {
brep->NewVertex(vtx, 0.0);
}
}
// Get the end vertex index
if (c3d->IsClosed()) {
end_idx = start_idx;
} else {
ON_3dPoint vtx = face.SurfaceOf()->PointAt(end.x, end.y);
int i;
for (i = 0; i < brep->m_V.Count(); i++) {
if (brep->m_V[i].Point().DistanceTo(vtx) < ON_ZERO_TOLERANCE) {
break;
}
}
end_idx = i;
if (i == brep->m_V.Count()) {
brep->NewVertex(vtx, 0.0);
}
}
brep->AddEdgeCurve(c3d);
int ti = brep->AddTrimCurve(loop[k]);
ON_BrepEdge &edge = brep->NewEdge(brep->m_V[start_idx], brep->m_V[end_idx],
brep->m_C3.Count() - 1, (const ON_Interval *)0, MAX_FASTF);
ON_BrepTrim &trim = brep->NewTrim(edge, 0, breploop, ti);
trim.m_tolerance[0] = trim.m_tolerance[1] = MAX_FASTF;
}
}
HIDDEN bool
is_point_on_brep_surface(const ON_3dPoint &pt, const ON_Brep *brep, ON_SimpleArray<Subsurface *> &surf_tree)
{
// Decide whether a point is on a brep's surface.
// Basic approach: use PSI on the point with all the surfaces.
if (brep == NULL || pt.IsUnsetPoint()) {
bu_log("is_point_on_brep_surface(): brep == NULL || pt.IsUnsetPoint()\n");
return false;
}
if (surf_tree.Count() != brep->m_S.Count()) {
bu_log("is_point_on_brep_surface(): surf_tree.Count() != brep->m_S.Count()\n");
return false;
}
ON_BoundingBox bbox = brep->BoundingBox();
bbox.m_min -= ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
bbox.m_max += ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
if (!bbox.IsPointIn(pt)) {
return false;
}
for (int i = 0; i < brep->m_F.Count(); i++) {
const ON_BrepFace &face = brep->m_F[i];
const ON_Surface *surf = face.SurfaceOf();
ON_ClassArray<ON_PX_EVENT> px_event;
if (!ON_Intersect(pt, *surf, px_event, INTERSECTION_TOL, 0, 0, surf_tree[face.m_si])) {
continue;
}
// Get the trimming curves of the face, and determine whether the
// points are inside the outerloop
ON_SimpleArray<ON_Curve *> outerloop;
const ON_BrepLoop &loop = brep->m_L[face.m_li[0]]; // outerloop only
for (int j = 0; j < loop.m_ti.Count(); j++) {
outerloop.Append(brep->m_C2[brep->m_T[loop.m_ti[j]].m_c2i]);
}
ON_2dPoint pt2d(px_event[0].m_b[0], px_event[0].m_b[1]);
try {
if (!is_point_outside_loop(pt2d, outerloop)) {
return true;
}
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
}
}
return false;
}
HIDDEN bool
is_point_inside_brep(const ON_3dPoint &pt, const ON_Brep *brep, ON_SimpleArray<Subsurface *> &surf_tree)
{
// Decide whether a point is inside a brep's surface.
// Basic approach: intersect a ray with the brep, and count the number of
// intersections (like the raytrace)
// Returns true (inside) or false (outside) provided the pt is not on the
// surfaces. (See also is_point_on_brep_surface())
if (brep == NULL || pt.IsUnsetPoint()) {
bu_log("is_point_inside_brep(): brep == NULL || pt.IsUnsetPoint()\n");
return false;
}
if (surf_tree.Count() != brep->m_S.Count()) {
bu_log("is_point_inside_brep(): surf_tree.Count() != brep->m_S.Count()\n");
return false;
}
ON_BoundingBox bbox = brep->BoundingBox();
bbox.m_min -= ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
bbox.m_max += ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
if (!bbox.IsPointIn(pt)) {
return false;
}
ON_3dVector diag = bbox.Diagonal() * 1.5; // Make it even longer
ON_LineCurve line(pt, pt + diag); // pt + diag should be outside, if pt
// is inside the bbox
ON_3dPointArray isect_pt;
for (int i = 0; i < brep->m_F.Count(); i++) {
const ON_BrepFace &face = brep->m_F[i];
const ON_Surface *surf = face.SurfaceOf();
ON_SimpleArray<ON_X_EVENT> x_event;
if (!ON_Intersect(&line, surf, x_event, INTERSECTION_TOL, 0.0, 0, 0, 0, 0, 0, surf_tree[face.m_si])) {
continue;
}
// Get the trimming curves of the face, and determine whether the
// points are inside the outerloop
ON_SimpleArray<ON_Curve *> outerloop;
const ON_BrepLoop &loop = brep->m_L[face.m_li[0]]; // outerloop only
for (int j = 0; j < loop.m_ti.Count(); j++) {
outerloop.Append(brep->m_C2[brep->m_T[loop.m_ti[j]].m_c2i]);
}
try {
for (int j = 0; j < x_event.Count(); j++) {
ON_2dPoint pt2d(x_event[j].m_b[0], x_event[j].m_b[1]);
if (!is_point_outside_loop(pt2d, outerloop)) {
isect_pt.Append(x_event[j].m_B[0]);
}
if (x_event[j].m_type == ON_X_EVENT::ccx_overlap) {
pt2d = ON_2dPoint(x_event[j].m_b[2], x_event[j].m_b[3]);
if (!is_point_outside_loop(pt2d, outerloop)) {
isect_pt.Append(x_event[j].m_B[1]);
}
}
}
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
}
}
// Remove duplications
ON_3dPointArray pt_no_dup;
for (int i = 0; i < isect_pt.Count(); i++) {
int j;
for (j = 0; j < pt_no_dup.Count(); j++) {
if (isect_pt[i].DistanceTo(pt_no_dup[j]) < INTERSECTION_TOL) {
break;
}
}
if (j == pt_no_dup.Count()) {
// No duplication, append to the array
pt_no_dup.Append(isect_pt[i]);
}
}
return pt_no_dup.Count() % 2 != 0;
}
HIDDEN bool
is_point_inside_trimmed_face(const ON_2dPoint &pt, const TrimmedFace *tface)
{
bool inside = false;
if (is_point_inside_loop(pt, tface->m_outerloop)) {
inside = true;
for (size_t i = 0; i < tface->m_innerloop.size(); ++i) {
if (!is_point_outside_loop(pt, tface->m_innerloop[i])) {
inside = false;
break;
}
}
}
return inside;
}
// TODO: For faces that have most of their area trimmed away, this is
// a very inefficient algorithm. If the grid approach doesn't work
// after a small number of samples, we should switch to an alternative
// algorithm, such as sampling around points on the inner loops.
HIDDEN ON_2dPoint
get_point_inside_trimmed_face(const TrimmedFace *tface)
{
const int GP_MAX_STEPS = 8; // must be a power of two
ON_PolyCurve polycurve;
if (!is_loop_valid(tface->m_outerloop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("face_brep_location(): invalid outerloop.\n");
}
ON_BoundingBox bbox = polycurve.BoundingBox();
double u_len = bbox.m_max.x - bbox.m_min.x;
double v_len = bbox.m_max.y - bbox.m_min.y;
ON_2dPoint test_pt2d;
bool found = false;
for (int steps = 1; steps <= GP_MAX_STEPS && !found; steps *= 2) {
double u_halfstep = u_len / (steps * 2.0);
double v_halfstep = v_len / (steps * 2.0);
for (int i = 0; i < steps && !found; ++i) {
test_pt2d.x = bbox.m_min.x + u_halfstep * (1 + 2 * i);
for (int j = 0; j < steps && !found; ++j) {
test_pt2d.y = bbox.m_min.y + v_halfstep * (1 + 2 * j);
found = is_point_inside_trimmed_face(test_pt2d, tface);
}
}
}
if (!found) {
throw AlgorithmError("Cannot find a point inside this trimmed face. Aborted.\n");
}
return test_pt2d;
}
enum {
OUTSIDE_BREP,
INSIDE_BREP,
ON_BREP_SURFACE
};
// Returns the location of the face with respect to the brep.
//
// Throws InvalidGeometry if given invalid arguments.
// Throws AlgorithmError if a point inside the TrimmedFace can't be
// found for testing.
HIDDEN int
face_brep_location(const TrimmedFace *tface, const ON_Brep *brep, ON_SimpleArray<Subsurface *> &surf_tree)
{
if (tface == NULL || brep == NULL) {
throw InvalidGeometry("face_brep_location(): given NULL argument.\n");
}
const ON_BrepFace *bface = tface->m_face;
if (bface == NULL) {
throw InvalidGeometry("face_brep_location(): TrimmedFace has NULL face.\n");
}
ON_BoundingBox brep2box = brep->BoundingBox();
brep2box.m_min -= ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
brep2box.m_max += ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
if (!bface->BoundingBox().Intersection(brep2box)) {
return OUTSIDE_BREP;
}
if (tface->m_outerloop.Count() == 0) {
throw InvalidGeometry("face_brep_location(): the input TrimmedFace is not trimmed.\n");
}
ON_PolyCurve polycurve;
if (!is_loop_valid(tface->m_outerloop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("face_brep_location(): invalid outerloop.\n");
}
ON_2dPoint test_pt2d = get_point_inside_trimmed_face(tface);
ON_3dPoint test_pt3d = tface->m_face->PointAt(test_pt2d.x, test_pt2d.y);
if (DEBUG_BREP_BOOLEAN) {
bu_log("valid test point: (%g, %g, %g)\n", test_pt3d.x, test_pt3d.y, test_pt3d.z);
}
if (is_point_on_brep_surface(test_pt3d, brep, surf_tree)) {
// because the overlap parts will be split out as separated trimmed
// faces, if one point on a trimmed face is on the brep's surface,
// the whole trimmed face should be on the surface
return ON_BREP_SURFACE;
}
return is_point_inside_brep(test_pt3d, brep, surf_tree) ? INSIDE_BREP : OUTSIDE_BREP;
}
HIDDEN ON_ClassArray<ON_SimpleArray<SSICurve> >
get_face_intersection_curves(
ON_SimpleArray<Subsurface *> &surf_tree1,
ON_SimpleArray<Subsurface *> &surf_tree2,
const ON_Brep *brep1,
const ON_Brep *brep2,
op_type operation)
{
std::vector<Subsurface *> st1, st2;
std::set<int> unused1, unused2;
std::set<int> finalform1, finalform2;
ON_ClassArray<ON_SimpleArray<SSICurve> > curves_array;
int face_count1 = brep1->m_F.Count();
int face_count2 = brep2->m_F.Count();
int surf_count1 = brep1->m_S.Count();
int surf_count2 = brep2->m_S.Count();
// We're not well set up currently to handle a situation where
// one of the breps has no faces - don't try. Also make sure
// we don't have too many faces.
if (!face_count1 || !face_count2 || ((face_count1 + face_count2) < 0))
return curves_array;
if (!surf_count1 || !surf_count2 || ((surf_count1 + surf_count2) < 0))
return curves_array;
/* Depending on the operation type and the bounding box behaviors, we
* can sometimes decide immediately whether a face will end up in the
* final brep or will have no role in the intersections - do that
* categorization up front */
for (int i = 0; i < face_count1 + face_count2; i++) {
const ON_BrepFace &face = i < face_count1 ? brep1->m_F[i] : brep2->m_F[i - face_count1];
const ON_Brep *brep = i < face_count1 ? brep2 : brep1;
std::set<int> *unused = i < face_count1 ? &unused1 : &unused2;
std::set<int> *intact = i < face_count1 ? &finalform1 : &finalform2;
int curr_index = i < face_count1 ? i : i - face_count1;
if (face.BoundingBox().MinimumDistanceTo(brep->BoundingBox()) > INTERSECTION_TOL) {
switch (operation) {
case BOOLEAN_UNION:
intact->insert(curr_index);
break;
case BOOLEAN_DIFF:
if (i < face_count1) {
intact->insert(curr_index);
}
if (i >= face_count1) {
unused->insert(curr_index);
}
break;
case BOOLEAN_INTERSECT:
unused->insert(curr_index);
break;
default:
throw InvalidBooleanOperation("Error - unknown "
"boolean operation\n");
}
}
}
// For the faces that we can't rule out, there are several possible roles they can play:
//
// 1. Fully utilized in the new brep
// 2. Changed into a new set of faces by intersections, each of which must be evaluated
// 3. Fully discarded by the new brep
//
// We won't be able to distinguish between 1 and 3 at this stage, but we can narrow in
// on which faces might fall into category 2 and what faces they might interact with.
std::set<std::pair<int, int> > intersection_candidates;
for (int i = 0; i < face_count1; i++) {
if (unused1.find(i) == unused1.end() && finalform1.find(i) == finalform1.end()) {
for (int j = 0; j < face_count2; j++) {
if (unused2.find(j) == unused2.end() && finalform2.find(j) == finalform2.end()) {
// If the two faces don't interact according to their bounding boxes,
// they won't be a source of events - otherwise, they must be checked.
fastf_t face_dist = brep1->m_F[i].BoundingBox().MinimumDistanceTo(brep2->m_F[j].BoundingBox());
if (face_dist <= INTERSECTION_TOL) {
intersection_candidates.insert(std::pair<int, int>(i, j));
}
}
}
}
}
// For those not in category 2 an inside/outside test on the breps combined with the boolean op
// should be enough to decide the issue, but there is a problem. If *all* faces of a brep are
// inside the other brep and the operation is a subtraction, we don't want a "floating" inside-out
// brep volume inside the outer volume and topologically isolated. Normally this is handled by
// creating a face that connects the outer and inner shells, but this is potentially a non-trivial
// operation. The only thing that comes immediately to mind is to find the center point of the
// bounding box of the inner brep, create a plane using that point and the z+ unit vector for a normal, and
// cut both breps in half with that plane to form four new breps and two new subtraction problems.
//
// More broadly, this is a problem - unioning two half-spheres with a sphere subtracted out of their
// respective centers will end up with isolated surfaces in the middle of the union unless the routines
// know they must keep one of the coplanar faces in order to topologically connect the middle. However,
// in the case where there is no center sphere the central face should be removed. It may be that the
// condition to satisfy for removal is no interior trimming loops on the face.
//
//
// Also worth thinking about - would it be possible to then do edge comparisons to
// determine which of the "fully used/fully non-used" faces are needed?
if (DEBUG_BREP_BOOLEAN) {
//bu_log("Summary of brep status: \n unused1: %zd\n unused2: %zd\n finalform1: %zd\n finalform2 %zd\nintersection_candidates(%zd):\n", unused1.size(), unused2.size(), finalform1.size(), finalform2.size(), intersection_candidates.size());
for (std::set<std::pair<int, int> >::iterator it = intersection_candidates.begin(); it != intersection_candidates.end(); ++it) {
bu_log(" (%d, %d)\n", (*it).first, (*it).second);
}
}
for (int i = 0; i < surf_count1; i++) {
Subsurface *ss = new Subsurface(brep1->m_S[i]->Duplicate());
st1.push_back(ss);
}
for (int i = 0; i < surf_count2; i++) {
Subsurface *ss = new Subsurface(brep2->m_S[i]->Duplicate());
st2.push_back(ss);
}
curves_array.SetCapacity(face_count1 + face_count2);
// count must equal capacity for array copy to work as expected
// when the result of the function is assigned
curves_array.SetCount(curves_array.Capacity());
// calculate intersection curves
for (int i = 0; i < face_count1; i++) {
if ((int)st1.size() < brep1->m_F[i].m_si + 1)
continue;
for (int j = 0; j < face_count2; j++) {
if (intersection_candidates.find(std::pair<int, int>(i, j)) != intersection_candidates.end()) {
ON_Surface *surf1, *surf2;
ON_ClassArray<ON_SSX_EVENT> events;
int results = 0;
surf1 = brep1->m_S[brep1->m_F[i].m_si];
surf2 = brep2->m_S[brep2->m_F[j].m_si];
if (is_same_surface(surf1, surf2)) {
continue;
}
if (surf_tree2.Count() < brep2->m_F[j].m_si + 1)
continue;
// Possible enhancement: Some faces may share the same surface.
// We can store the result of SSI to avoid re-computation.
results = ON_Intersect(surf1,
surf2,
events,
INTERSECTION_TOL,
0.0,
0.0,
NULL,
NULL,
NULL,
NULL,
st1[brep1->m_F[i].m_si],
st2[brep2->m_F[j].m_si]);
if (results <= 0) {
continue;
}
dplot->SSX(events, brep1, brep1->m_F[i].m_si, brep2, brep2->m_F[j].m_si);
dplot->WriteLog();
ON_SimpleArray<ON_Curve *> face1_curves, face2_curves;
for (int k = 0; k < events.Count(); k++) {
if (events[k].m_type == ON_SSX_EVENT::ssx_tangent ||
events[k].m_type == ON_SSX_EVENT::ssx_transverse ||
events[k].m_type == ON_SSX_EVENT::ssx_overlap)
{
ON_SimpleArray<ON_Curve *> subcurves_on1, subcurves_on2;
get_subcurves_inside_faces(subcurves_on1,
subcurves_on2, brep1, brep2, i, j, &events[k]);
for (int l = 0; l < subcurves_on1.Count(); ++l) {
SSICurve ssi_on1;
ssi_on1.m_curve = subcurves_on1[l];
curves_array[i].Append(ssi_on1);
face1_curves.Append(subcurves_on1[l]);
}
for (int l = 0; l < subcurves_on2.Count(); ++l) {
SSICurve ssi_on2;
ssi_on2.m_curve = subcurves_on2[l];
curves_array[face_count1 + j].Append(ssi_on2);
face2_curves.Append(subcurves_on2[l]);
}
}
}
dplot->ClippedFaceCurves(surf1, surf2, face1_curves, face2_curves);
dplot->WriteLog();
if (DEBUG_BREP_BOOLEAN) {
// Look for coplanar faces
ON_Plane surf1_plane, surf2_plane;
if (surf1->IsPlanar(&surf1_plane) && surf2->IsPlanar(&surf2_plane)) {
/* We already checked for disjoint above, so the only remaining question is the normals */
if (surf1_plane.Normal().IsParallelTo(surf2_plane.Normal())) {
bu_log("Faces brep1->%d and brep2->%d are coplanar and intersecting\n", i, j);
}
}
}
}
}
}
for (size_t i = 0; i < st1.size(); i++) {
surf_tree1.Append(st1[i]);
}
for (size_t i = 0; i < st2.size(); i++) {
surf_tree2.Append(st2[i]);
}
return curves_array;
}
HIDDEN ON_SimpleArray<ON_Curve *>get_face_trim_loop(const ON_Brep *brep, int face_loop_index)
{
const ON_BrepLoop &loop = brep->m_L[face_loop_index];
const ON_SimpleArray<int> &trim_index = loop.m_ti;
ON_SimpleArray<ON_Curve *> face_trim_loop;
for (int i = 0; i < trim_index.Count(); ++i) {
ON_Curve *curve2d = brep->m_C2[brep->m_T[trim_index[i]].m_c2i];
face_trim_loop.Append(curve2d->Duplicate());
}
return face_trim_loop;
}
HIDDEN ON_SimpleArray<TrimmedFace *>
get_trimmed_faces(const ON_Brep *brep)
{
std::vector<TrimmedFace *> trimmed_faces;
int face_count = brep->m_F.Count();
for (int i = 0; i < face_count; i++) {
const ON_BrepFace &face = brep->m_F[i];
const ON_SimpleArray<int> &loop_index = face.m_li;
if (loop_index.Count() <= 0) {
continue;
}
TrimmedFace *trimmed_face = new TrimmedFace();
trimmed_face->m_face = &face;
ON_SimpleArray<ON_Curve *> index_loop = get_face_trim_loop(brep, loop_index[0]);
trimmed_face->m_outerloop = index_loop;
for (int j = 1; j < loop_index.Count(); j++) {
index_loop = get_face_trim_loop(brep, loop_index[j]);
trimmed_face->m_innerloop.push_back(index_loop);
}
trimmed_faces.push_back(trimmed_face);
}
ON_SimpleArray<TrimmedFace *> tf;
for (size_t i = 0; i < trimmed_faces.size(); i++) {
tf.Append(trimmed_faces[i]);
}
return tf;
}
HIDDEN void
categorize_trimmed_faces(
ON_ClassArray<ON_SimpleArray<TrimmedFace *> > &trimmed_faces,
const ON_Brep *brep1,
const ON_Brep *brep2,
ON_SimpleArray<Subsurface *> &surf_tree1,
ON_SimpleArray<Subsurface *> &surf_tree2,
op_type operation)
{
int face_count1 = brep1->m_F.Count();
for (int i = 0; i < trimmed_faces.Count(); i++) {
/* Perform inside-outside test to decide whether the trimmed face should
* be used in the final b-rep structure or not.
* Different operations should be dealt with accordingly.
* Use connectivity graphs (optional) which represents the topological
* structure of the b-rep. This can reduce time-consuming inside-outside
* tests.
*/
const ON_SimpleArray<TrimmedFace *> &splitted = trimmed_faces[i];
const ON_Brep *another_brep = i >= face_count1 ? brep1 : brep2;
ON_SimpleArray<Subsurface *> &surf_tree = i >= face_count1 ? surf_tree1 : surf_tree2;
for (int j = 0; j < splitted.Count(); j++) {
if (splitted[j]->m_belong_to_final != TrimmedFace::UNKNOWN) {
// Visited before, don't need to test again
continue;
}
int face_location = -1;
try {
face_location = face_brep_location(splitted[j], another_brep, surf_tree);
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
} catch (AlgorithmError &e) {
bu_log("%s", e.what());
}
if (face_location < 0) {
if (DEBUG_BREP_BOOLEAN) {
bu_log("Whether the trimmed face is inside/outside is unknown.\n");
}
splitted[j]->m_belong_to_final = TrimmedFace::NOT_BELONG;
continue;
}
splitted[j]->m_rev = false;
splitted[j]->m_belong_to_final = TrimmedFace::NOT_BELONG;
switch (face_location) {
case INSIDE_BREP:
if (operation == BOOLEAN_INTERSECT ||
operation == BOOLEAN_XOR ||
(operation == BOOLEAN_DIFF && i >= face_count1))
{
splitted[j]->m_belong_to_final = TrimmedFace::BELONG;
}
if (operation == BOOLEAN_DIFF || operation == BOOLEAN_XOR) {
splitted[j]->m_rev = true;
}
break;
case OUTSIDE_BREP:
if (operation == BOOLEAN_UNION ||
operation == BOOLEAN_XOR ||
(operation == BOOLEAN_DIFF && i < face_count1))
{
splitted[j]->m_belong_to_final = TrimmedFace::BELONG;
}
break;
case ON_BREP_SURFACE:
// get a 3d point on the face
ON_2dPoint face_pt2d = get_point_inside_trimmed_face(splitted[j]);
ON_3dPoint face_pt3d = splitted[j]->m_face->PointAt(face_pt2d.x, face_pt2d.y);
// find the matching point on the other brep
ON_3dPoint brep_pt2d;
const ON_Surface *brep_surf;
bool found = false;
for (int fi = 0; fi < another_brep->m_F.Count(); ++fi) {
const ON_BrepFace &face = another_brep->m_F[fi];
brep_surf = face.SurfaceOf();
ON_ClassArray<ON_PX_EVENT> px_event;
if (ON_Intersect(face_pt3d, *brep_surf, px_event,
INTERSECTION_TOL, 0, 0, surf_tree[face.m_si]))
{
found = true;
brep_pt2d = px_event[0].m_b;
break;
}
}
if (found) {
// compare normals of surfaces at shared point
ON_3dVector brep_norm, face_norm;
brep_surf->EvNormal(brep_pt2d.x, brep_pt2d.y, brep_norm);
splitted[j]->m_face->SurfaceOf()->EvNormal(face_pt2d.x, face_pt2d.y, face_norm);
double dot = ON_DotProduct(brep_norm, face_norm);
bool same_direction = false;
if (dot > 0) {
// normals appear to have same direction
same_direction = true;
}
if ((operation == BOOLEAN_UNION && same_direction) ||
(operation == BOOLEAN_INTERSECT && same_direction) ||
(operation == BOOLEAN_DIFF && !same_direction && i < face_count1))
{
splitted[j]->m_belong_to_final = TrimmedFace::BELONG;
}
}
// TODO: Actually only one of them is needed in the final brep structure
}
if (DEBUG_BREP_BOOLEAN) {
bu_log("The trimmed face is %s the other brep.",
(face_location == INSIDE_BREP) ? "inside" :
((face_location == OUTSIDE_BREP) ? "outside" : "on the surface of"));
}
}
}
}
HIDDEN ON_ClassArray<ON_SimpleArray<TrimmedFace *> >
get_evaluated_faces(const ON_Brep *brep1, const ON_Brep *brep2, op_type operation)
{
ON_SimpleArray<Subsurface *> surf_tree1, surf_tree2;
int face_count1 = brep1->m_F.Count();
int face_count2 = brep2->m_F.Count();
// check for face counts high enough to cause overflow
if ((face_count1 + face_count2) < 0)
return ON_ClassArray<ON_SimpleArray<TrimmedFace *> > ();
ON_ClassArray<ON_SimpleArray<SSICurve> > curves_array =
get_face_intersection_curves(surf_tree1, surf_tree2, brep1, brep2, operation);
ON_SimpleArray<TrimmedFace *> brep1_faces, brep2_faces;
brep1_faces = get_trimmed_faces(brep1);
brep2_faces = get_trimmed_faces(brep2);
ON_SimpleArray<TrimmedFace *> original_faces = brep1_faces;
for (int i = 0; i < brep2_faces.Count(); ++i) {
original_faces.Append(brep2_faces[i]);
}
if (original_faces.Count() != face_count1 + face_count2) {
throw GeometryGenerationError("ON_Boolean() Error: TrimmedFace"
" generation failed.\n");
}
// split the surfaces with the intersection curves
ON_ClassArray<ON_SimpleArray<TrimmedFace *> > trimmed_faces;
for (int i = 0; i < original_faces.Count(); i++) {
TrimmedFace *first = original_faces[i];
ON_ClassArray<LinkedCurve> linked_curves = link_curves(curves_array[i]);
dplot->LinkedCurves(first->m_face->SurfaceOf(), linked_curves);
dplot->WriteLog();
ON_SimpleArray<TrimmedFace *> splitted = split_trimmed_face(first, linked_curves);
trimmed_faces.Append(splitted);
// Delete the curves passed in.
// Only the copies of them will be used later.
for (int j = 0; j < linked_curves.Count(); j++) {
for (int k = 0; k < linked_curves[j].m_ssi_curves.Count(); k++) {
if (linked_curves[j].m_ssi_curves[k].m_curve) {
delete linked_curves[j].m_ssi_curves[k].m_curve;
linked_curves[j].m_ssi_curves[k].m_curve = NULL;
}
}
}
}
if (trimmed_faces.Count() != original_faces.Count()) {
throw GeometryGenerationError("ON_Boolean() Error: "
"trimmed_faces.Count() != original_faces.Count()\n");
}
for (int i = 0; i < original_faces.Count(); i++) {
delete original_faces[i];
original_faces[i] = NULL;
}
categorize_trimmed_faces(trimmed_faces, brep1, brep2, surf_tree1, surf_tree2, operation);
dplot->SplitFaces(trimmed_faces);
dplot->WriteLog();
for (int i = 0; i < surf_tree1.Count(); i++) {
delete surf_tree1[i];
}
for (int i = 0; i < surf_tree2.Count(); i++) {
delete surf_tree2[i];
}
return trimmed_faces;
}
HIDDEN void
standardize_loop_orientations(ON_Brep *brep)
{
std::map<int, int> reversed_curve2d, reversed_edge;
for (int face_idx = 0; face_idx < brep->m_F.Count(); ++face_idx) {
const ON_BrepFace &eb_face = brep->m_F[face_idx];
for (int loop_idx = 0; loop_idx < eb_face.LoopCount(); ++loop_idx) {
const ON_BrepLoop &face_loop = brep->m_L[eb_face.m_li[loop_idx]];
if (face_loop.m_type != ON_BrepLoop::outer &&
face_loop.m_type != ON_BrepLoop::inner) {
continue;
}
int loop_direction = brep->LoopDirection(face_loop);
if ((loop_direction == LOOP_DIRECTION_CCW && face_loop.m_type == ON_BrepLoop::inner) ||
(loop_direction == LOOP_DIRECTION_CW && face_loop.m_type == ON_BrepLoop::outer))
{
// found reversed loop
int brep_li = eb_face.m_li[loop_idx];
ON_BrepLoop &reversed_loop = brep->m_L[brep_li];
// reverse all the loop's curves
for (int trim_idx = 0; trim_idx < reversed_loop.TrimCount(); ++trim_idx) {
ON_BrepTrim *trim = reversed_loop.Trim(trim_idx);
// Replace trim curve2d with a reversed copy.
// We'll use a previously made curve, or else
// make a new one.
if (reversed_curve2d.find(trim->m_c2i) != reversed_curve2d.end()) {
trim->ChangeTrimCurve(reversed_curve2d[trim->m_c2i]);
} else {
ON_Curve *curve_copy = trim->TrimCurveOf()->DuplicateCurve();
int copy_c2i = brep->AddTrimCurve(curve_copy);
reversed_curve2d[trim->m_c2i] = copy_c2i;
trim->ChangeTrimCurve(copy_c2i);
trim->Reverse();
}
// Replace trim edge with a reversed copy.
// We'll use a previously made edge, or else
// make a new one.
if (reversed_edge.find(trim->m_ei) != reversed_edge.end()) {
trim->RemoveFromEdge(false, false);
trim->AttachToEdge(reversed_edge[trim->m_ei], trim->m_bRev3d);
} else {
ON_BrepEdge *edge = trim->Edge();
ON_BrepVertex &v_start = *edge->Vertex(0);
ON_BrepVertex &v_end = *edge->Vertex(1);
ON_Interval dom = edge->ProxyCurveDomain();
ON_Curve *curve_copy = trim->EdgeCurveOf()->DuplicateCurve();
int copy_c3i = brep->AddEdgeCurve(curve_copy);
ON_BrepEdge &edge_copy = brep->NewEdge(v_start,
v_end, copy_c3i, &dom, edge->m_tolerance);
reversed_edge[trim->m_ei] = copy_c3i;
trim->RemoveFromEdge(false, false);
trim->AttachToEdge(edge_copy.m_edge_index, trim->m_bRev3d);
trim->Edge()->Reverse();
}
}
// need to reverse the order of trims in the loop
// too so they appear continuous
reversed_loop.m_ti.Reverse();
}
}
}
}
int
ON_Boolean(ON_Brep *evaluated_brep, const ON_Brep *brep1, const ON_Brep *brep2, op_type operation)
{
static int calls = 0;
++calls;
std::ostringstream prefix;
prefix << "bool" << calls;
dplot = new DebugPlot(prefix.str().c_str());
dplot->Surfaces(brep1, brep2);
dplot->WriteLog();
ON_ClassArray<ON_SimpleArray<TrimmedFace *> > trimmed_faces;
try {
/* Deal with the trivial cases up front */
if (brep1->BoundingBox().MinimumDistanceTo(brep2->BoundingBox()) > ON_ZERO_TOLERANCE) {
switch (operation) {
case BOOLEAN_UNION:
evaluated_brep->Append(*brep1);
evaluated_brep->Append(*brep2);
break;
case BOOLEAN_DIFF:
evaluated_brep->Append(*brep1);
break;
case BOOLEAN_INTERSECT:
return 0;
break;
default:
throw InvalidBooleanOperation("Error - unknown boolean operation\n");
}
evaluated_brep->ShrinkSurfaces();
evaluated_brep->Compact();
dplot->WriteLog();
return 0;
}
trimmed_faces = get_evaluated_faces(brep1, brep2, operation);
} catch (InvalidBooleanOperation &e) {
bu_log("%s", e.what());
dplot->WriteLog();
return -1;
} catch (GeometryGenerationError &e) {
bu_log("%s", e.what());
dplot->WriteLog();
return -1;
}
int face_count1 = brep1->m_F.Count();
int face_count2 = brep2->m_F.Count();
// check for face counts high enough to cause overflow
if ((face_count1 + face_count2) < 0)
return -1;
for (int i = 0; i < trimmed_faces.Count(); i++) {
const ON_SimpleArray<TrimmedFace *> &splitted = trimmed_faces[i];
const ON_Surface *surf = splitted.Count() ? splitted[0]->m_face->SurfaceOf() : NULL;
bool added = false;
for (int j = 0; j < splitted.Count(); j++) {
TrimmedFace *t_face = splitted[j];
if (t_face->m_belong_to_final == TrimmedFace::BELONG) {
// Add the surfaces, faces, loops, trims, vertices, edges, etc.
// to the brep structure.
if (!added) {
ON_Surface *new_surf = surf->Duplicate();
evaluated_brep->AddSurface(new_surf);
added = true;
}
ON_BrepFace &new_face = evaluated_brep->NewFace(evaluated_brep->m_S.Count() - 1);
add_elements(evaluated_brep, new_face, t_face->m_outerloop, ON_BrepLoop::outer);
// ON_BrepLoop &loop = evaluated_brep->m_L[evaluated_brep->m_L.Count() - 1];
for (unsigned int k = 0; k < t_face->m_innerloop.size(); k++) {
add_elements(evaluated_brep, new_face, t_face->m_innerloop[k], ON_BrepLoop::inner);
}
evaluated_brep->SetTrimIsoFlags(new_face);
const ON_BrepFace &original_face = i >= face_count1 ? brep2->m_F[i - face_count1] : brep1->m_F[i];
if (original_face.m_bRev ^ t_face->m_rev) {
evaluated_brep->FlipFace(new_face);
}
}
}
}
for (int i = 0; i < face_count1 + face_count2; i++) {
for (int j = 0; j < trimmed_faces[i].Count(); j++) {
if (trimmed_faces[i][j]) {
delete trimmed_faces[i][j];
trimmed_faces[i][j] = NULL;
}
}
}
evaluated_brep->ShrinkSurfaces();
evaluated_brep->Compact();
standardize_loop_orientations(evaluated_brep);
// Check IsValid() and output the message.
ON_wString ws;
ON_TextLog log(ws);
evaluated_brep->IsValid(&log);
if (ON_String(ws).Array()) {
bu_log("%s", ON_String(ws).Array());
}
dplot->WriteLog();
delete dplot;
dplot = NULL;
return 0;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 29.943304 | 238 | 0.657711 | dservin |
6a9f5366992b799f1eecc1b8c94338190ffaa867 | 4,708 | hpp | C++ | deps/cinder/include/boost/spirit/home/qi/nonterminal/debug_handler.hpp | multi-os-engine/cinder-natj-binding | 969b66fdd49e4ca63442baf61ce90ae385ab8178 | [
"Apache-2.0"
] | 1,210 | 2020-08-18T07:57:36.000Z | 2022-03-31T15:06:05.000Z | ios/Pods/boost-for-react-native/boost/spirit/home/qi/nonterminal/debug_handler.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 1,074 | 2015-08-25T15:08:14.000Z | 2019-07-22T20:28:39.000Z | ios/Pods/boost-for-react-native/boost/spirit/home/qi/nonterminal/debug_handler.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 534 | 2016-10-20T21:00:00.000Z | 2022-03-29T10:02:27.000Z | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_SPIRIT_DEBUG_HANDLER_DECEMBER_05_2008_0734PM)
#define BOOST_SPIRIT_DEBUG_HANDLER_DECEMBER_05_2008_0734PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/qi/nonterminal/rule.hpp>
#include <boost/spirit/home/qi/nonterminal/debug_handler_state.hpp>
#include <boost/spirit/home/qi/operator/expect.hpp>
#include <boost/function.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/out.hpp>
#include <iostream>
namespace boost { namespace spirit { namespace qi
{
template <
typename Iterator, typename Context
, typename Skipper, typename F>
struct debug_handler
{
typedef function<
bool(Iterator& first, Iterator const& last
, Context& context
, Skipper const& skipper
)>
function_type;
debug_handler(
function_type subject_
, F f_
, std::string const& rule_name_)
: subject(subject_)
, f(f_)
, rule_name(rule_name_)
{
}
bool operator()(
Iterator& first, Iterator const& last
, Context& context, Skipper const& skipper) const
{
f(first, last, context, pre_parse, rule_name);
try // subject might throw an exception
{
if (subject(first, last, context, skipper))
{
f(first, last, context, successful_parse, rule_name);
return true;
}
f(first, last, context, failed_parse, rule_name);
}
catch (expectation_failure<Iterator> const& e)
{
f(first, last, context, failed_parse, rule_name);
boost::throw_exception(e);
}
return false;
}
function_type subject;
F f;
std::string rule_name;
};
template <typename Iterator
, typename T1, typename T2, typename T3, typename T4, typename F>
void debug(rule<Iterator, T1, T2, T3, T4>& r, F f)
{
typedef rule<Iterator, T1, T2, T3, T4> rule_type;
typedef
debug_handler<
Iterator
, typename rule_type::context_type
, typename rule_type::skipper_type
, F>
debug_handler;
r.f = debug_handler(r.f, f, r.name());
}
struct simple_trace;
namespace detail
{
// This class provides an extra level of indirection through a
// template to produce the simple_trace type. This way, the use
// of simple_trace below is hidden behind a dependent type, so
// that compilers eagerly type-checking template definitions
// won't complain that simple_trace is incomplete.
template<typename T>
struct get_simple_trace
{
typedef simple_trace type;
};
}
template <typename Iterator
, typename T1, typename T2, typename T3, typename T4>
void debug(rule<Iterator, T1, T2, T3, T4>& r)
{
typedef rule<Iterator, T1, T2, T3, T4> rule_type;
typedef
debug_handler<
Iterator
, typename rule_type::context_type
, typename rule_type::skipper_type
, simple_trace>
debug_handler;
typedef typename qi::detail::get_simple_trace<Iterator>::type trace;
r.f = debug_handler(r.f, trace(), r.name());
}
}}}
///////////////////////////////////////////////////////////////////////////////
// Utility macro for easy enabling of rule and grammar debugging
#if !defined(BOOST_SPIRIT_DEBUG_NODE)
#if defined(BOOST_SPIRIT_DEBUG) || defined(BOOST_SPIRIT_QI_DEBUG)
#define BOOST_SPIRIT_DEBUG_NODE(r) r.name(#r); debug(r)
#else
#define BOOST_SPIRIT_DEBUG_NODE(r) r.name(#r)
#endif
#endif
#define BOOST_SPIRIT_DEBUG_NODE_A(r, _, name) \
BOOST_SPIRIT_DEBUG_NODE(name); \
/***/
#define BOOST_SPIRIT_DEBUG_NODES(seq) \
BOOST_PP_SEQ_FOR_EACH(BOOST_SPIRIT_DEBUG_NODE_A, _, seq) \
/***/
#endif
| 32.246575 | 81 | 0.561172 | multi-os-engine |
6aa296e4271acaefa4e99d245bd535a646560041 | 435 | tpp | C++ | BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-016.tpp | hmarcuzzo/compiler_project | 2463d19c2b81ba28a943974828e8bb5954424cac | [
"Apache-2.0"
] | null | null | null | BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-016.tpp | hmarcuzzo/compiler_project | 2463d19c2b81ba28a943974828e8bb5954424cac | [
"Apache-2.0"
] | null | null | null | BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-016.tpp | hmarcuzzo/compiler_project | 2463d19c2b81ba28a943974828e8bb5954424cac | [
"Apache-2.0"
] | 4 | 2020-12-11T10:12:37.000Z | 2021-11-01T18:34:25.000Z | {Aviso: Coerção implícita do valor atribuído para 'a', variável a flutuante recebendo um inteiro}
{Erro: Função 'func' do tipo inteiro retornando flutuante}
{Aviso: Função 'func' declarada, mas não utilizada}
{Aviso: Chamada recursiva para a função 'principal'}
{Erro: Função 'principal' deveria retornar inteiro, mas retorna vazio}
flutuante: a
inteiro: b
inteiro func()
a := 10
retorna(a)
fim
inteiro principal()
b := 18
fim
| 24.166667 | 97 | 0.747126 | hmarcuzzo |
6aa4f512a2df7f5a1d78bc65cba5f0ef68794edc | 3,736 | cpp | C++ | modules/ocl/perf/perf_surf.cpp | emaknyus/OpenCV-2.4.3-custom | a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7 | [
"MIT"
] | null | null | null | modules/ocl/perf/perf_surf.cpp | emaknyus/OpenCV-2.4.3-custom | a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7 | [
"MIT"
] | null | null | null | modules/ocl/perf/perf_surf.cpp | emaknyus/OpenCV-2.4.3-custom | a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Peng Xiao, pengxiao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include <iomanip>
#ifdef HAVE_OPENCL
using namespace cv;
using namespace cv::ocl;
using namespace cvtest;
using namespace testing;
using namespace std;
#define FILTER_IMAGE "../../../samples/gpu/road.png"
TEST(SURF, Performance)
{
cv::Mat img = readImage(FILTER_IMAGE, cv::IMREAD_GRAYSCALE);
ASSERT_FALSE(img.empty());
ocl::SURF_OCL d_surf;
ocl::oclMat d_keypoints;
ocl::oclMat d_descriptors;
double totalgputick = 0;
double totalgputick_kernel = 0;
double t1 = 0;
double t2 = 0;
for(int j = 0; j < LOOP_TIMES + 1; j ++)
{
t1 = (double)cvGetTickCount();//gpu start1
ocl::oclMat d_src(img);//upload
t2 = (double)cvGetTickCount(); //kernel
d_surf(d_src, ocl::oclMat(), d_keypoints, d_descriptors);
t2 = (double)cvGetTickCount() - t2;//kernel
cv::Mat cpu_kp, cpu_dp;
d_keypoints.download (cpu_kp);//download
d_descriptors.download (cpu_dp);//download
t1 = (double)cvGetTickCount() - t1;//gpu end1
if(j == 0)
continue;
totalgputick = t1 + totalgputick;
totalgputick_kernel = t2 + totalgputick_kernel;
}
cout << "average gpu runtime is " << totalgputick / ((double)cvGetTickFrequency()* LOOP_TIMES * 1000.) << "ms" << endl;
cout << "average gpu runtime without data transfer is " << totalgputick_kernel / ((double)cvGetTickFrequency()* LOOP_TIMES * 1000.) << "ms" << endl;
}
#endif //Have opencl | 36.271845 | 153 | 0.680139 | emaknyus |
6aa999e2ff00bd03bc8497fcf6b10f6459ac8c43 | 2,574 | cpp | C++ | src/prod/src/Management/ClusterManager/StoreDataComposeDeploymentInstanceCounter.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 1 | 2018-03-15T02:09:21.000Z | 2018-03-15T02:09:21.000Z | src/prod/src/Management/ClusterManager/StoreDataComposeDeploymentInstanceCounter.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | src/prod/src/Management/ClusterManager/StoreDataComposeDeploymentInstanceCounter.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace Store;
using namespace std;
using namespace Management::ClusterManager;
StoreDataComposeDeploymentInstanceCounter::StoreDataComposeDeploymentInstanceCounter()
: StoreData()
, value_(0)
{
}
wstring const & StoreDataComposeDeploymentInstanceCounter::get_Type() const
{
return Constants::StoreType_ComposeDeploymentInstanceCounter;
}
wstring StoreDataComposeDeploymentInstanceCounter::ConstructKey() const
{
return Constants::StoreKey_ComposeDeploymentInstanceCounter;
}
void StoreDataComposeDeploymentInstanceCounter::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const
{
w.Write("ComposeDeploymentInstanceCounter[{0}]", value_);
}
ErrorCode StoreDataComposeDeploymentInstanceCounter::GetTypeNameAndVersion(
StoreTransaction const &storeTx,
__out ServiceModelTypeName &typeName,
__out ServiceModelVersion &version)
{
// refresh the latest version from store.
ErrorCode error = storeTx.ReadExact(*this);
if (error.IsSuccess())
{
++value_;
error = storeTx.Update(*this);
}
else if (error.IsError(ErrorCodeValue::NotFound))
{
value_ = 0;
error = storeTx.Insert(*this);
}
if (error.IsSuccess())
{
//
// Application type name is used as a part of the directory name for the package, so using a sequence number to limit the length of
// name.
//
typeName = ServiceModelTypeName(wformatString("{0}{1}", *Constants::ComposeDeploymentTypePrefix, this->Value));
version = StoreDataComposeDeploymentInstanceCounter::GenerateServiceModelVersion(this->Value);
}
return error;
}
ErrorCode StoreDataComposeDeploymentInstanceCounter::GetVersionNumber(ServiceModelVersion const &version, uint64 *versionNumber)
{
auto versionString = version.Value;
StringUtility::TrimLeading<wstring>(versionString, L"v");
if (!StringUtility::TryFromWString(versionString, *versionNumber))
{
return ErrorCodeValue::NotFound;
}
return ErrorCodeValue::Success;
}
ServiceModelVersion StoreDataComposeDeploymentInstanceCounter::GenerateServiceModelVersion(uint64 number)
{
return ServiceModelVersion(wformatString("v{0}", number));
}
| 29.930233 | 139 | 0.703186 | AnthonyM |
6aaa42ef431f5ec2d9fe5c251b78b3e27f40ee0d | 885 | hpp | C++ | presets/Particle/RectangularParticle.hpp | emirroner/MiniParticle | ece0c4d38f978530aba4a0eb382e0b8f07be4748 | [
"MIT"
] | null | null | null | presets/Particle/RectangularParticle.hpp | emirroner/MiniParticle | ece0c4d38f978530aba4a0eb382e0b8f07be4748 | [
"MIT"
] | null | null | null | presets/Particle/RectangularParticle.hpp | emirroner/MiniParticle | ece0c4d38f978530aba4a0eb382e0b8f07be4748 | [
"MIT"
] | 1 | 2021-01-05T14:02:56.000Z | 2021-01-05T14:02:56.000Z | #ifndef RECTANGULAR_PARTICLE_HPP
#define RECTANGULAR_PARTICLE_HPP
#include <SFML\Graphics.hpp>
#include "..\..\include\MiniParticle.hpp"
class RectangularParticle : public MiniParticle
{
public:
RectangularParticle();
RectangularParticle(sf::Vector2f pos,sf::Vector2f velocity,sf::Color color,sf::Vector2f size,float lifeTime,bool resize,float gravity,float rotationSpeed,unsigned short ID = 0);
void update(float elapsed,float deltaTime);
const sf::Vector2f& getSize() const;
sf::Color getColor() const;
const sf::Vector2f& getStartSize() const;
float getRotation() const;
float getStartLifeTime() const;
void setSize(sf::Vector2f size);
void setColor(sf::Color color);
private:
sf::Vector2f m_size, m_startSize;
float m_rotationSpeed, m_rotation;
float m_startLifeTime;
bool m_resize;
float m_gravity;
sf::Color m_color;
};
#endif // RECTANGULAR_PARTICLE_HPP
| 25.285714 | 178 | 0.776271 | emirroner |
6aaa4ed24b3a53cc7e35a954c2d5af11a60ca9fb | 308 | cpp | C++ | 03-SDU_Exam_Algorithm_Question/2006/2006-T01_Class_Declaration.cpp | ysl970629/kaoyan_data_structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | 2 | 2021-03-24T03:29:16.000Z | 2022-03-29T16:34:30.000Z | 03-SDU_Exam_Algorithm_Question/2006/2006-T01_Class_Declaration.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | 03-SDU_Exam_Algorithm_Question/2006/2006-T01_Class_Declaration.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | template <class T>
class BinaryTreeNode {
public:
BinaryTreeNode(const T &e, BinaryTreeNode *lchild, BinaryTreeNode *rchild) {
data = e;
BinaryTreeNode::lchild = lchild;
BinaryTreeNode::rchild = rchild;
}
private:
T data;
BinaryTreeNode<T> *lchild, *rchild;
};
| 22 | 80 | 0.636364 | ysl970629 |
6aac537ab0672cb45ed9300d1dd746e8359d241a | 3,100 | hpp | C++ | src/kernel/threads/thread_listing.hpp | brandonbraun653/Valkyrie | 7132907f658c6d56ea43c998d9639d0a8e770ff8 | [
"MIT"
] | null | null | null | src/kernel/threads/thread_listing.hpp | brandonbraun653/Valkyrie | 7132907f658c6d56ea43c998d9639d0a8e770ff8 | [
"MIT"
] | 6 | 2019-06-01T13:31:16.000Z | 2021-04-07T22:03:05.000Z | src/kernel/threads/thread_listing.hpp | brandonbraun653/Valkyrie | 7132907f658c6d56ea43c998d9639d0a8e770ff8 | [
"MIT"
] | null | null | null | /********************************************************************************
* File Name:
* listing.hpp
*
* Description:
* List out all the threads in use with the project
*
* 2021 | Brandon Braun | brandonbraun653@gmail.com
*******************************************************************************/
#pragma once
#ifndef VALKYRIE_THREAD_LISTING_HPP
#define VALKYRIE_THREAD_LISTING_HPP
/* Chimera Includes */
#include <Chimera/thread>
namespace Valkyrie::Thread
{
/*-------------------------------------------------------------------------------
Public Functions
-------------------------------------------------------------------------------*/
/**
* @brief Starts up the system threads
*/
void CreateThreads();
/*-------------------------------------------------------------------------------
Background Thread: Idle processing and low priority tasks
-------------------------------------------------------------------------------*/
namespace Background
{
static const std::string_view Name = "Bkgd";
static constexpr size_t StackDepth = STACK_BYTES( 1024 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace Background
/*-------------------------------------------------------------------------------
Hardware Manager: Performs IO access to system hardware
-------------------------------------------------------------------------------*/
namespace HardwareManager
{
static const std::string_view Name = "HWMgr";
static constexpr size_t Period = 5;
static constexpr size_t StackDepth = STACK_BYTES( 2048 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace HardwareManager
/*-------------------------------------------------------------------------------
System Monitor: Watches the system state, like a more complicated watchdog.
-------------------------------------------------------------------------------*/
namespace SystemMonitor
{
static const std::string_view Name = "SYSMon";
static constexpr size_t StackDepth = STACK_BYTES( 1024 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace SystemMonitor
#if defined( SIMULATOR )
/*-------------------------------------------------------------------------------
Simulator Thread: Pumps RX/TX data through the simulator ports
-------------------------------------------------------------------------------*/
namespace Sim
{
static const std::string_view Name = "SimPump";
static constexpr size_t Period = 5;
static constexpr size_t StackDepth = STACK_BYTES( 10 * 1024 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace Sim
#endif /* SIMULATOR */
} // namespace Valkyrie::Thread
#endif /* !VALKYRIE_THREAD_LISTING_HPP */
| 31 | 83 | 0.444194 | brandonbraun653 |
6aad751f3c13538372f5746641773c62eea3d07e | 19,622 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgstereomatch/StereoMultipass.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgstereomatch/StereoMultipass.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgstereomatch/StereoMultipass.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* OpenSceneGraph example, osgstereomatch.
*
* 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 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 "StereoMultipass.h"
#include <osgDB/FileUtils>
#include <iostream>
SubtractPass::SubtractPass(osg::TextureRectangle *left_tex,
osg::TextureRectangle *right_tex,
int width, int height,
int start_disparity) :
_TextureWidth(width),
_TextureHeight(height),
_StartDisparity(start_disparity)
{
_RootGroup = new osg::Group;
_InTextureLeft = left_tex;
_InTextureRight = right_tex;
createOutputTextures();
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_subtract.frag");
}
SubtractPass::~SubtractPass()
{
}
osg::ref_ptr<osg::Group> SubtractPass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
_StateSet->setTextureAttributeAndModes(0, _InTextureLeft.get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(1, _InTextureRight.get(), osg::StateAttribute::ON);
_StateSet->addUniform(new osg::Uniform("textureLeft", 0));
_StateSet->addUniform(new osg::Uniform("textureRight", 1));
_StateSet->addUniform(new osg::Uniform("start_disparity", _StartDisparity));
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void SubtractPass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
// attach the 4 textures
for (int i=0; i<4; i++) {
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+i), _OutTexture[i].get());
}
}
void SubtractPass::createOutputTextures()
{
for (int i=0; i<4; i++) {
_OutTexture[i] = new osg::TextureRectangle;
_OutTexture[i]->setTextureSize(_TextureWidth, _TextureHeight);
_OutTexture[i]->setInternalFormat(GL_RGBA);
_OutTexture[i]->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_OutTexture[i]->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
}
}
void SubtractPass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
AggregatePass::AggregatePass(osg::TextureRectangle *diff_tex0,
osg::TextureRectangle *diff_tex1,
osg::TextureRectangle *diff_tex2,
osg::TextureRectangle *diff_tex3,
osg::TextureRectangle *agg_tex_in,
osg::TextureRectangle *agg_tex_out,
int width, int height,
int start_disparity, int window_size):
_TextureWidth(width),
_TextureHeight(height),
_StartDisparity(start_disparity),
_WindowSize(window_size)
{
_RootGroup = new osg::Group;
_InTextureDifference[0] = diff_tex0;
_InTextureDifference[1] = diff_tex1;
_InTextureDifference[2] = diff_tex2;
_InTextureDifference[3] = diff_tex3;
_InTextureAggregate = agg_tex_in;
_OutTextureAggregate = agg_tex_out;
_OutTexture = _OutTextureAggregate;
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_aggregate.frag");
}
AggregatePass::~AggregatePass()
{
}
osg::ref_ptr<osg::Group> AggregatePass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
_StateSet->setTextureAttributeAndModes(0, _InTextureDifference[0].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(1, _InTextureDifference[1].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(2, _InTextureDifference[2].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(3, _InTextureDifference[3].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(4, _InTextureAggregate.get(), osg::StateAttribute::ON);
_StateSet->addUniform(new osg::Uniform("textureDiff0", 0));
_StateSet->addUniform(new osg::Uniform("textureDiff1", 1));
_StateSet->addUniform(new osg::Uniform("textureDiff2", 2));
_StateSet->addUniform(new osg::Uniform("textureDiff3", 3));
_StateSet->addUniform(new osg::Uniform("textureAggIn", 4));
_StateSet->addUniform(new osg::Uniform("start_disparity", _StartDisparity));
_StateSet->addUniform(new osg::Uniform("window_size", _WindowSize));
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void AggregatePass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+0), _OutTexture.get());
}
void AggregatePass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
SelectPass::SelectPass(osg::TextureRectangle *in_tex,
int width, int height,
int min_disparity, int max_disparity) :
_TextureWidth(width),
_TextureHeight(height),
_MinDisparity(min_disparity),
_MaxDisparity(max_disparity)
{
_RootGroup = new osg::Group;
_InTexture = in_tex;
createOutputTextures();
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_select.frag");
}
SelectPass::~SelectPass()
{
}
osg::ref_ptr<osg::Group> SelectPass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
_StateSet->setTextureAttributeAndModes(0, _InTexture.get(), osg::StateAttribute::ON);
_StateSet->addUniform(new osg::Uniform("textureIn", 0));
_StateSet->addUniform(new osg::Uniform("min_disparity", _MinDisparity));
_StateSet->addUniform(new osg::Uniform("max_disparity", _MaxDisparity));
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void SelectPass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+0), _OutTexture.get());
}
void SelectPass::createOutputTextures()
{
_OutTexture = new osg::TextureRectangle;
_OutTexture->setTextureSize(_TextureWidth, _TextureHeight);
_OutTexture->setInternalFormat(GL_RGBA);
_OutTexture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_OutTexture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
}
void SelectPass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
StereoMultipass::StereoMultipass(osg::TextureRectangle *left_tex,
osg::TextureRectangle *right_tex,
int width, int height,
int min_disparity, int max_disparity, int window_size) :
_TextureWidth(width),
_TextureHeight(height)
{
_RootGroup = new osg::Group;
createOutputTextures();
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_clear.frag");
flip=1;
flop=0;
// we can do 16 differences in one pass,
// but we must ping-pong the aggregate textures between passes
// add passes until we cover the disparity range
for (int i=min_disparity; i<=max_disparity; i+=16) {
SubtractPass *subp = new SubtractPass(left_tex, right_tex,
width, height,
i);
AggregatePass *aggp = new AggregatePass(subp->getOutputTexture(0).get(),
subp->getOutputTexture(1).get(),
subp->getOutputTexture(2).get(),
subp->getOutputTexture(3).get(),
_OutTexture[flip].get(),
_OutTexture[flop].get(),
width, height,
i, window_size);
_RootGroup->addChild(subp->getRoot().get());
_RootGroup->addChild(aggp->getRoot().get());
flip = flip ? 0 : 1;
flop = flop ? 0 : 1;
}
// add select pass
_SelectPass = new SelectPass(_OutTexture[flip].get(),
width, height,
min_disparity, max_disparity);
_RootGroup->addChild(_SelectPass->getRoot().get());
}
StereoMultipass::~StereoMultipass()
{
}
osg::ref_ptr<osg::Group> StereoMultipass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void StereoMultipass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(10.0f,0.0f,0.0f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
// attach two textures for aggregating results
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+0), _OutTexture[0].get());
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+1), _OutTexture[1].get());
}
void StereoMultipass::createOutputTextures()
{
for (int i=0; i<2; i++) {
_OutTexture[i] = new osg::TextureRectangle;
_OutTexture[i]->setTextureSize(_TextureWidth, _TextureHeight);
_OutTexture[i]->setInternalFormat(GL_RGBA);
_OutTexture[i]->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_OutTexture[i]->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
// hdr, we want to store floats
_OutTexture[i]->setInternalFormat(GL_RGBA16F_ARB);
//_OutTexture[i]->setInternalFormat(GL_FLOAT_RGBA32_NV);
//_OutTexture[i]->setInternalFormat(GL_FLOAT_RGBA16_NV);
_OutTexture[i]->setSourceFormat(GL_RGBA);
_OutTexture[i]->setSourceType(GL_FLOAT);
}
}
void StereoMultipass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
| 36.202952 | 118 | 0.71109 | UM-ARM-Lab |
6aaedaf1b0dcea4877952e2e5d791acb3fab3fe5 | 3,488 | hpp | C++ | grasp_generation/graspitmodified_lm/Coin-3.1.3/include/boost/test/unit_test.hpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | 12 | 2019-10-29T01:42:55.000Z | 2021-11-14T18:33:43.000Z | grasp_generation/graspitmodified_lm/Coin-3.1.3/include/boost/test/unit_test.hpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/include/boost/test/unit_test.hpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | 6 | 2019-10-29T08:02:35.000Z | 2021-07-30T16:57:29.000Z | // (C) Copyright Gennadiy Rozental 2001-2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile: unit_test.hpp,v $
//
// Version : $Revision: 1.19 $
//
// Description : Entry point for the end user into the Unit Test Framework.
// ***************************************************************************
#ifndef BOOST_TEST_UNIT_TEST_HPP_071894GER
#define BOOST_TEST_UNIT_TEST_HPP_071894GER
// Boost.Test
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_suite.hpp>
//____________________________________________________________________________//
// ************************************************************************** //
// ************** Auto Linking ************** //
// ************************************************************************** //
#if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_TEST_NO_LIB) && \
!defined(BOOST_TEST_SOURCE) && !defined(BOOST_TEST_INCLUDED)
# define BOOST_LIB_NAME boost_unit_test_framework
# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_TEST_DYN_LINK)
# define BOOST_DYN_LINK
# endif
# include <boost/config/auto_link.hpp>
#endif // auto-linking disabled
// ************************************************************************** //
// ************** unit_test_main ************** //
// ************************************************************************** //
namespace boost { namespace unit_test {
#if defined(BOOST_TEST_DYN_LINK)
int BOOST_TEST_DECL unit_test_main( bool (*init_unit_test_func)(), int argc, char* argv[] );
#else
int BOOST_TEST_DECL unit_test_main( int argc, char* argv[] );
#endif
}}
#if defined(BOOST_TEST_DYN_LINK) && defined(BOOST_TEST_MAIN) && !defined(BOOST_TEST_NO_MAIN)
// ************************************************************************** //
// ************** main function for tests using dll ************** //
// ************************************************************************** //
int BOOST_TEST_CALL_DECL
main( int argc, char* argv[] )
{
return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv );
}
//____________________________________________________________________________//
#endif // BOOST_TEST_DYN_LINK && BOOST_TEST_MAIN && !BOOST_TEST_NO_MAIN
// ***************************************************************************
// Revision History :
//
// $Log: unit_test.hpp,v $
// Revision 1.19 2006/03/19 11:45:26 rogeeff
// main function renamed for consistancy
//
// Revision 1.18 2006/02/07 16:15:20 rogeeff
// BOOST_TEST_INCLUDED guard were missing
//
// Revision 1.17 2006/02/06 10:04:55 rogeeff
// BOOST_TEST_MODULE - master test suite name
//
// Revision 1.16 2005/12/14 05:21:36 rogeeff
// dll support introduced
// auto linking support introduced
//
// Revision 1.15 2005/02/20 08:27:06 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// Revision 1.14 2005/02/01 06:40:06 rogeeff
// copyright update
// old log entries removed
// minor stilistic changes
// depricated tools removed
//
// ***************************************************************************
#endif // BOOST_TEST_UNIT_TEST_HPP_071894GER
| 33.864078 | 101 | 0.550459 | KraftOreo |
6aaf607f059a16a24cdd00be10ee871eafc17a7b | 4,135 | cc | C++ | src/operator/contrib/deformable_psroi_pooling.cc | Vikas-kum/incubator-mxnet | ba02bf2fe2da423caa59ddb3fd5e433b90b730bf | [
"Apache-2.0"
] | 64 | 2021-05-02T14:42:34.000Z | 2021-05-06T01:35:03.000Z | src/operator/contrib/deformable_psroi_pooling.cc | Vikas-kum/incubator-mxnet | ba02bf2fe2da423caa59ddb3fd5e433b90b730bf | [
"Apache-2.0"
] | 187 | 2018-03-16T23:44:43.000Z | 2021-12-14T21:19:54.000Z | src/operator/contrib/deformable_psroi_pooling.cc | Vikas-kum/incubator-mxnet | ba02bf2fe2da423caa59ddb3fd5e433b90b730bf | [
"Apache-2.0"
] | 51 | 2019-07-12T05:10:25.000Z | 2021-07-28T16:19:06.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2017 Microsoft
* Licensed under The Apache-2.0 License [see LICENSE for details]
* \file deformable_psroi_pooling.cc
* \brief
* \author Yi Li, Guodong Zhang, Jifeng Dai
*/
#include "./deformable_psroi_pooling-inl.h"
#include <mshadow/base.h>
#include <mshadow/tensor.h>
#include <mshadow/packet-inl.h>
#include <mshadow/dot_engine-inl.h>
#include <cassert>
using std::max;
using std::min;
using std::floor;
using std::ceil;
namespace mshadow {
template<typename DType>
inline void DeformablePSROIPoolForward(const Tensor<cpu, 4, DType> &out,
const Tensor<cpu, 4, DType> &data,
const Tensor<cpu, 2, DType> &bbox,
const Tensor<cpu, 4, DType> &trans,
const Tensor<cpu, 4, DType> &top_count,
const bool no_trans,
const float spatial_scale,
const int output_dim,
const int group_size,
const int pooled_size,
const int part_size,
const int sample_per_part,
const float trans_std) {
// NOT_IMPLEMENTED;
return;
}
template<typename DType>
inline void DeformablePSROIPoolBackwardAcc(const Tensor<cpu, 4, DType> &in_grad,
const Tensor<cpu, 4, DType> &trans_grad,
const Tensor<cpu, 4, DType> &out_grad,
const Tensor<cpu, 4, DType> &data,
const Tensor<cpu, 2, DType> &bbox,
const Tensor<cpu, 4, DType> &trans,
const Tensor<cpu, 4, DType> &top_count,
const bool no_trans,
const float spatial_scale,
const int output_dim,
const int group_size,
const int pooled_size,
const int part_size,
const int sample_per_part,
const float trans_std) {
// NOT_IMPLEMENTED;
return;
}
} // namespace mshadow
namespace mxnet {
namespace op {
template<>
Operator *CreateOp<cpu>(DeformablePSROIPoolingParam param, int dtype) {
Operator* op = nullptr;
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
op = new DeformablePSROIPoolingOp<cpu, DType>(param);
});
return op;
}
Operator *DeformablePSROIPoolingProp::CreateOperatorEx(
Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, in_type->at(0));
}
DMLC_REGISTER_PARAMETER(DeformablePSROIPoolingParam);
MXNET_REGISTER_OP_PROPERTY(_contrib_DeformablePSROIPooling, DeformablePSROIPoolingProp)
.describe("Performs deformable position-sensitive region-of-interest pooling on inputs.\n"
"The DeformablePSROIPooling operation is described in https://arxiv.org/abs/1703.06211 ."
"batch_size will change to the number of region bounding boxes after DeformablePSROIPooling")
.add_argument("data", "Symbol", "Input data to the pooling operator, a 4D Feature maps")
.add_argument("rois", "Symbol", "Bounding box coordinates, a 2D array of "
"[[batch_index, x1, y1, x2, y2]]. (x1, y1) and (x2, y2) are top left and down right corners "
"of designated region of interest. batch_index indicates the index of corresponding image "
"in the input data")
.add_argument("trans", "Symbol", "transition parameter")
.add_arguments(DeformablePSROIPoolingParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| 35.646552 | 99 | 0.718259 | Vikas-kum |
6ab2c7e1f8b312f12e618cc550e47ffd48921505 | 6,504 | hpp | C++ | src/api/crypto.hpp | zengyuxing007/pipy | c60e08560b08728fa181940a4b9d67807a0ee625 | [
"BSL-1.0"
] | null | null | null | src/api/crypto.hpp | zengyuxing007/pipy | c60e08560b08728fa181940a4b9d67807a0ee625 | [
"BSL-1.0"
] | null | null | null | src/api/crypto.hpp | zengyuxing007/pipy | c60e08560b08728fa181940a4b9d67807a0ee625 | [
"BSL-1.0"
] | null | null | null | /*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CRYPTO_HPP
#define CRYPTO_HPP
#include "pjs/pjs.hpp"
#include "data.hpp"
#include <openssl/evp.h>
namespace pipy {
namespace crypto {
//
// AliasType
//
enum class AliasType {
sm2,
};
//
// PublicKey
//
class PublicKey : public pjs::ObjectTemplate<PublicKey> {
public:
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
PublicKey(Data *data, pjs::Object *options);
PublicKey(pjs::Str *data, pjs::Object *options);
~PublicKey();
EVP_PKEY* m_pkey = nullptr;
static auto read_pem(const void *data, size_t size) -> EVP_PKEY*;
friend class pjs::ObjectTemplate<PublicKey>;
};
//
// PrivateKey
//
class PrivateKey : public pjs::ObjectTemplate<PrivateKey> {
public:
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
PrivateKey(Data *data, pjs::Object *options);
PrivateKey(pjs::Str *data, pjs::Object *options);
~PrivateKey();
EVP_PKEY* m_pkey = nullptr;
static auto read_pem(const void *data, size_t size) -> EVP_PKEY*;
friend class pjs::ObjectTemplate<PrivateKey>;
};
//
// Cipher
//
class Cipher : public pjs::ObjectTemplate<Cipher> {
public:
enum class Algorithm {
sm4_cbc,
sm4_ecb,
sm4_cfb,
sm4_cfb128,
sm4_ofb,
sm4_ctr,
};
static auto cipher(Algorithm algorithm) -> const EVP_CIPHER*;
auto update(Data *data) -> Data*;
auto update(pjs::Str *str) -> Data*;
auto final() -> Data*;
private:
Cipher(Algorithm algorithm, pjs::Object *options);
~Cipher();
EVP_CIPHER_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Cipher>;
};
//
// Decipher
//
class Decipher : public pjs::ObjectTemplate<Decipher> {
public:
auto update(Data *data) -> Data*;
auto update(pjs::Str *str) -> Data*;
auto final() -> Data*;
private:
Decipher(Cipher::Algorithm algorithm, pjs::Object *options);
~Decipher();
EVP_CIPHER_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Decipher>;
};
//
// Hash
//
class Hash : public pjs::ObjectTemplate<Hash> {
public:
enum class Algorithm {
md4,
md5,
md5_sha1,
blake2b512,
blake2s256,
sha1,
sha224,
sha256,
sha384,
sha512,
sha512_224,
sha512_256,
sha3_224,
sha3_256,
sha3_384,
sha3_512,
shake128,
shake256,
mdc2,
ripemd160,
whirlpool,
sm3,
};
static auto digest(Algorithm algorithm) -> const EVP_MD*;
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto digest() -> Data*;
auto digest(Data::Encoding enc) -> pjs::Str*;
private:
Hash(Algorithm algorithm);
~Hash();
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Hash>;
};
//
// Hmac
//
class Hmac : public pjs::ObjectTemplate<Hmac> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto digest() -> Data*;
auto digest(Data::Encoding enc) -> pjs::Str*;
private:
Hmac(Hash::Algorithm algorithm, Data *key);
Hmac(Hash::Algorithm algorithm, pjs::Str *key);
~Hmac();
HMAC_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Hmac>;
};
//
// Sign
//
class Sign : public pjs::ObjectTemplate<Sign> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto sign(PrivateKey *key, Object *options = nullptr) -> Data*;
auto sign(PrivateKey *key, Data::Encoding enc, Object *options = nullptr) -> pjs::Str*;
private:
Sign(Hash::Algorithm algorithm);
~Sign();
const EVP_MD* m_md = nullptr;
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Sign>;
};
//
// Verify
//
class Verify : public pjs::ObjectTemplate<Verify> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
bool verify(PublicKey *key, Data *signature, Object *options = nullptr);
bool verify(PublicKey *key, pjs::Str *signature, Data::Encoding enc, Object *options = nullptr);
private:
Verify(Hash::Algorithm algorithm);
~Verify();
const EVP_MD* m_md = nullptr;
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Verify>;
};
//
// JWK
//
class JWK : public pjs::ObjectTemplate<JWK> {
public:
bool is_valid() const { return m_pkey; }
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
JWK(pjs::Object *json);
~JWK();
EVP_PKEY* m_pkey = nullptr;
friend class pjs::ObjectTemplate<JWK>;
};
//
// JWT
//
class JWT : public pjs::ObjectTemplate<JWT> {
public:
enum class Algorithm {
HS256,
HS384,
HS512,
RS256,
RS384,
RS512,
ES256,
ES384,
ES512,
};
bool is_valid() const { return m_is_valid; }
auto header() const -> const pjs::Value& { return m_header; }
auto payload() const -> const pjs::Value& { return m_payload; }
void sign(pjs::Str *key);
bool verify(Data *key);
bool verify(pjs::Str *key);
bool verify(JWK *key);
private:
JWT(pjs::Str *token);
~JWT();
bool m_is_valid = false;
Algorithm m_algorithm = Algorithm::HS256;
pjs::Value m_header;
pjs::Value m_payload;
std::string m_header_str;
std::string m_payload_str;
std::string m_signature_str;
std::string m_signature;
auto get_md() -> const EVP_MD*;
bool verify(const char *key, int key_len);
bool verify(EVP_PKEY *pkey);
int jose2der(char *out, const char *inp, int len);
friend class pjs::ObjectTemplate<JWT>;
};
//
// Crypto
//
class Crypto : public pjs::ObjectTemplate<Crypto>
{
};
} // namespace crypto
} // namespace pipy
#endif // CRYPTO_HPP | 20.325 | 98 | 0.673739 | zengyuxing007 |
6ab325034ed73897ac162b5fe67b4b3694da4823 | 708 | cpp | C++ | tests/test-main.cpp | tom91136/libfluid | a0d54d06b1fe754db14ddc7d511fb7b57a5cce45 | [
"Apache-2.0"
] | 4 | 2019-03-11T18:12:22.000Z | 2019-07-11T12:39:35.000Z | tests/test-main.cpp | tom91136/libfluid | a0d54d06b1fe754db14ddc7d511fb7b57a5cce45 | [
"Apache-2.0"
] | null | null | null | tests/test-main.cpp | tom91136/libfluid | a0d54d06b1fe754db14ddc7d511fb7b57a5cce45 | [
"Apache-2.0"
] | null | null | null | #define CATCH_CONFIG_MAIN
#define CATCH_CONFIG_NOSTDOUT
#include <catch2/catch.hpp>
class out_buff : public std::stringbuf {
std::FILE *m_stream;
public:
out_buff(std::FILE *stream) : m_stream(stream) {}
~out_buff() { pubsync(); }
int sync() {
int ret = 0;
for (unsigned char c : str()) {
if (putc(c, m_stream) == EOF) {
ret = -1;
break;
}
}
// Reset the buffer to avoid printing it multiple times
str("");
return ret;
}
};
namespace Catch {
std::ostream &cout() {
static std::ostream ret(new out_buff(stdout));
return ret;
}
std::ostream &clog() {
static std::ostream ret(new out_buff(stderr));
return ret;
}
std::ostream &cerr() {
return clog();
}
}
| 16.090909 | 57 | 0.628531 | tom91136 |
6ab92eeccb38faaee427fffbdc824977caba9993 | 409 | cpp | C++ | src/xrGame/weaponshotgun_script.cpp | acidicMercury8/xray-1.6 | 52fba7348a93a52ff9694f2c9dd40c0d090e791e | [
"Linux-OpenIB"
] | 10 | 2021-05-04T06:40:27.000Z | 2022-01-20T20:24:28.000Z | src/xrGame/weaponshotgun_script.cpp | acidicMercury8/xray-1.6 | 52fba7348a93a52ff9694f2c9dd40c0d090e791e | [
"Linux-OpenIB"
] | null | null | null | src/xrGame/weaponshotgun_script.cpp | acidicMercury8/xray-1.6 | 52fba7348a93a52ff9694f2c9dd40c0d090e791e | [
"Linux-OpenIB"
] | 2 | 2020-05-17T10:01:14.000Z | 2020-09-11T20:17:27.000Z | #include "pch_script.h"
#include "WeaponShotgun.h"
#include "WeaponAutomaticShotgun.h"
using namespace luabind;
#pragma optimize("s",on)
void CWeaponShotgun::script_register (lua_State *L)
{
module(L)
[
class_<CWeaponShotgun,CGameObject>("CWeaponShotgun")
.def(constructor<>()),
class_<CWeaponAutomaticShotgun,CGameObject>("CWeaponAutomaticShotgun")
.def(constructor<>())
];
}
| 22.722222 | 73 | 0.716381 | acidicMercury8 |
6abca41ee0eab7b863930330842283c3e87d0a4c | 18,412 | cpp | C++ | Code/GraphMol/Fingerprints/AtomPairs.cpp | chcltchunk/rdkit | af0ccf686779a8efd9db7c77f0bb3cab718ea2ba | [
"BSD-3-Clause"
] | 4 | 2020-12-29T14:52:15.000Z | 2021-08-28T08:12:45.000Z | Code/GraphMol/Fingerprints/AtomPairs.cpp | chcltchunk/rdkit | af0ccf686779a8efd9db7c77f0bb3cab718ea2ba | [
"BSD-3-Clause"
] | 2 | 2020-06-08T08:06:39.000Z | 2020-07-03T07:04:42.000Z | Code/GraphMol/Fingerprints/AtomPairs.cpp | chcltchunk/rdkit | af0ccf686779a8efd9db7c77f0bb3cab718ea2ba | [
"BSD-3-Clause"
] | 1 | 2020-05-15T12:15:35.000Z | 2020-05-15T12:15:35.000Z | //
// Copyright (C) 2007-2013 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include <GraphMol/Subgraphs/Subgraphs.h>
#include <DataStructs/SparseIntVect.h>
#include <RDGeneral/hash/hash.hpp>
#include <cstdint>
#include <boost/dynamic_bitset.hpp>
#include <boost/foreach.hpp>
#include <GraphMol/Fingerprints/FingerprintUtil.h>
namespace RDKit {
namespace AtomPairs {
template <typename T1, typename T2>
void updateElement(SparseIntVect<T1> &v, T2 elem) {
v.setVal(elem, v.getVal(elem) + 1);
}
template <typename T1>
void updateElement(ExplicitBitVect &v, T1 elem) {
v.setBit(elem % v.getNumBits());
}
template <typename T>
void setAtomPairBit(std::uint32_t i, std::uint32_t j,
std::uint32_t nAtoms,
const std::vector<std::uint32_t> &atomCodes,
const double *dm, T *bv, unsigned int minLength,
unsigned int maxLength, bool includeChirality) {
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bitId =
getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);
updateElement(*bv, static_cast<std::uint32_t>(bitId));
}
}
SparseIntVect<std::int32_t> *getAtomPairFingerprint(
const ROMol &mol, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
return getAtomPairFingerprint(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D,
confId);
};
SparseIntVect<std::int32_t> *getAtomPairFingerprint(
const ROMol &mol, unsigned int minLength, unsigned int maxLength,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
auto *res = new SparseIntVect<std::int32_t>(
1 << (numAtomPairFingerprintBits + 2 * (includeChirality ? 2 : 0)));
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(*lmol);
} else {
dm = MolOps::get3DDistanceMat(*lmol, confId);
}
const unsigned int nAtoms = lmol->getNumAtoms();
std::vector<std::uint32_t> atomCodes;
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %
((1 << codeSize) - 1));
}
}
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != lmol->endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
} else {
BOOST_FOREACH (std::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
}
}
}
return res;
}
SparseIntVect<std::int32_t> *getHashedAtomPairFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
auto *res = new SparseIntVect<std::int32_t>(nBits);
const double *dm;
try {
if (use2D) {
dm = MolOps::getDistanceMat(*lmol);
} else {
dm = MolOps::get3DDistanceMat(*lmol, confId);
}
} catch (const ConformerException &) {
delete res;
throw;
}
const unsigned int nAtoms = lmol->getNumAtoms();
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(nAtoms);
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);
}
}
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != lmol->endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<std::int32_t>(bit % nBits));
}
}
} else {
BOOST_FOREACH (std::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<std::int32_t>(bit % nBits));
}
}
}
}
}
return res;
}
ExplicitBitVect *getHashedAtomPairFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<std::int32_t> *sres = getHashedAtomPairFingerprint(
mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D, confId);
auto *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i)) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
SparseIntVect<boost::int64_t> *getTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
boost::uint64_t sz = 1;
sz = (sz << (targetSize *
(codeSize + (includeChirality ? numChiralBits : 0))));
// NOTE: this -1 is incorrect but it's needed for backwards compatibility.
// hopefully we'll never have a case with a torsion that hits this.
//
// mmm, bug compatible.
sz -= 1;
auto *res = new SparseIntVect<boost::int64_t>(sz);
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(lmol->getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(
(*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);
}
}
boost::dynamic_bitset<> *fromAtomsBV = nullptr;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
boost::dynamic_bitset<> pAtoms(lmol->getNumAtoms());
PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
std::vector<std::uint32_t> pathCodes;
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
pAtoms.reset();
for (auto pIt = path.begin(); pIt < path.end(); ++pIt) {
// look for a cycle that doesn't start at the first atom
// we can't effectively canonicalize these at the moment
// (was github #811)
if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {
pathCodes.clear();
break;
}
pAtoms.set(*pIt);
unsigned int code = atomCodes[*pIt] - 1;
// subtract off the branching number:
if (pIt != path.begin() && pIt + 1 != path.end()) {
--code;
}
pathCodes.push_back(code);
}
if (pathCodes.size()) {
boost::int64_t code =
getTopologicalTorsionCode(pathCodes, includeChirality);
updateElement(*res, code);
}
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
return res;
}
namespace {
template <typename T>
void TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,
unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(lmol->getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);
}
}
boost::dynamic_bitset<> *fromAtomsBV = nullptr;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
std::vector<std::uint32_t> pathCodes(targetSize);
for (unsigned int i = 0; i < targetSize; ++i) {
unsigned int code = atomCodes[path[i]] - 1;
// subtract off the branching number:
if (i > 0 && i < targetSize - 1) {
--code;
}
pathCodes[i] = code;
}
size_t bit = getTopologicalTorsionHash(pathCodes);
updateElement(*res, bit % nBits);
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
}
} // namespace
SparseIntVect<boost::int64_t> *getHashedTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
auto *res = new SparseIntVect<boost::int64_t>(nBits);
TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
return res;
}
ExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
auto *sres = new SparseIntVect<boost::int64_t>(blockLength);
TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
auto *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i)) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
} // end of namespace AtomPairs
} // end of namespace RDKit
| 36.971888 | 80 | 0.620845 | chcltchunk |
6abe596612463c9e7facca31767b80ada6702075 | 404 | cpp | C++ | source/LoopManager/LoopManager.cpp | mvxxx/MarsCombat | c4d10da7cf9bf8a71e00f64e5e364a358b477b15 | [
"MIT"
] | 1 | 2019-08-25T10:36:16.000Z | 2019-08-25T10:36:16.000Z | source/LoopManager/LoopManager.cpp | mvxxx/MarsCombat | c4d10da7cf9bf8a71e00f64e5e364a358b477b15 | [
"MIT"
] | null | null | null | source/LoopManager/LoopManager.cpp | mvxxx/MarsCombat | c4d10da7cf9bf8a71e00f64e5e364a358b477b15 | [
"MIT"
] | null | null | null | #include "LoopManager.hpp"
LoopManager::LoopManager(const sf::Time & _timePerFrame)
:timePerFrame(_timePerFrame)
{
timeSinceLastUpdate = sf::Time::Zero;
}
void LoopManager::increaseTime()
{
timeSinceLastUpdate += clock.restart();
}
bool LoopManager::canChangeTheFrame()
{
return timeSinceLastUpdate <= timePerFrame;
}
void LoopManager::reduceTime()
{
timeSinceLastUpdate -= timePerFrame;
}
| 17.565217 | 56 | 0.752475 | mvxxx |
6abf7aa1d03ea9e237cd1ad07c4ceb1fb1793f0d | 1,811 | cpp | C++ | src/data/label_utils.cpp | ltriess/voxelizer | f8dcc2296cd75d63081cea0edaaf162bbbfb717f | [
"MIT"
] | null | null | null | src/data/label_utils.cpp | ltriess/voxelizer | f8dcc2296cd75d63081cea0edaaf162bbbfb717f | [
"MIT"
] | null | null | null | src/data/label_utils.cpp | ltriess/voxelizer | f8dcc2296cd75d63081cea0edaaf162bbbfb717f | [
"MIT"
] | 4 | 2021-08-18T14:24:01.000Z | 2021-10-06T11:52:36.000Z | #include "label_utils.h"
#include <QtXml/QDomDocument>
#include <QtCore/QFile>
#include <QtCore/QStringList>
#include <QtCore/QString>
void getLabelNames(const std::string& filename,
std::map<uint32_t, std::string>& label_names)
{
QDomDocument doc("mydocument");
QFile file(QString::fromStdString(filename));
if (!file.open(QIODevice::ReadOnly)) return;
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomElement rootNode = doc.firstChildElement("config");
QDomElement n = rootNode.firstChildElement("label");
for (; !n.isNull(); n = n.nextSiblingElement("label"))
{
std::string name = n.firstChildElement("name").text().toStdString();
uint32_t id = n.firstChildElement("id").text().toInt();
label_names[id] = name;
}
}
void getLabelColors(const std::string& filename,
std::map<uint32_t, glow::GlColor>& label_colors)
{
QDomDocument doc("mydocument");
QFile file(QString::fromStdString(filename));
if (!file.open(QIODevice::ReadOnly)) return;
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomElement rootNode = doc.firstChildElement("config");
QDomElement n = rootNode.firstChildElement("label");
for (; !n.isNull(); n = n.nextSiblingElement("label"))
{
std::string name = n.firstChildElement("name").text().toStdString();
uint32_t id = n.firstChildElement("id").text().toInt();
QString color_string = n.firstChildElement("color").text();
QStringList tokens = color_string.split(" ");
int32_t R = tokens.at(0).toInt();
int32_t G = tokens.at(1).toInt();
int32_t B = tokens.at(2).toInt();
label_colors[id] = glow::GlColor::FromRGB(R, G, B);
}
}
| 26.246377 | 72 | 0.675318 | ltriess |
6abfbc9e999295fe4813fecf36d075d602aeedbd | 5,027 | cpp | C++ | B2G/gecko/content/html/content/src/nsHTMLDivElement.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/content/html/content/src/nsHTMLDivElement.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/content/html/content/src/nsHTMLDivElement.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/Util.h"
#include "nsIDOMHTMLDivElement.h"
#include "nsIDOMEventTarget.h"
#include "nsGenericHTMLElement.h"
#include "nsGkAtoms.h"
#include "nsStyleConsts.h"
#include "nsMappedAttributes.h"
using namespace mozilla;
class nsHTMLDivElement : public nsGenericHTMLElement,
public nsIDOMHTMLDivElement
{
public:
nsHTMLDivElement(already_AddRefed<nsINodeInfo> aNodeInfo);
virtual ~nsHTMLDivElement();
// nsISupports
NS_DECL_ISUPPORTS_INHERITED
// nsIDOMNode
NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::)
// nsIDOMElement
NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLElement::)
// nsIDOMHTMLElement
NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLElement::)
// nsIDOMHTMLDivElement
NS_DECL_NSIDOMHTMLDIVELEMENT
virtual bool ParseAttribute(int32_t aNamespaceID,
nsIAtom* aAttribute,
const nsAString& aValue,
nsAttrValue& aResult);
NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom* aAttribute) const;
virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
virtual nsXPCClassInfo* GetClassInfo();
virtual nsIDOMNode* AsDOMNode() { return this; }
};
NS_IMPL_NS_NEW_HTML_ELEMENT(Div)
nsHTMLDivElement::nsHTMLDivElement(already_AddRefed<nsINodeInfo> aNodeInfo)
: nsGenericHTMLElement(aNodeInfo)
{
}
nsHTMLDivElement::~nsHTMLDivElement()
{
}
NS_IMPL_ADDREF_INHERITED(nsHTMLDivElement, nsGenericElement)
NS_IMPL_RELEASE_INHERITED(nsHTMLDivElement, nsGenericElement)
DOMCI_NODE_DATA(HTMLDivElement, nsHTMLDivElement)
// QueryInterface implementation for nsHTMLDivElement
NS_INTERFACE_TABLE_HEAD(nsHTMLDivElement)
NS_HTML_CONTENT_INTERFACE_TABLE1(nsHTMLDivElement, nsIDOMHTMLDivElement)
NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLDivElement,
nsGenericHTMLElement)
NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLDivElement)
NS_IMPL_ELEMENT_CLONE(nsHTMLDivElement)
NS_IMPL_STRING_ATTR(nsHTMLDivElement, Align, align)
bool
nsHTMLDivElement::ParseAttribute(int32_t aNamespaceID,
nsIAtom* aAttribute,
const nsAString& aValue,
nsAttrValue& aResult)
{
if (aNamespaceID == kNameSpaceID_None) {
if (mNodeInfo->Equals(nsGkAtoms::marquee)) {
if ((aAttribute == nsGkAtoms::width) ||
(aAttribute == nsGkAtoms::height)) {
return aResult.ParseSpecialIntValue(aValue);
}
if (aAttribute == nsGkAtoms::bgcolor) {
return aResult.ParseColor(aValue);
}
if ((aAttribute == nsGkAtoms::hspace) ||
(aAttribute == nsGkAtoms::vspace)) {
return aResult.ParseIntWithBounds(aValue, 0);
}
}
if (mNodeInfo->Equals(nsGkAtoms::div) &&
aAttribute == nsGkAtoms::align) {
return ParseDivAlignValue(aValue, aResult);
}
}
return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
aResult);
}
static void
MapAttributesIntoRule(const nsMappedAttributes* aAttributes, nsRuleData* aData)
{
nsGenericHTMLElement::MapDivAlignAttributeInto(aAttributes, aData);
nsGenericHTMLElement::MapCommonAttributesInto(aAttributes, aData);
}
static void
MapMarqueeAttributesIntoRule(const nsMappedAttributes* aAttributes, nsRuleData* aData)
{
nsGenericHTMLElement::MapImageMarginAttributeInto(aAttributes, aData);
nsGenericHTMLElement::MapImageSizeAttributesInto(aAttributes, aData);
nsGenericHTMLElement::MapCommonAttributesInto(aAttributes, aData);
nsGenericHTMLElement::MapBGColorInto(aAttributes, aData);
}
NS_IMETHODIMP_(bool)
nsHTMLDivElement::IsAttributeMapped(const nsIAtom* aAttribute) const
{
if (mNodeInfo->Equals(nsGkAtoms::div)) {
static const MappedAttributeEntry* const map[] = {
sDivAlignAttributeMap,
sCommonAttributeMap
};
return FindAttributeDependence(aAttribute, map);
}
if (mNodeInfo->Equals(nsGkAtoms::marquee)) {
static const MappedAttributeEntry* const map[] = {
sImageMarginSizeAttributeMap,
sBackgroundColorAttributeMap,
sCommonAttributeMap
};
return FindAttributeDependence(aAttribute, map);
}
return nsGenericHTMLElement::IsAttributeMapped(aAttribute);
}
nsMapRuleToAttributesFunc
nsHTMLDivElement::GetAttributeMappingFunction() const
{
if (mNodeInfo->Equals(nsGkAtoms::div)) {
return &MapAttributesIntoRule;
}
if (mNodeInfo->Equals(nsGkAtoms::marquee)) {
return &MapMarqueeAttributesIntoRule;
}
return nsGenericHTMLElement::GetAttributeMappingFunction();
}
| 30.652439 | 86 | 0.724687 | wilebeast |
6ac2777870eac3943b7128f02cb8c3590c48100c | 11,109 | cpp | C++ | FileZillaFTP/source/interface/splitex.cpp | JyothsnaMididoddi26/xampp | 8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b | [
"Apache-2.0"
] | 1 | 2017-01-31T08:49:16.000Z | 2017-01-31T08:49:16.000Z | FileZillaFTP/source/interface/splitex.cpp | JyothsnaMididoddi26/xampp | 8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b | [
"Apache-2.0"
] | 2 | 2020-07-17T00:13:41.000Z | 2021-05-08T17:01:54.000Z | FileZillaFTP/source/interface/splitex.cpp | JyothsnaMididoddi26/xampp | 8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////
//
// splitex.cpp
// Based upon code from Oleg G. Galkin
// Modified to handle multiple hidden rows
#include "stdafx.h"
#include "splitex.h"
#if defined(_DEBUG) && !defined(MMGR)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
////////////////////////////////////////////////////////////////////////////
//
// CSplitterWndEx
CSplitterWndEx::CSplitterWndEx()
{
m_arr = 0;
m_length = 0;
}
CSplitterWndEx::~CSplitterWndEx()
{
delete [] m_arr;
}
int CSplitterWndEx::Id_short(int row, int col)
{
return AFX_IDW_PANE_FIRST + row * 16 + col;
}
void CSplitterWndEx::ShowRow(int r)
{
ASSERT_VALID(this);
ASSERT(m_nRows < m_nMaxRows);
ASSERT(m_arr);
ASSERT(r < m_length);
ASSERT(m_arr[r] >= m_nRows);
ASSERT(m_arr[r] < m_length);
int rowNew = r;
int cyNew = m_pRowInfo[m_arr[r]].nCurSize;
int cyIdealNew = m_pRowInfo[m_arr[r]].nIdealSize;
int new_val = 0;
for (int i = rowNew - 1; i >= 0; i--)
if (m_arr[i] < m_nRows) // not hidden
{
new_val = m_arr[i] + 1;
break;
}
int old_val = m_arr[rowNew];
m_nRows++; // add a row
// fill the hided row
int row;
for (int col = 0; col < m_nCols; col++)
{
CWnd* pPaneShow = GetDlgItem(
Id_short(old_val, col));
ASSERT(pPaneShow != NULL);
pPaneShow->ShowWindow(SW_SHOWNA);
for (row = m_length - 1; row >= 0; row--)
{
if ((m_arr[row] >= new_val) &&
(m_arr[row] < old_val))
{
CWnd* pPane = CSplitterWnd::GetPane(m_arr[row], col);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(m_arr[row] + 1, col));
}
}
pPaneShow->SetDlgCtrlID(Id_short(new_val, col));
}
for (row = 0; row < m_length; row++)
if ((m_arr[row] >= new_val) &&
(m_arr[row] < old_val))
m_arr[row]++;
m_arr[rowNew] = new_val;
//new panes have been created -- recalculate layout
for (row = new_val + 1; row < m_length; row++)
{
if (m_arr[row]<m_nRows)
{
m_pRowInfo[m_arr[row]].nIdealSize = m_pRowInfo[m_arr[row-1]].nCurSize;
m_pRowInfo[m_arr[row]].nCurSize = m_pRowInfo[m_arr[row-1]].nCurSize;
}
}
if (cyNew>=0x10000)
{
int rowToResize=(cyNew>>16)-1;
cyNew%=0x10000;
cyIdealNew%=0x10000;
m_pRowInfo[m_arr[rowToResize]].nCurSize-=cyNew+m_cxSplitter;
m_pRowInfo[m_arr[rowToResize]].nIdealSize=m_pRowInfo[m_arr[rowToResize]].nCurSize;//-=cyIdealNew+m_cxSplitter;
}
m_pRowInfo[new_val].nIdealSize = cyNew;
m_pRowInfo[new_val].nCurSize = cyNew;
RecalcLayout();
}
void CSplitterWndEx::ShowColumn(int c)
{
ASSERT_VALID(this);
ASSERT(m_nCols < m_nMaxCols);
ASSERT(m_arr);
ASSERT(c < m_length);
ASSERT(m_arr[c] >= m_nRows);
ASSERT(m_arr[c] < m_length);
int colNew = c;
int cxNew = m_pColInfo[m_arr[c]].nCurSize;
int cxIdealNew = m_pColInfo[m_arr[c]].nIdealSize;
int new_val = 0;
for (int i = colNew - 1; i >= 0; i--)
if (m_arr[i] < m_nCols) // not hidden
{
new_val = m_arr[i] + 1;
break;
}
int old_val = m_arr[colNew];
m_nCols++; // add a col
// fill the hided col
int col;
for (int row = 0; row < m_nRows; row++)
{
CWnd* pPaneShow = GetDlgItem(
Id_short(row, old_val));
ASSERT(pPaneShow != NULL);
pPaneShow->ShowWindow(SW_SHOWNA);
for (col = m_length - 1; col >= 0; col--)
{
if ((m_arr[col] >= new_val) &&
(m_arr[col] < old_val))
{
CWnd* pPane = CSplitterWnd::GetPane(row, m_arr[col]);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row, m_arr[col]+1));
}
}
pPaneShow->SetDlgCtrlID(Id_short(row, new_val));
}
for (col = 0; col < m_length; col++)
if ((m_arr[col] >= new_val) &&
(m_arr[col] < old_val))
m_arr[col]++;
m_arr[colNew] = new_val;
//new panes have been created -- recalculate layout
for (col = new_val + 1; col < m_length; col++)
{
if (m_arr[col]<m_nCols)
{
m_pColInfo[m_arr[col]].nIdealSize = m_pColInfo[m_arr[col-1]].nCurSize;
m_pColInfo[m_arr[col]].nCurSize = m_pColInfo[m_arr[col-1]].nCurSize;
}
}
if (cxNew>=0x10000)
{
int colToResize=(cxNew>>16)-1;
cxNew%=0x10000;
cxIdealNew%=0x10000;
m_pColInfo[m_arr[colToResize]].nCurSize-=cxNew+m_cySplitter;
m_pColInfo[m_arr[colToResize]].nIdealSize=m_pColInfo[m_arr[colToResize]].nCurSize;//-=cxIdealNew+m_cySplitter;
}
m_pColInfo[new_val].nIdealSize = cxNew;
m_pColInfo[new_val].nCurSize = cxNew;
RecalcLayout();
}
void CSplitterWndEx::HideRow(int rowHide,int rowToResize)
{
ASSERT_VALID(this);
ASSERT(m_nRows > 1);
if (m_arr)
ASSERT(m_arr[rowHide] < m_nRows);
// if the row has an active window -- change it
int rowActive, colActive;
if (!m_arr)
{
m_arr = new int[m_nRows];
for (int i = 0; i < m_nRows; i++)
m_arr[i] = i;
m_length = m_nRows;
}
if (GetActivePane(&rowActive, &colActive) != NULL &&
rowActive == rowHide) //colActive == rowHide)
{
if (++rowActive >= m_nRows)
rowActive = 0;
//SetActivePane(rowActive, colActive);
SetActivePane(rowActive, colActive);
}
// hide all row panes
for (int col = 0; col < m_nCols; col++)
{
CWnd* pPaneHide = CSplitterWnd::GetPane(m_arr[rowHide], col);
ASSERT(pPaneHide != NULL);
pPaneHide->ShowWindow(SW_HIDE);
for (int row = rowHide + 1; row < m_length; row++)
{
if (m_arr[row] < m_nRows )
{
CWnd* pPane = CSplitterWnd::GetPane(m_arr[row], col);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row-1, col));
m_arr[row]--;
}
}
pPaneHide->SetDlgCtrlID(
Id_short(m_nRows -1 , col));
}
int oldsize=m_pRowInfo[m_arr[rowHide]].nCurSize;
for (int row=rowHide;row<(m_length-1);row++)
{
if (m_arr[row+1] < m_nRows )
{
m_pRowInfo[m_arr[row]].nCurSize=m_pRowInfo[m_arr[row+1]].nCurSize;
m_pRowInfo[m_arr[row]].nIdealSize=m_pRowInfo[m_arr[row+1]].nCurSize;
}
}
if (rowToResize!=-1)
{
m_pRowInfo[m_arr[rowToResize]].nCurSize+=oldsize+m_cySplitter;
m_pRowInfo[m_arr[rowToResize]].nIdealSize+=oldsize+m_cySplitter;
oldsize+=0x10000*(rowToResize+1);
}
m_pRowInfo[m_nRows - 1].nCurSize =oldsize;
m_pRowInfo[m_nRows - 1].nIdealSize =oldsize;
m_arr[rowHide] = m_nRows-1;
m_nRows--;
RecalcLayout();
}
void CSplitterWndEx::HideColumn(int colHide, int colToResize)
{
ASSERT_VALID(this);
ASSERT(m_nCols > 1);
if (m_arr)
ASSERT(m_arr[colHide] < m_nCols);
// if the col has an active window -- change it
int colActive, rowActive;
if (!m_arr)
{
m_arr = new int[m_nCols];
for (int i = 0; i < m_nCols; i++)
m_arr[i] = i;
m_length = m_nCols;
}
if (GetActivePane(&rowActive, &colActive) != NULL &&
colActive == colHide)
{
if (++colActive >= m_nCols)
colActive = 0;
SetActivePane(rowActive, colActive);
}
// hide all row panes
for (int row = 0; row < m_nRows; row++)
{
CWnd* pPaneHide = CSplitterWnd::GetPane(row, m_arr[colHide]);
ASSERT(pPaneHide != NULL);
pPaneHide->ShowWindow(SW_HIDE);
for (int col = colHide + 1; col < m_length; col++)
{
if (m_arr[col] < m_nCols )
{
CWnd* pPane = CSplitterWnd::GetPane(row, m_arr[col]);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row, col-1));
m_arr[col]--;
}
}
pPaneHide->SetDlgCtrlID(
Id_short(row, m_nCols -1));
}
int oldsize = m_pColInfo[m_arr[colHide]].nCurSize;
for (int col = colHide; col < (m_length - 1); ++col)
{
if (m_arr[col + 1] < m_nCols)
{
m_pColInfo[m_arr[col]].nCurSize = m_pColInfo[m_arr[col + 1]].nCurSize;
m_pColInfo[m_arr[col]].nIdealSize = m_pColInfo[m_arr[col + 1]].nCurSize;
}
}
if (colToResize != -1)
{
m_pColInfo[m_arr[colToResize]].nCurSize += oldsize + m_cxSplitter;
m_pColInfo[m_arr[colToResize]].nIdealSize += oldsize + m_cxSplitter;
oldsize += 0x10000 * (colToResize + 1);
}
m_pColInfo[m_nCols - 1].nCurSize = oldsize;
m_pColInfo[m_nCols - 1].nIdealSize = oldsize;
m_arr[colHide] = m_nCols - 1;
m_nCols--;
RecalcLayout();
}
BEGIN_MESSAGE_MAP(CSplitterWndEx, CSplitterWnd)
//{{AFX_MSG_MAP(CSplitterWndEx)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CWnd* CSplitterWndEx::GetPane(int row, int col)
{
if (!m_arr)
return CSplitterWnd::GetPane(row,col);
else
{
ASSERT_VALID(this);
CWnd* pView = GetDlgItem(IdFromRowCol(m_arr[row], col));
ASSERT(pView != NULL); // panes can be a CWnd, but are usually CViews
return pView;
}
}
int CSplitterWndEx::IdFromRowCol(int row, int col) const
{
ASSERT_VALID(this);
ASSERT(row >= 0);
ASSERT(row < (m_arr?m_length:m_nRows));
ASSERT(col >= 0);
ASSERT(col < m_nCols);
return AFX_IDW_PANE_FIRST + row * 16 + col;
}
BOOL CSplitterWndEx::IsChildPane(CWnd* pWnd, int* pRow, int* pCol)
{
ASSERT_VALID(this);
ASSERT_VALID(pWnd);
UINT nID = ::GetDlgCtrlID(pWnd->m_hWnd);
if (IsChild(pWnd) && nID >= AFX_IDW_PANE_FIRST && nID <= AFX_IDW_PANE_LAST)
{
if (pWnd->GetParent()!=this)
return FALSE;
if (pRow != NULL)
*pRow = (nID - AFX_IDW_PANE_FIRST) / 16;
if (pCol != NULL)
*pCol = (nID - AFX_IDW_PANE_FIRST) % 16;
ASSERT(pRow == NULL || *pRow < (m_arr?m_length:m_nRows));
ASSERT(pCol == NULL || *pCol < m_nCols);
return TRUE;
}
else
{
if (pRow != NULL)
*pRow = -1;
if (pCol != NULL)
*pCol = -1;
return FALSE;
}
}
CWnd* CSplitterWndEx::GetActivePane(int* pRow, int* pCol)
// return active view, NULL when no active view
{
ASSERT_VALID(this);
// attempt to use active view of frame window
CWnd* pView = NULL;
CFrameWnd* pFrameWnd = GetParentFrame();
ASSERT_VALID(pFrameWnd);
pView = pFrameWnd->GetActiveView();
// failing that, use the current focus
if (pView == NULL)
pView = GetFocus();
// make sure the pane is a child pane of the splitter
if (pView != NULL && !IsChildPane(pView, pRow, pCol))
pView = NULL;
return pView;
}
BOOL CSplitterWndEx::IsRowHidden(int row)
{
return m_arr[row]>=m_nRows;
}
void CSplitterWndEx::GetRowInfoEx(int row, int &cyCur, int &cyMin)
{
if (!m_arr)
GetRowInfo(row,cyCur,cyMin);
else
{
if (m_pRowInfo[m_arr[row]].nCurSize>0x10000)
cyCur=m_pRowInfo[m_arr[row]].nCurSize/0x10000;
else
cyCur=m_pRowInfo[m_arr[row]].nCurSize%0x10000;
cyMin=0;
}
}
__int64 CSplitterWndEx::GetSizes() const
{
LARGE_INTEGER v;
int dummy;
int s1, s2;
if (BarIsHorizontal())
{
GetRowInfo(0, s1, dummy);
GetRowInfo(1, s2, dummy);
v.HighPart = s1;
v.LowPart = s2;
}
else
{
GetColumnInfo(0, s1, dummy);
GetColumnInfo(1, s2, dummy);
v.HighPart = s1;
v.LowPart = s2;
}
return v.QuadPart;
}
| 23.890323 | 113 | 0.606985 | JyothsnaMididoddi26 |
6ac2dd4a5672e1d1a4cd0dfb9fab41d0c691795e | 13,736 | cpp | C++ | bindings/python/src/Shape.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | bindings/python/src/Shape.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | bindings/python/src/Shape.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | ////////////////////////////////////////////////////////////
//
// PySFML - Python binding for SFML (Simple and Fast Multimedia Library)
// Copyright (C) 2007, 2008 Rémi Koenig (remi.k2620@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#include "Shape.hpp"
#include <SFML/Graphics/Color.hpp>
#include "Color.hpp"
#include "compat.hpp"
extern PyTypeObject PySfColorType;
extern PyTypeObject PySfDrawableType;
static void
PySfShape_dealloc(PySfShape* self)
{
delete self->obj;
free_object(self);
}
static PyObject *
PySfShape_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PySfShape *self;
self = (PySfShape *)type->tp_alloc(type, 0);
if (self != NULL)
{
self->obj = new sf::Shape();
self->IsCustom = false;
}
return (PyObject *)self;
}
// void AddPoint(float X, float Y, const Color& Col = Color(255, 255, 255), const Color& OutlineCol = Color(0, 0, 0));
static PyObject *
PySfShape_AddPoint(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X", "Y", "Col", "OutlineCol", NULL};
float X, Y;
sf::Color *Col, *OutlineCol;
PySfColor *ColTmp=NULL, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "ff|O!O!:Shape.AddPoint", (char **)kwlist, &X, &Y, &PySfColorType, &ColTmp, &PySfColorType, &OutlineColTmp))
return NULL;
if (ColTmp)
{
PySfColorUpdate(ColTmp);
Col = ColTmp->obj;
}
else
Col = (sf::Color *)&sf::Color::White;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
self->obj->AddPoint(X, Y, *Col, *OutlineCol);
Py_RETURN_NONE;
}
static PyObject *
PySfShape_SetOutlineWidth(PySfShape* self, PyObject *args)
{
self->obj->SetOutlineWidth(PyFloat_AsDouble(args));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_GetOutlineWidth(PySfShape* self)
{
return PyFloat_FromDouble(self->obj->GetOutlineWidth());
}
// static Shape Line(float X0, float Y0, float X1, float Y1, float Thickness, const Color& Col, float Outline = 0.f, const Color& OutlineCol = sf::Color(0, 0, 0));
static PyObject *
PySfShape_Line(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X0", "Y0", "X1", "Y1", "Thickness", "Col", "Outline", "OutlineCol", NULL};
PySfShape *Line = GetNewPySfShape();
float X0, Y0, X1, Y1, Thickness, Outline = 0.f;
sf::Color *OutlineCol;
PySfColor *ColTmp, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffffO!|fO!:Shape.Line", (char **)kwlist, &X0, &Y0, &X1, &Y1, &Thickness, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp))
return NULL;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
PySfColorUpdate(ColTmp);
Line->obj = new sf::Shape(sf::Shape::Line(X0, Y0, X1, Y1, Thickness, *(ColTmp->obj), Outline, *OutlineCol));
return (PyObject *)Line;
}
// static Shape Rectangle(float X0, float Y0, float X1, float Y1, const Color& Col, float Outline = 0.f, const Color& OutlineCol = sf::Color(0, 0, 0));
static PyObject *
PySfShape_Rectangle(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X0", "Y0", "X1", "Y1", "Col", "Outline", "OutlineCol", NULL};
PySfShape *Rectangle = GetNewPySfShape();
float X0, Y0, X1, Y1, Outline = 0.f;
sf::Color *OutlineCol;
PySfColor *ColTmp, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "ffffO!|fO!:Shape.Rectangle", (char **)kwlist, &X0, &Y0, &X1, &Y1, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp))
return NULL;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
PySfColorUpdate(ColTmp);
Rectangle->obj = new sf::Shape(sf::Shape::Rectangle(X0, Y0, X1, Y1, *(ColTmp->obj), Outline, *OutlineCol));
return (PyObject *)Rectangle;
}
// static Shape Circle(float X, float Y, float Radius, const Color& Col, float Outline = 0.f, const Color& OutlineCol = sf::Color(0, 0, 0));
static PyObject *
PySfShape_Circle(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X", "Y", "Radius", "Col", "Outline", "OutlineCol", NULL};
PySfShape *Circle = GetNewPySfShape();
float X, Y, Radius, Outline = 0.f;
sf::Color *OutlineCol;
PySfColor *ColTmp, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffO!|fO!:Shape.Circle", (char **)kwlist, &X, &Y, &Radius, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp))
return NULL;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
PySfColorUpdate(ColTmp);
Circle->obj = new sf::Shape(sf::Shape::Circle(X, Y, Radius, *(ColTmp->obj), Outline, *OutlineCol));
return (PyObject *)Circle;
}
static PyObject *
PySfShape_GetPointPosition(PySfShape* self, PyObject *args)
{
sf::Vector2f result = self->obj->GetPointPosition(PyLong_AsUnsignedLong(args));
return Py_BuildValue("ff", result.x, result.y);
}
static PyObject *
PySfShape_GetPointColor(PySfShape* self, PyObject *args)
{
PySfColor *PyColor = GetNewPySfColor();
PyColor->obj = new sf::Color(self->obj->GetPointColor(PyLong_AsUnsignedLong(args)));
PyColor->r = PyColor->obj->r;
PyColor->g = PyColor->obj->g;
PyColor->b = PyColor->obj->b;
PyColor->a = PyColor->obj->a;
return (PyObject *)PyColor;
}
static PyObject *
PySfShape_GetPointOutlineColor(PySfShape* self, PyObject *args)
{
PySfColor *PyColor = GetNewPySfColor();
PyColor->obj = new sf::Color(self->obj->GetPointOutlineColor(PyLong_AsUnsignedLong(args)));
PyColor->r = PyColor->obj->r;
PyColor->g = PyColor->obj->g;
PyColor->b = PyColor->obj->b;
PyColor->a = PyColor->obj->a;
return (PyObject *)PyColor;
}
static PyObject *
PySfShape_SetPointPosition(PySfShape* self, PyObject *args)
{
unsigned int Index;
float X, Y;
if (!PyArg_ParseTuple(args, "Iff:Shape.SetPointPosition", &Index, &X, &Y))
return NULL;
self->obj->SetPointPosition(Index, X, Y);
Py_RETURN_NONE;
}
static PyObject *
PySfShape_SetPointColor(PySfShape* self, PyObject *args)
{
unsigned int Index;
PySfColor *Color;
if (!PyArg_ParseTuple(args, "IO!:Shape.SetPointColor", &Index, &PySfColorType, &Color))
return NULL;
PySfColorUpdate(Color);
self->obj->SetPointColor(Index, *(Color->obj));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_SetPointOutlineColor(PySfShape* self, PyObject *args)
{
unsigned int Index;
PySfColor *Color;
if (!PyArg_ParseTuple(args, "IO!:Shape.SetPointOutlineColor", &Index, &PySfColorType, &Color))
return NULL;
PySfColorUpdate(Color);
self->obj->SetPointOutlineColor(Index, *(Color->obj));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_GetNbPoints(PySfShape* self, PyObject *args)
{
return PyLong_FromUnsignedLong(self->obj->GetNbPoints());
}
static PyObject *
PySfShape_EnableFill(PySfShape* self, PyObject *args)
{
self->obj->EnableFill(PyBool_AsBool(args));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_EnableOutline(PySfShape* self, PyObject *args)
{
self->obj->EnableOutline(PyBool_AsBool(args));
Py_RETURN_NONE;
}
static PyMethodDef PySfShape_methods[] = {
{"GetPointPosition", (PyCFunction)PySfShape_GetPointPosition, METH_O, "GetPointPosition(Index)\n\
Get the position of a point.\n\
Index : Index-th point."},
{"GetPointColor", (PyCFunction)PySfShape_GetPointColor, METH_O, "GetPointColor(Index)\n\
Get the color of a point.\n Index : Index-th point."},
{"GetPointOutlineColor", (PyCFunction)PySfShape_GetPointOutlineColor, METH_O, "GetPointOutlineColor(Index)\n\
Get the outline color of a point.\n Index : Index-th point."},
{"SetPointPosition", (PyCFunction)PySfShape_SetPointPosition, METH_VARARGS, "SetPointPosition(Index, X, Y).\n\
Set the position of a point\n\
Index : Index of the point, in range [0, GetNbPoints() - 1]\n\
X : New X coordinate of the Index-th point\n\
Y : New Y coordinate of the Index-th point."},
{"SetPointColor", (PyCFunction)PySfShape_SetPointColor, METH_VARARGS, "SetPointColor(Index, Color).\n\
Set the color of a point\n\
Index : Index of the point, in range [0, GetNbPoints() - 1]\n\
Col : New color of the Index-th point."},
{"SetPointOutlineColor", (PyCFunction)PySfShape_SetPointOutlineColor, METH_VARARGS, "SetPointOutlineColor(Index, Color).\n\
Set the outline color of a point\n\
Index : Index of the point, in range [0, GetNbPoints() - 1]\n\
Col : New color of the Index-th point."},
{"GetNbPoints", (PyCFunction)PySfShape_GetNbPoints, METH_NOARGS, "GetNbPoints()\n\
Get the number of points composing the shape."},
{"EnableFill", (PyCFunction)PySfShape_EnableFill, METH_O, "EnableFill(Enable)\n\
Enable or disable filling the shape. Fill is enabled by default.\n\
Enable : True to enable, false to disable."},
{"EnableOutline", (PyCFunction)PySfShape_EnableOutline, METH_O, "EnableOutline(Enable)\n\
Enable or disable drawing the shape outline. Outline is enabled by default.\n\
Enable : True to enable, false to disable"},
{"AddPoint", (PyCFunction)PySfShape_AddPoint, METH_VARARGS | METH_KEYWORDS, "AddPoint(X, Y, Col=sf.Color.White, OutlineCol=sf.Color.Black)\n\
Add a point to the shape.\n\
X : X coordinate of the point\n\
Y : Y coordinate of the point\n\
Col : Color of the point (white by default)\n\
OutlineCol : Outline color of the point (black by default)."},
{"SetOutlineWidth", (PyCFunction)PySfShape_SetOutlineWidth, METH_O, "SetOutlineWidth(Width)\n\
Change the width of the shape outline.\n\
Width : New width (use 0 to remove the outline)."},
{"GetOutlineWidth", (PyCFunction)PySfShape_GetOutlineWidth, METH_NOARGS, "GetOutlineWidth()\n\
Get the width of the shape outline."},
{"Line", (PyCFunction)PySfShape_Line, METH_STATIC | METH_VARARGS | METH_KEYWORDS, "Line(X0, Y0, X1, Y1, Thickness, Col, Outline = 0., OutlineCol = sf.Color(0, 0, 0))\n\
Create a shape made of a single line.\n\
X0 : X coordinate of the first point.\n\
Y0 : Y coordinate of the first point.\n\
X1 : X coordinate of the second point.\n\
Y1 : Y coordinate of the second point.\n\
Thickness : Line thickness.\n\
Col : Color used to draw the line\n\
Outline : Outline width (0 by default)\n\
OutlineCol : Color used to draw the outline (black by default)."},
{"Rectangle", (PyCFunction)PySfShape_Rectangle, METH_STATIC | METH_VARARGS | METH_KEYWORDS, "Rectangle(X0, Y0, X1, Y1, Col, Outline = 0., OutlineCol = sf.Color(0, 0, 0))\n\
Create a shape made of a single rectangle.\n\
X0 : X coordinate of the first point.\n\
Y0 : Y coordinate of the first point.\n\
X1 : X coordinate of the second point.\n\
Y1 : Y coordinate of the second point.\n\
Col : Color used to fill the rectangle.\n\
Outline : Outline width (0 by default).\n\
OutlineCol : Color used to draw the outline (black by default)."},
{"Circle", (PyCFunction)PySfShape_Circle, METH_STATIC | METH_VARARGS | METH_KEYWORDS, "Circle(X, Y, Radius, Col, Outline = 0., OutlineCol = sf.Color(0, 0, 0))\n\
Create a shape made of a single circle.\n\
X : X coordinate of the center.\n\
Y : Y coordinate of the center.\n\
Radius : Radius\n\
Col : Color used to fill the rectangle.\n\
Outline : Outline width (0 by default).\n\
OutlineCol : Color used to draw the outline (black by default)."},
{NULL} /* Sentinel */
};
PyTypeObject PySfShapeType = {
head_init
"Shape", /*tp_name*/
sizeof(PySfShape), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PySfShape_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Shape defines a drawable convex shape ; it also defines helper functions to draw simple shapes like lines, rectangles, circles, etc.\nDefault constructor: Shape()", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
PySfShape_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PySfDrawableType, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PySfShape_new, /* tp_new */
};
PySfShape *
GetNewPySfShape()
{
PySfShape *Shape = PyObject_New(PySfShape, &PySfShapeType);
Shape->IsCustom = false;
return Shape;
}
| 36.147368 | 188 | 0.689866 | yoyonel |
6ac3b8ec5b976243d82d875267efa94e4481c6b1 | 421 | cpp | C++ | 202009-1.cpp | ZubinGou/CCF-CSP | 6d8b8de66c4ffc6c058efdf021e3a546fccdea44 | [
"MIT"
] | null | null | null | 202009-1.cpp | ZubinGou/CCF-CSP | 6d8b8de66c4ffc6c058efdf021e3a546fccdea44 | [
"MIT"
] | null | null | null | 202009-1.cpp | ZubinGou/CCF-CSP | 6d8b8de66c4ffc6c058efdf021e3a546fccdea44 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <algorithm>
#define MAX_N 250
using namespace std;
pair<int, int> p[MAX_N];
int main()
{
int n, x, y, a, b;
scanf("%d%d%d", &n, &x, &y);
for (int i = 0; i < n; i++)
{
scanf("%d%d", &a, &b);
p[i] = make_pair((x-a) * (x-a) + (y-b) * (y - b), i + 1);
}
sort(p, p + n);
printf("%d\n%d\n%d\n", p[0].second, p[1].second, p[2].second);
return 0;
} | 18.304348 | 66 | 0.458432 | ZubinGou |
6ac3c7ed0ea2773620a4a6499251243360d79be0 | 394 | cpp | C++ | src/Airline/Ticket.cpp | jlcrodrigues/feup-aed | 9586e984cd725292c7d76645b146ec969f788e19 | [
"MIT"
] | 7 | 2021-12-22T21:57:38.000Z | 2022-01-05T18:08:17.000Z | src/Airline/Ticket.cpp | jlcrodrigues/feup-aed | 9586e984cd725292c7d76645b146ec969f788e19 | [
"MIT"
] | null | null | null | src/Airline/Ticket.cpp | jlcrodrigues/feup-aed | 9586e984cd725292c7d76645b146ec969f788e19 | [
"MIT"
] | 1 | 2021-12-23T00:35:06.000Z | 2021-12-23T00:35:06.000Z | #include "Ticket.h"
using namespace std;
Ticket::Ticket(const Flight& flight, const bool& baggage): flight(flight)
{
this->baggage = baggage;
checked_in = false;
}
Flight Ticket::getFlight() const
{
return flight;
}
bool Ticket::getBaggage() const
{
return baggage;
}
void Ticket::checkIn()
{
checked_in = true;
}
bool Ticket::hasCheckedIn() const
{
return checked_in;
} | 13.586207 | 73 | 0.687817 | jlcrodrigues |
6acf1f004df6d514d9d82e76649e16b7e6e731b1 | 15,832 | cpp | C++ | examples/SharedMemory/plugins/fileIOPlugin/fileIOPlugin.cpp | aaronfranke/bullet3 | 0c6c7976baeb43204dc8adeb3235d960b2a9b340 | [
"Zlib"
] | 2 | 2021-11-08T02:53:13.000Z | 2021-11-08T09:40:43.000Z | examples/SharedMemory/plugins/fileIOPlugin/fileIOPlugin.cpp | aaronfranke/bullet3 | 0c6c7976baeb43204dc8adeb3235d960b2a9b340 | [
"Zlib"
] | null | null | null | examples/SharedMemory/plugins/fileIOPlugin/fileIOPlugin.cpp | aaronfranke/bullet3 | 0c6c7976baeb43204dc8adeb3235d960b2a9b340 | [
"Zlib"
] | null | null | null | #include "fileIOPlugin.h"
#include "../../SharedMemoryPublic.h"
#include "../b3PluginContext.h"
#include <stdio.h>
#include "../../../CommonInterfaces/CommonFileIOInterface.h"
#include "../../../Utils/b3ResourcePath.h"
#include "Bullet3Common/b3HashMap.h"
#include <string.h> //memcpy/strlen
#ifndef B3_EXCLUDE_DEFAULT_FILEIO
#include "../../../Utils/b3BulletDefaultFileIO.h"
#endif //B3_EXCLUDE_DEFAULT_FILEIO
#ifdef B3_USE_ZIPFILE_FILEIO
#include "zipFileIO.h"
#endif //B3_USE_ZIPFILE_FILEIO
#ifdef B3_USE_CNS_FILEIO
#include "CNSFileIO.h"
#endif //B3_USE_CNS_FILEIO
#define B3_MAX_FILEIO_INTERFACES 1024
struct WrapperFileHandle
{
CommonFileIOInterface* childFileIO;
int m_childFileHandle;
};
struct InMemoryFile
{
char* m_buffer;
int m_fileSize;
};
struct InMemoryFileAccessor
{
InMemoryFile* m_file;
int m_curPos;
};
struct InMemoryFileIO : public CommonFileIOInterface
{
b3HashMap<b3HashString,InMemoryFile*> m_fileCache;
InMemoryFileAccessor m_fileHandles[B3_MAX_FILEIO_INTERFACES];
int m_numAllocs;
int m_numFrees;
InMemoryFileIO()
:CommonFileIOInterface(eInMemoryFileIO,0)
{
m_numAllocs=0;
m_numFrees=0;
for (int i=0;i<B3_FILEIO_MAX_FILES;i++)
{
m_fileHandles[i].m_curPos = 0;
m_fileHandles[i].m_file = 0;
}
}
virtual ~InMemoryFileIO()
{
clearCache();
if (m_numAllocs != m_numFrees)
{
printf("Error: InMemoryFile::~InMemoryFileIO (numAllocs %d numFrees %d\n", m_numAllocs, m_numFrees);
}
}
void clearCache()
{
for (int i=0;i<m_fileCache.size();i++)
{
b3HashString name = m_fileCache.getKeyAtIndex(i);
InMemoryFile** memPtr = m_fileCache.getAtIndex(i);
if (memPtr && *memPtr)
{
InMemoryFile* mem = *memPtr;
freeBuffer(mem->m_buffer);
m_numFrees++;
delete (mem);
m_numFrees++;
m_fileCache.remove(name);
}
}
}
char* allocateBuffer(int len)
{
char* buffer = 0;
if (len)
{
m_numAllocs++;
buffer = new char[len];
}
return buffer;
}
void freeBuffer(char* buffer)
{
delete[] buffer;
}
virtual int registerFile(const char* fileName, char* buffer, int len)
{
m_numAllocs++;
InMemoryFile* f = new InMemoryFile();
f->m_buffer = buffer;
f->m_fileSize = len;
b3HashString key(fileName);
m_fileCache.insert(key,f);
return 0;
}
void removeFileFromCache(const char* fileName)
{
InMemoryFile* f = getInMemoryFile(fileName);
if (f)
{
m_fileCache.remove(fileName);
freeBuffer(f->m_buffer);
delete (f);
}
}
InMemoryFile* getInMemoryFile(const char* fileName)
{
InMemoryFile** fPtr = m_fileCache[fileName];
if (fPtr && *fPtr)
{
return *fPtr;
}
return 0;
}
virtual int fileOpen(const char* fileName, const char* mode)
{
//search a free slot
int slot = -1;
for (int i=0;i<B3_FILEIO_MAX_FILES;i++)
{
if (m_fileHandles[i].m_file==0)
{
slot=i;
break;
}
}
if (slot>=0)
{
InMemoryFile* f = getInMemoryFile(fileName);
if (f)
{
m_fileHandles[slot].m_curPos = 0;
m_fileHandles[slot].m_file = f;
} else
{
slot=-1;
}
}
//printf("InMemoryFileIO fileOpen %s, %d\n", fileName, slot);
return slot;
}
virtual int fileRead(int fileHandle, char* destBuffer, int numBytes)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES)
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
//if (numBytes>1)
// printf("curPos = %d\n", f.m_curPos);
if (f.m_curPos+numBytes <= f.m_file->m_fileSize)
{
memcpy(destBuffer,f.m_file->m_buffer+f.m_curPos,numBytes);
f.m_curPos+=numBytes;
//if (numBytes>1)
// printf("read %d bytes, now curPos = %d\n", numBytes, f.m_curPos);
return numBytes;
} else
{
if (numBytes!=1)
{
printf("InMemoryFileIO::fileRead Attempt to read beyond end of file\n");
}
}
}
}
return 0;
}
virtual int fileWrite(int fileHandle,const char* sourceBuffer, int numBytes)
{
return 0;
}
virtual void fileClose(int fileHandle)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES)
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
m_fileHandles[fileHandle].m_file = 0;
m_fileHandles[fileHandle].m_curPos = 0;
//printf("InMemoryFileIO fileClose %d\n", fileHandle);
}
}
}
virtual bool findResourcePath(const char* fileName, char* resourcePathOut, int resourcePathMaxNumBytes)
{
InMemoryFile* f = getInMemoryFile(fileName);
int fileNameLen = strlen(fileName);
if (f && fileNameLen<(resourcePathMaxNumBytes-1))
{
memcpy(resourcePathOut, fileName, fileNameLen);
resourcePathOut[fileNameLen]=0;
return true;
}
return false;
}
virtual char* readLine(int fileHandle, char* destBuffer, int numBytes)
{
int numRead = 0;
int endOfFile = 0;
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES )
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
//return ::fgets(destBuffer, numBytes, m_fileHandles[fileHandle]);
char c = 0;
do
{
int bytesRead = fileRead(fileHandle,&c,1);
if (bytesRead != 1)
{
endOfFile = 1;
c=0;
}
if (c && c!='\n')
{
if (c!=13)
{
destBuffer[numRead++]=c;
} else
{
destBuffer[numRead++]=0;
}
}
} while (c != 0 && c != '\n' && numRead<(numBytes-1));
}
}
if (numRead==0 && endOfFile)
{
return 0;
}
if (numRead<numBytes)
{
if (numRead >=0)
{
destBuffer[numRead]=0;
}
return &destBuffer[0];
} else
{
if (endOfFile==0)
{
printf("InMemoryFileIO::readLine readLine warning: numRead=%d, numBytes=%d\n", numRead, numBytes);
}
}
return 0;
}
virtual int getFileSize(int fileHandle)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES )
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
return f.m_file->m_fileSize;
}
}
return 0;
}
virtual void enableFileCaching(bool enable)
{
(void)enable;
}
};
struct WrapperFileIO : public CommonFileIOInterface
{
CommonFileIOInterface* m_availableFileIOInterfaces[B3_MAX_FILEIO_INTERFACES];
int m_numWrapperInterfaces;
WrapperFileHandle m_wrapperFileHandles[B3_MAX_FILEIO_INTERFACES];
InMemoryFileIO m_cachedFiles;
bool m_enableFileCaching;
WrapperFileIO()
:CommonFileIOInterface(0,0),
m_numWrapperInterfaces(0),
m_enableFileCaching(true)
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
m_availableFileIOInterfaces[i]=0;
m_wrapperFileHandles[i].childFileIO=0;
m_wrapperFileHandles[i].m_childFileHandle=0;
}
//addFileIOInterface(&m_cachedFiles);
}
virtual ~WrapperFileIO()
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
removeFileIOInterface(i);
}
m_cachedFiles.clearCache();
}
int addFileIOInterface(CommonFileIOInterface* fileIO)
{
int result = -1;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_availableFileIOInterfaces[i]==0)
{
m_availableFileIOInterfaces[i]=fileIO;
result = i;
break;
}
}
return result;
}
CommonFileIOInterface* getFileIOInterface(int fileIOIndex)
{
if (fileIOIndex>=0 && fileIOIndex<B3_MAX_FILEIO_INTERFACES)
{
return m_availableFileIOInterfaces[fileIOIndex];
}
return 0;
}
void removeFileIOInterface(int fileIOIndex)
{
if (fileIOIndex>=0 && fileIOIndex<B3_MAX_FILEIO_INTERFACES)
{
if (m_availableFileIOInterfaces[fileIOIndex])
{
delete m_availableFileIOInterfaces[fileIOIndex];
m_availableFileIOInterfaces[fileIOIndex]=0;
}
}
}
virtual int fileOpen(const char* fileName, const char* mode)
{
//find an available wrapperFileHandle slot
int wrapperFileHandle=-1;
int slot = -1;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_wrapperFileHandles[i].childFileIO==0)
{
slot=i;
break;
}
}
if (slot>=0)
{
//first check the cache
int cacheHandle = m_cachedFiles.fileOpen(fileName, mode);
if (cacheHandle>=0)
{
m_cachedFiles.fileClose(cacheHandle);
}
if (cacheHandle<0)
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* childFileIO=m_availableFileIOInterfaces[i];
if (childFileIO)
{
int childHandle = childFileIO->fileOpen(fileName, mode);
if (childHandle>=0)
{
if (m_enableFileCaching)
{
int fileSize = childFileIO->getFileSize(childHandle);
char* buffer = 0;
if (fileSize)
{
buffer = m_cachedFiles.allocateBuffer(fileSize);
if (buffer)
{
int readBytes = childFileIO->fileRead(childHandle, buffer, fileSize);
if (readBytes!=fileSize)
{
if (readBytes<fileSize)
{
fileSize = readBytes;
} else
{
printf("WrapperFileIO error: reading more bytes (%d) then reported file size (%d) of file %s.\n", readBytes, fileSize, fileName);
}
}
} else
{
fileSize=0;
}
}
//potentially register a zero byte file, or files that only can be read partially
m_cachedFiles.registerFile(fileName, buffer, fileSize);
}
childFileIO->fileClose(childHandle);
break;
}
}
}
}
{
int childHandle = m_cachedFiles.fileOpen(fileName, mode);
if (childHandle>=0)
{
wrapperFileHandle = slot;
m_wrapperFileHandles[slot].childFileIO = &m_cachedFiles;
m_wrapperFileHandles[slot].m_childFileHandle = childHandle;
} else
{
//figure out what wrapper interface to use
//use the first one that can open the file
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* childFileIO=m_availableFileIOInterfaces[i];
if (childFileIO)
{
int childHandle = childFileIO->fileOpen(fileName, mode);
if (childHandle>=0)
{
wrapperFileHandle = slot;
m_wrapperFileHandles[slot].childFileIO = childFileIO;
m_wrapperFileHandles[slot].m_childFileHandle = childHandle;
break;
}
}
}
}
}
}
return wrapperFileHandle;
}
virtual int fileRead(int fileHandle, char* destBuffer, int numBytes)
{
int fileReadResult=-1;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
fileReadResult = m_wrapperFileHandles[fileHandle].childFileIO->fileRead(
m_wrapperFileHandles[fileHandle].m_childFileHandle, destBuffer, numBytes);
}
}
return fileReadResult;
}
virtual int fileWrite(int fileHandle,const char* sourceBuffer, int numBytes)
{
//todo
return -1;
}
virtual void fileClose(int fileHandle)
{
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
m_wrapperFileHandles[fileHandle].childFileIO->fileClose(
m_wrapperFileHandles[fileHandle].m_childFileHandle);
m_wrapperFileHandles[fileHandle].childFileIO = 0;
m_wrapperFileHandles[fileHandle].m_childFileHandle = -1;
}
}
}
virtual bool findResourcePath(const char* fileName, char* resourcePathOut, int resourcePathMaxNumBytes)
{
if (m_cachedFiles.findResourcePath(fileName, resourcePathOut, resourcePathMaxNumBytes))
return true;
bool found = false;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_availableFileIOInterfaces[i])
{
found = m_availableFileIOInterfaces[i]->findResourcePath(fileName, resourcePathOut, resourcePathMaxNumBytes);
}
if (found)
break;
}
return found;
}
virtual char* readLine(int fileHandle, char* destBuffer, int numBytes)
{
char* result = 0;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
result = m_wrapperFileHandles[fileHandle].childFileIO->readLine(
m_wrapperFileHandles[fileHandle].m_childFileHandle,
destBuffer, numBytes);
}
}
return result;
}
virtual int getFileSize(int fileHandle)
{
int numBytes = 0;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
numBytes = m_wrapperFileHandles[fileHandle].childFileIO->getFileSize(
m_wrapperFileHandles[fileHandle].m_childFileHandle);
}
}
return numBytes;
}
virtual void enableFileCaching(bool enable)
{
m_enableFileCaching = enable;
if (!enable)
{
m_cachedFiles.clearCache();
}
}
};
struct FileIOClass
{
int m_testData;
WrapperFileIO m_fileIO;
FileIOClass()
: m_testData(42),
m_fileIO()
{
}
virtual ~FileIOClass()
{
}
};
B3_SHARED_API int initPlugin_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = new FileIOClass();
context->m_userPointer = obj;
#ifndef B3_EXCLUDE_DEFAULT_FILEIO
obj->m_fileIO.addFileIOInterface(new b3BulletDefaultFileIO());
#endif //B3_EXCLUDE_DEFAULT_FILEIO
return SHARED_MEMORY_MAGIC_NUMBER;
}
B3_SHARED_API int executePluginCommand_fileIOPlugin(struct b3PluginContext* context, const struct b3PluginArguments* arguments)
{
int result=-1;
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
printf("text argument:%s\n", arguments->m_text);
printf("int args: [");
//remove a fileIO type
if (arguments->m_numInts==1)
{
int fileIOIndex = arguments->m_ints[0];
obj->m_fileIO.removeFileIOInterface(fileIOIndex);
}
if (arguments->m_numInts==2)
{
int action = arguments->m_ints[0];
switch (action)
{
case eAddFileIOAction:
{
//if the fileIO already exists, skip this action
int fileIOType = arguments->m_ints[1];
bool alreadyExists = false;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* fileIO = obj->m_fileIO.getFileIOInterface(i);
if (fileIO)
{
if (fileIO->m_fileIOType == fileIOType)
{
if (fileIO->m_pathPrefix && strcmp(fileIO->m_pathPrefix,arguments->m_text)==0)
{
result = i;
alreadyExists = true;
break;
}
}
}
}
//create new fileIO interface
if (!alreadyExists)
{
switch (fileIOType)
{
case ePosixFileIO:
{
#ifdef B3_EXCLUDE_DEFAULT_FILEIO
printf("ePosixFileIO is not enabled in this build.\n");
#else
result = obj->m_fileIO.addFileIOInterface(new b3BulletDefaultFileIO(ePosixFileIO, arguments->m_text));
#endif
break;
}
case eZipFileIO:
{
#ifdef B3_USE_ZIPFILE_FILEIO
if (arguments->m_text[0])
{
result = obj->m_fileIO.addFileIOInterface(new ZipFileIO(eZipFileIO, arguments->m_text, &obj->m_fileIO));
}
#else
printf("eZipFileIO is not enabled in this build.\n");
#endif
break;
}
case eCNSFileIO:
{
#ifdef B3_USE_CNS_FILEIO
result = obj->m_fileIO.addFileIOInterface(new CNSFileIO(eCNSFileIO, arguments->m_text));
#else//B3_USE_CNS_FILEIO
printf("CNSFileIO is not enabled in this build.\n");
#endif //B3_USE_CNS_FILEIO
break;
}
default:
{
}
}//switch (fileIOType)
}//if (!alreadyExists)
break;
}
case eRemoveFileIOAction:
{
//remove fileIO interface
int fileIOIndex = arguments->m_ints[1];
obj->m_fileIO.removeFileIOInterface(fileIOIndex);
result = fileIOIndex;
break;
}
default:
{
printf("executePluginCommand_fileIOPlugin: unknown action\n");
}
}
}
return result;
}
B3_SHARED_API struct CommonFileIOInterface* getFileIOFunc_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
return &obj->m_fileIO;
}
B3_SHARED_API void exitPlugin_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
delete obj;
context->m_userPointer = 0;
}
| 22.552707 | 141 | 0.669214 | aaronfranke |
6ad19fa15572e3b9d4ea08e8a450cdf5a0a96ed6 | 1,638 | cpp | C++ | exportobjects/exportmaterial.cpp | walbourn/contentexporter | 2559ac92bbb1ce1409f1c63b51957ea088427b24 | [
"MIT"
] | 62 | 2015-04-14T22:28:11.000Z | 2022-03-28T07:02:28.000Z | exportobjects/exportmaterial.cpp | TienAska/contentexporter | 746cf69136b63b0502e9e6e8687ed66b5a268103 | [
"MIT"
] | 18 | 2015-07-01T18:29:14.000Z | 2021-11-13T12:28:08.000Z | exportobjects/exportmaterial.cpp | TienAska/contentexporter | 746cf69136b63b0502e9e6e8687ed66b5a268103 | [
"MIT"
] | 21 | 2015-05-31T07:57:37.000Z | 2021-07-30T10:20:06.000Z | //-------------------------------------------------------------------------------------
// ExportMaterial.cpp
//
// Advanced Technology Group (ATG)
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=226208
//-------------------------------------------------------------------------------------
#include "stdafx.h"
#include "ExportMaterial.h"
using namespace ATG;
ExportMaterial::ExportMaterial()
: ExportBase(nullptr),
m_pMaterialDefinition(nullptr),
m_bTransparent(false)
{
}
ExportMaterial::ExportMaterial(ExportString name)
: ExportBase(name),
m_pMaterialDefinition(nullptr),
m_bTransparent(false)
{
}
ExportMaterial::~ExportMaterial()
{
}
ExportMaterialParameter* ExportMaterial::FindParameter(const ExportString strName)
{
MaterialParameterList::iterator iter = m_Parameters.begin();
MaterialParameterList::iterator end = m_Parameters.end();
while (iter != end)
{
ExportMaterialParameter& param = *iter;
if (param.Name == strName)
return ¶m;
++iter;
}
return nullptr;
}
ExportString ExportMaterial::GetDefaultDiffuseMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultDiffuseMapTextureName);
}
ExportString ExportMaterial::GetDefaultNormalMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultNormalMapTextureName);
}
ExportString ExportMaterial::GetDefaultSpecularMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultSpecMapTextureName);
}
| 26 | 88 | 0.639805 | walbourn |
6ad1d9211afa891af4726132a404a8fd65ccf94f | 1,012 | cpp | C++ | Client/ui/AddFriendWidget.cpp | LiardeauxQ/Babel | 6cdd475b8947f6a8b0d1c4325a06dfd9bfa65e72 | [
"MIT"
] | 1 | 2020-02-12T12:02:19.000Z | 2020-02-12T12:02:19.000Z | Client/ui/AddFriendWidget.cpp | LiardeauxQ/Babel | 6cdd475b8947f6a8b0d1c4325a06dfd9bfa65e72 | [
"MIT"
] | null | null | null | Client/ui/AddFriendWidget.cpp | LiardeauxQ/Babel | 6cdd475b8947f6a8b0d1c4325a06dfd9bfa65e72 | [
"MIT"
] | 3 | 2020-02-12T12:02:22.000Z | 2021-10-11T11:00:24.000Z | //
// Created by Quentin Liardeaux on 10/5/19.
//
#include "AddFriendWidget.hpp"
ui::AddFriendWidget::AddFriendWidget(boost::shared_ptr<NotificationHandler> notifHandler, QWidget *parent) :
QWidget(parent),
notifHandler_(notifHandler) {
QPointer<QPushButton> closeButton = new QPushButton(tr("Close"));
usernameLineEdit_ = QSharedPointer<QLineEdit>(new QLineEdit());
QPointer<QLabel> usernameLabel = new QLabel(tr("Username:"));
QPointer<QLabel> passwordLabel = new QLabel(tr("Password:"));
connect(closeButton, SIGNAL(clicked()), this, SLOT(closeTap()));
QPointer<QFormLayout> formLayout = new QFormLayout();
formLayout->addRow(closeButton);
formLayout->addRow(usernameLabel, usernameLineEdit_.get());
setLayout(formLayout);
setWindowTitle(tr("Add a friend"));
}
void ui::AddFriendWidget::closeTap()
{
for (auto action : actions()) {
if (action->text() == "close") {
action->trigger();
break;
}
}
}
| 28.111111 | 108 | 0.667984 | LiardeauxQ |
6ad8199849dd6c3c158dc0e36f431799f55afe25 | 16,809 | cpp | C++ | tests/ProxyTest.cpp | derp-caf/external_skia | b09dc92e00edce8366085aaad7dcce94ceb11b69 | [
"BSD-3-Clause"
] | 1 | 2019-05-29T09:54:38.000Z | 2019-05-29T09:54:38.000Z | tests/ProxyTest.cpp | derp-caf/external_skia | b09dc92e00edce8366085aaad7dcce94ceb11b69 | [
"BSD-3-Clause"
] | null | null | null | tests/ProxyTest.cpp | derp-caf/external_skia | b09dc92e00edce8366085aaad7dcce94ceb11b69 | [
"BSD-3-Clause"
] | 8 | 2019-01-12T23:06:45.000Z | 2021-09-03T00:15:46.000Z | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This is a GPU-backend specific test.
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrBackendSurface.h"
#include "GrContextPriv.h"
#include "GrProxyProvider.h"
#include "GrRenderTargetPriv.h"
#include "GrRenderTargetProxy.h"
#include "GrResourceProvider.h"
#include "GrSurfaceProxyPriv.h"
#include "GrTexture.h"
#include "GrTextureProxy.h"
#include "SkGr.h"
// Check that the surface proxy's member vars are set as expected
static void check_surface(skiatest::Reporter* reporter,
GrSurfaceProxy* proxy,
GrSurfaceOrigin origin,
int width, int height,
GrPixelConfig config,
SkBudgeted budgeted) {
REPORTER_ASSERT(reporter, proxy->origin() == origin);
REPORTER_ASSERT(reporter, proxy->width() == width);
REPORTER_ASSERT(reporter, proxy->height() == height);
REPORTER_ASSERT(reporter, proxy->config() == config);
REPORTER_ASSERT(reporter, !proxy->uniqueID().isInvalid());
REPORTER_ASSERT(reporter, proxy->isBudgeted() == budgeted);
}
static void check_rendertarget(skiatest::Reporter* reporter,
const GrCaps& caps,
GrResourceProvider* provider,
GrRenderTargetProxy* rtProxy,
int numSamples,
SkBackingFit fit,
int expectedMaxWindowRects) {
REPORTER_ASSERT(reporter, rtProxy->maxWindowRectangles(caps) == expectedMaxWindowRects);
REPORTER_ASSERT(reporter, rtProxy->numStencilSamples() == numSamples);
GrSurfaceProxy::UniqueID idBefore = rtProxy->uniqueID();
REPORTER_ASSERT(reporter, rtProxy->instantiate(provider));
GrRenderTarget* rt = rtProxy->priv().peekRenderTarget();
REPORTER_ASSERT(reporter, rtProxy->uniqueID() == idBefore);
// Deferred resources should always have a different ID from their instantiated rendertarget
REPORTER_ASSERT(reporter, rtProxy->uniqueID().asUInt() != rt->uniqueID().asUInt());
if (SkBackingFit::kExact == fit) {
REPORTER_ASSERT(reporter, rt->width() == rtProxy->width());
REPORTER_ASSERT(reporter, rt->height() == rtProxy->height());
} else {
REPORTER_ASSERT(reporter, rt->width() >= rtProxy->width());
REPORTER_ASSERT(reporter, rt->height() >= rtProxy->height());
}
REPORTER_ASSERT(reporter, rt->config() == rtProxy->config());
REPORTER_ASSERT(reporter, rt->fsaaType() == rtProxy->fsaaType());
REPORTER_ASSERT(reporter, rt->numColorSamples() == rtProxy->numColorSamples());
REPORTER_ASSERT(reporter, rt->numStencilSamples() == rtProxy->numStencilSamples());
REPORTER_ASSERT(reporter, rt->renderTargetPriv().flags() == rtProxy->testingOnly_getFlags());
}
static void check_texture(skiatest::Reporter* reporter,
GrResourceProvider* provider,
GrTextureProxy* texProxy,
SkBackingFit fit) {
GrSurfaceProxy::UniqueID idBefore = texProxy->uniqueID();
REPORTER_ASSERT(reporter, texProxy->instantiate(provider));
GrTexture* tex = texProxy->priv().peekTexture();
REPORTER_ASSERT(reporter, texProxy->uniqueID() == idBefore);
// Deferred resources should always have a different ID from their instantiated texture
REPORTER_ASSERT(reporter, texProxy->uniqueID().asUInt() != tex->uniqueID().asUInt());
if (SkBackingFit::kExact == fit) {
REPORTER_ASSERT(reporter, tex->width() == texProxy->width());
REPORTER_ASSERT(reporter, tex->height() == texProxy->height());
} else {
REPORTER_ASSERT(reporter, tex->width() >= texProxy->width());
REPORTER_ASSERT(reporter, tex->height() >= texProxy->height());
}
REPORTER_ASSERT(reporter, tex->config() == texProxy->config());
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(DeferredProxyTest, reporter, ctxInfo) {
GrProxyProvider* proxyProvider = ctxInfo.grContext()->contextPriv().proxyProvider();
GrResourceProvider* resourceProvider = ctxInfo.grContext()->contextPriv().resourceProvider();
const GrCaps& caps = *ctxInfo.grContext()->caps();
int attempt = 0; // useful for debugging
for (auto origin : { kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin }) {
for (auto widthHeight : { 100, 128, 1048576 }) {
for (auto config : { kAlpha_8_GrPixelConfig, kRGB_565_GrPixelConfig,
kRGBA_8888_GrPixelConfig, kRGBA_1010102_GrPixelConfig }) {
for (auto fit : { SkBackingFit::kExact, SkBackingFit::kApprox }) {
for (auto budgeted : { SkBudgeted::kYes, SkBudgeted::kNo }) {
for (auto numSamples : {1, 4, 16, 128}) {
GrSurfaceDesc desc;
desc.fFlags = kRenderTarget_GrSurfaceFlag;
desc.fOrigin = origin;
desc.fWidth = widthHeight;
desc.fHeight = widthHeight;
desc.fConfig = config;
desc.fSampleCnt = numSamples;
{
sk_sp<GrTexture> tex;
if (SkBackingFit::kApprox == fit) {
tex = resourceProvider->createApproxTexture(desc, 0);
} else {
tex = resourceProvider->createTexture(desc, budgeted);
}
sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
desc, fit, budgeted);
REPORTER_ASSERT(reporter, SkToBool(tex) == SkToBool(proxy));
if (proxy) {
REPORTER_ASSERT(reporter, proxy->asRenderTargetProxy());
// This forces the proxy to compute and cache its
// pre-instantiation size guess. Later, when it is actually
// instantiated, it checks that the instantiated size is <= to
// the pre-computation. If the proxy never computed its
// pre-instantiation size then the check is skipped.
proxy->gpuMemorySize();
check_surface(reporter, proxy.get(), origin,
widthHeight, widthHeight, config, budgeted);
int supportedSamples =
caps.getRenderTargetSampleCount(numSamples, config);
check_rendertarget(reporter, caps, resourceProvider,
proxy->asRenderTargetProxy(),
supportedSamples,
fit, caps.maxWindowRectangles());
}
}
desc.fFlags = kNone_GrSurfaceFlags;
{
sk_sp<GrTexture> tex;
if (SkBackingFit::kApprox == fit) {
tex = resourceProvider->createApproxTexture(desc, 0);
} else {
tex = resourceProvider->createTexture(desc, budgeted);
}
sk_sp<GrTextureProxy> proxy(proxyProvider->createProxy(
desc, fit, budgeted));
REPORTER_ASSERT(reporter, SkToBool(tex) == SkToBool(proxy));
if (proxy) {
// This forces the proxy to compute and cache its
// pre-instantiation size guess. Later, when it is actually
// instantiated, it checks that the instantiated size is <= to
// the pre-computation. If the proxy never computed its
// pre-instantiation size then the check is skipped.
proxy->gpuMemorySize();
check_surface(reporter, proxy.get(), origin,
widthHeight, widthHeight, config, budgeted);
check_texture(reporter, resourceProvider,
proxy->asTextureProxy(), fit);
}
}
attempt++;
}
}
}
}
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(WrappedProxyTest, reporter, ctxInfo) {
GrProxyProvider* proxyProvider = ctxInfo.grContext()->contextPriv().proxyProvider();
GrResourceProvider* resourceProvider = ctxInfo.grContext()->contextPriv().resourceProvider();
GrGpu* gpu = ctxInfo.grContext()->contextPriv().getGpu();
const GrCaps& caps = *ctxInfo.grContext()->caps();
static const int kWidthHeight = 100;
if (kOpenGL_GrBackend != ctxInfo.backend()) {
return;
}
for (auto origin : { kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin }) {
for (auto colorType : { kAlpha_8_SkColorType, kRGBA_8888_SkColorType,
kRGBA_1010102_SkColorType }) {
for (auto numSamples : {1, 4}) {
GrPixelConfig config = SkImageInfo2GrPixelConfig(colorType, nullptr, caps);
SkASSERT(kUnknown_GrPixelConfig != config);
int supportedNumSamples = caps.getRenderTargetSampleCount(numSamples, config);
if (!supportedNumSamples) {
continue;
}
// External on-screen render target.
// Tests createWrappedRenderTargetProxy with a GrBackendRenderTarget
{
GrGLFramebufferInfo fboInfo;
fboInfo.fFBOID = 0;
GrBackendRenderTarget backendRT(kWidthHeight, kWidthHeight, numSamples, 8,
config, fboInfo);
sk_sp<GrSurfaceProxy> sProxy(proxyProvider->createWrappedRenderTargetProxy(
backendRT, origin));
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendRT.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_rendertarget(reporter, caps, resourceProvider,
sProxy->asRenderTargetProxy(),
supportedNumSamples, SkBackingFit::kExact, 0);
}
// Tests createWrappedRenderTargetProxy with a GrBackendTexture
{
GrBackendTexture backendTex =
gpu->createTestingOnlyBackendTexture(nullptr, kWidthHeight,
kWidthHeight, colorType, true,
GrMipMapped::kNo);
sk_sp<GrSurfaceProxy> sProxy =
proxyProvider->createWrappedRenderTargetProxy(backendTex, origin,
supportedNumSamples);
if (!sProxy) {
gpu->deleteTestingOnlyBackendTexture(&backendTex);
continue; // This can fail on Mesa
}
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendTex.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_rendertarget(reporter, caps, resourceProvider,
sProxy->asRenderTargetProxy(),
supportedNumSamples, SkBackingFit::kExact,
caps.maxWindowRectangles());
gpu->deleteTestingOnlyBackendTexture(&backendTex);
}
// Tests createWrappedTextureProxy that is only renderable
{
GrBackendTexture backendTex =
gpu->createTestingOnlyBackendTexture(nullptr, kWidthHeight,
kWidthHeight, colorType, true,
GrMipMapped::kNo);
sk_sp<GrSurfaceProxy> sProxy =
proxyProvider->createWrappedTextureProxy(backendTex, origin,
supportedNumSamples);
if (!sProxy) {
gpu->deleteTestingOnlyBackendTexture(&backendTex);
continue; // This can fail on Mesa
}
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendTex.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_rendertarget(reporter, caps, resourceProvider,
sProxy->asRenderTargetProxy(),
supportedNumSamples, SkBackingFit::kExact,
caps.maxWindowRectangles());
gpu->deleteTestingOnlyBackendTexture(&backendTex);
}
// Tests createWrappedTextureProxy that is only textureable
{
// Internal offscreen texture
GrBackendTexture backendTex =
gpu->createTestingOnlyBackendTexture(nullptr, kWidthHeight,
kWidthHeight, colorType, false,
GrMipMapped::kNo);
sk_sp<GrSurfaceProxy> sProxy =
proxyProvider->createWrappedTextureProxy(backendTex, origin,
kBorrow_GrWrapOwnership,
nullptr, nullptr);
if (!sProxy) {
gpu->deleteTestingOnlyBackendTexture(&backendTex);
continue;
}
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendTex.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_texture(reporter, resourceProvider, sProxy->asTextureProxy(),
SkBackingFit::kExact);
gpu->deleteTestingOnlyBackendTexture(&backendTex);
}
}
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ZeroSizedProxyTest, reporter, ctxInfo) {
GrProxyProvider* provider = ctxInfo.grContext()->contextPriv().proxyProvider();
for (auto flags : { kRenderTarget_GrSurfaceFlag, kNone_GrSurfaceFlags }) {
for (auto fit : { SkBackingFit::kExact, SkBackingFit::kApprox }) {
for (int width : { 0, 100 }) {
for (int height : { 0, 100}) {
if (width && height) {
continue; // not zero-sized
}
GrSurfaceDesc desc;
desc.fFlags = flags;
desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
desc.fWidth = width;
desc.fHeight = height;
desc.fConfig = kRGBA_8888_GrPixelConfig;
desc.fSampleCnt = 1;
sk_sp<GrTextureProxy> proxy = provider->createProxy(desc, fit, SkBudgeted::kNo);
REPORTER_ASSERT(reporter, !proxy);
}
}
}
}
}
#endif
| 49.878338 | 100 | 0.500982 | derp-caf |
6adacd1f82fbc5257518e3fdd8e3acf6d3ba7bf5 | 430 | cpp | C++ | mts/write-after-reclaim-stack.cpp | comparch-security/cpu-sec-bench | 34506323a80637fae2a4d2add3bbbdaa4e6d8473 | [
"MIT"
] | 4 | 2021-11-12T03:41:54.000Z | 2022-02-28T12:23:49.000Z | mts/write-after-reclaim-stack.cpp | comparch-security/cpu-sec-bench | 34506323a80637fae2a4d2add3bbbdaa4e6d8473 | [
"MIT"
] | null | null | null | mts/write-after-reclaim-stack.cpp | comparch-security/cpu-sec-bench | 34506323a80637fae2a4d2add3bbbdaa4e6d8473 | [
"MIT"
] | 1 | 2021-11-29T08:38:28.000Z | 2021-11-29T08:38:28.000Z | #include "include/gcc_builtin.hpp"
#include "include/mss.hpp"
charBuffer *pb;
int FORCE_NOINLINE helper(bool option) {
charBuffer buffer;
if(option) {
update_by_pointer(pb->data, 0, 8, 1, 'c');
return check(buffer.data, 7, 1, 'c');
} else {
pb = &buffer;
char_buffer_init(&buffer, 'u', 'd', 'o');
return 0;
}
}
int main() {
int rv0 = helper(false);
int rv1 = helper(true);
return rv0+rv1;
}
| 18.695652 | 47 | 0.613953 | comparch-security |
6adada53107ff342115844eddbf6e87ec8bc54a7 | 5,844 | cc | C++ | test/av1_fht4x8_test.cc | merryApple/aom | 7b88ade6135ed4fecd6d745166ce74209ff137de | [
"BSD-2-Clause"
] | null | null | null | test/av1_fht4x8_test.cc | merryApple/aom | 7b88ade6135ed4fecd6d745166ce74209ff137de | [
"BSD-2-Clause"
] | 4 | 2018-01-12T14:03:23.000Z | 2018-01-15T11:23:08.000Z | test/av1_fht4x8_test.cc | merryApple/aom | 7b88ade6135ed4fecd6d745166ce74209ff137de | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "./aom_dsp_rtcd.h"
#include "./av1_rtcd.h"
#include "aom_ports/mem.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/transform_test_base.h"
#include "test/util.h"
using libaom_test::ACMRandom;
#if !CONFIG_DAALA_TX
namespace {
typedef void (*IhtFunc)(const tran_low_t *in, uint8_t *out, int stride,
const TxfmParam *txfm_param);
using std::tr1::tuple;
using libaom_test::FhtFunc;
typedef tuple<FhtFunc, IhtFunc, TX_TYPE, aom_bit_depth_t, int> Ht4x8Param;
void fht4x8_ref(const int16_t *in, tran_low_t *out, int stride,
TxfmParam *txfm_param) {
av1_fht4x8_c(in, out, stride, txfm_param);
}
void iht4x8_ref(const tran_low_t *in, uint8_t *out, int stride,
const TxfmParam *txfm_param) {
av1_iht4x8_32_add_c(in, out, stride, txfm_param);
}
class AV1Trans4x8HT : public libaom_test::TransformTestBase,
public ::testing::TestWithParam<Ht4x8Param> {
public:
virtual ~AV1Trans4x8HT() {}
virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
pitch_ = 4;
height_ = 8;
fwd_txfm_ref = fht4x8_ref;
inv_txfm_ref = iht4x8_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
num_coeffs_ = GET_PARAM(4);
txfm_param_.tx_type = GET_PARAM(2);
}
virtual void TearDown() { libaom_test::ClearSystemState(); }
protected:
void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride, &txfm_param_);
}
void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, &txfm_param_);
}
FhtFunc fwd_txfm_;
IhtFunc inv_txfm_;
};
TEST_P(AV1Trans4x8HT, AccuracyCheck) { RunAccuracyCheck(0, 0.00001); }
TEST_P(AV1Trans4x8HT, CoeffCheck) { RunCoeffCheck(); }
TEST_P(AV1Trans4x8HT, MemCheck) { RunMemCheck(); }
TEST_P(AV1Trans4x8HT, InvCoeffCheck) { RunInvCoeffCheck(); }
TEST_P(AV1Trans4x8HT, InvAccuracyCheck) { RunInvAccuracyCheck(0); }
using std::tr1::make_tuple;
const Ht4x8Param kArrayHt4x8Param_c[] = {
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_FLIPADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, IDTX, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_FLIPADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_FLIPADST, AOM_BITS_8, 32)
};
INSTANTIATE_TEST_CASE_P(C, AV1Trans4x8HT,
::testing::ValuesIn(kArrayHt4x8Param_c));
#if HAVE_SSE2
const Ht4x8Param kArrayHt4x8Param_sse2[] = {
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_DCT, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_DCT, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_DCT,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_ADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, IDTX, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_FLIPADST, AOM_BITS_8,
32)
};
INSTANTIATE_TEST_CASE_P(SSE2, AV1Trans4x8HT,
::testing::ValuesIn(kArrayHt4x8Param_sse2));
#endif // HAVE_SSE2
} // namespace
#endif // !CONFIG_DAALA_TX
| 40.583333 | 80 | 0.729295 | merryApple |
6adc5c6f9685980e5ab2bd50c57d40ba678fc667 | 143 | cpp | C++ | mia/medium/msx2.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | mia/medium/msx2.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | mia/medium/msx2.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | struct MSX2 : MSX {
auto name() -> string override { return "MSX2"; }
auto extensions() -> vector<string> override { return {"msx2"}; }
};
| 28.6 | 67 | 0.622378 | CasualPokePlayer |
6add5bf41ddcbf2de097d3c435cf4724053d6fe0 | 1,842 | cpp | C++ | admin/dcpromo/exe/unattendsplashdialog.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/dcpromo/exe/unattendsplashdialog.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/dcpromo/exe/unattendsplashdialog.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // Copyright (C) 1998 Microsoft Corporation
//
// Splash screen for unattended mode
//
// 10-1-98 sburns
#include "headers.hxx"
#include "UnattendSplashDialog.hpp"
#include "resource.h"
#include "state.hpp"
const UINT SELF_DESTRUCT_MESSAGE = WM_USER + 200;
static const DWORD HELP_MAP[] =
{
0, 0
};
UnattendSplashDialog::UnattendSplashDialog(int splashMessageResId)
:
Dialog(IDD_UNATTEND_SPLASH, HELP_MAP),
messageResId(splashMessageResId)
{
LOG_CTOR(UnattendSplashDialog);
ASSERT(messageResId);
}
UnattendSplashDialog::~UnattendSplashDialog()
{
LOG_DTOR(UnattendSplashDialog);
}
void
UnattendSplashDialog::OnInit()
{
LOG_FUNCTION(UnattendSplashDialog::OnInit);
// Since the window does not have a title bar, we need to give it some
// text to appear on the button label on the shell task bar.
Win::SetWindowText(hwnd, String::load(IDS_WIZARD_TITLE));
// NTRAID#NTBUG9-502991-2001/12/07-sburns
Win::SetDlgItemText(hwnd, IDC_MESSAGE, messageResId);
}
void
UnattendSplashDialog::SelfDestruct()
{
LOG_FUNCTION(UnattendSplashDialog::SelfDestruct);
// Post our window proc a self destruct message. We use Post instead of
// send, as we expect that in some cases, this function will be called from
// a thread other than the one that created the window. (It is illegal to
// try to destroy a window from a thread that it not the thread that
// created the window.)
Win::PostMessage(hwnd, SELF_DESTRUCT_MESSAGE, 0, 0);
}
bool
UnattendSplashDialog::OnMessage(
UINT message,
WPARAM /* wparam */ ,
LPARAM /* lparam */ )
{
if (message == SELF_DESTRUCT_MESSAGE)
{
delete this;
return true;
}
return false;
}
| 19.389474 | 79 | 0.666667 | npocmaka |
6addb3c8282a4d539b49e5278c83561633f72aad | 2,405 | cpp | C++ | platform/switch/godot_switch.cpp | ryancheung/godot | 39c52e45d330cf4eb5558d06e005b3d4ab2a08d2 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | platform/switch/godot_switch.cpp | ryancheung/godot | 39c52e45d330cf4eb5558d06e005b3d4ab2a08d2 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | platform/switch/godot_switch.cpp | ryancheung/godot | 39c52e45d330cf4eb5558d06e005b3d4ab2a08d2 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | #include "switch_wrapper.h"
#include <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <zlib.h>
#include "main/main.h"
#include "os_switch.h"
#define FB_WIDTH 1280
#define FB_HEIGHT 720
int main(int argc, char *argv[])
{
socketInitializeDefault();
nxlinkStdio();
int apptype = appletGetAppletType();
if(apptype != AppletType_Application && apptype != AppletType_SystemApplication)
{
romfsInit();
NWindow* win = nwindowGetDefault();
Framebuffer fb;
framebufferCreate(&fb, win, FB_WIDTH, FB_HEIGHT, PIXEL_FORMAT_RGBA_8888, 1);
framebufferMakeLinear(&fb);
u32 stride;
u32* framebuf = (u32*) framebufferBegin(&fb, &stride);
FILE *splash = fopen("romfs:/applet_splash.rgba.gz", "rb");
if(splash)
{
fseek(splash, 0, SEEK_END);
size_t splash_size = ftell(splash);
u8 *compressed_splash = (u8*)malloc(splash_size);
memset(compressed_splash, 0, splash_size);
fseek(splash, 0, SEEK_SET);
size_t amt_read = fread(compressed_splash, 1, splash_size, splash);
fclose(splash);
memset(framebuf, 0, stride * FB_HEIGHT);
struct z_stream_s stream;
memset(&stream, 0, sizeof(stream));
stream.zalloc = NULL;
stream.zfree = NULL;
stream.next_in = compressed_splash;
stream.avail_in = splash_size;
stream.next_out = (u8*)framebuf;
stream.avail_out = stride * FB_HEIGHT;
if(inflateInit2(&stream, 16+MAX_WBITS) == Z_OK)
{
int err = 0;
if((err = inflate(&stream, 0)) != Z_STREAM_END)
{
// idk
}
inflateEnd(&stream);
}
}
else
{
// this REALLY shouldn't fail. Hm.
}
framebufferEnd(&fb);
while(appletMainLoop())
{
hidScanInput();
if(hidKeysDown(CONTROLLER_P1_AUTO) &
~(KEY_TOUCH|
KEY_LSTICK_LEFT|KEY_LSTICK_RIGHT|
KEY_LSTICK_UP|KEY_LSTICK_DOWN|
KEY_RSTICK_LEFT|KEY_RSTICK_RIGHT|
KEY_RSTICK_UP|KEY_RSTICK_DOWN))
{
break;
}
}
framebufferClose(&fb);
romfsExit();
socketExit();
return 0;
}
OS_Switch os;
os.set_executable_path(argv[0]);
char *cwd = (char *)malloc(PATH_MAX);
getcwd(cwd, PATH_MAX);
Error err = Main::setup(argv[0], argc - 1, &argv[1]);
if (err != OK) {
free(cwd);
socketExit();
return 255;
}
if (Main::start())
{
os.run(); // it is actually the OS that decides how to run
}
Main::cleanup();
chdir(cwd);
free(cwd);
socketExit();
return os.get_exit_code();
}
| 19.552846 | 81 | 0.661538 | ryancheung |
6ae1cb945726178130cd9bc70b7afde00b8435a1 | 30,382 | cc | C++ | src/cxx/mc/mcmain2d/wk_memfilter.cc | sfarrens/cosmostat | a475315cda06dca346095a1e83cb6ad23979acae | [
"MIT"
] | null | null | null | src/cxx/mc/mcmain2d/wk_memfilter.cc | sfarrens/cosmostat | a475315cda06dca346095a1e83cb6ad23979acae | [
"MIT"
] | null | null | null | src/cxx/mc/mcmain2d/wk_memfilter.cc | sfarrens/cosmostat | a475315cda06dca346095a1e83cb6ad23979acae | [
"MIT"
] | null | null | null | /******************************************************************************
** Copyright (C) 1998 by CEA
*******************************************************************************
**
** UNIT
**
** Version: 1.4
**
** Author: 07/01/99
**
** Date: 99/07/05
**
** File: mc_mwfilter.cc
**
*******************************************************************************/
#include "wk_memfilter.h"
#include "MW_mcFilter.h"
#include "MR_Filter.h"
#include "MR_Edge.h"
#define MAX_ITER 100
#define DEF_SIGMA_PCA -1
#define DEF_SIGMA_MR2D 3
#define MAX_IMAG_VALUE 255
#define DEF_CORREL_COMP E_LOCAL
#define DEF_CORREL_NOISE E_THRESHOLD
#define DEF_CONV_PARAM DEF_MEM_FILT_CONGER
#define DEF_REGUL_PARAM 1
#define MAX_NBR_TYPE_OPT 3
#define DEF_SIZE_BLK DEFAULT_SIZE_BLOCK_SIG
#define DEF_ITER_SIGCLP 1
#define DEF_ITER_ENTROP DEF_MEM_FILT_MAX_ITER
extern int OptInd;
extern char *OptArg;
/***********************************************************************************/
char* getTypeOpt (int ind) {
switch (ind) {
case 1 : return ("fixed user Alpha value");break;
case 2 : return ("Estimate the optimal Alpha");break;
case 3 : return ("Estimate one Alpha value per band");break;
default : return ("Error: bad optim type");break;
}
}
/***********************************************************************************/
void mr_getmodel_from_edge(MultiResol & MR_Data, MultiResol &MR_Edge,
MRNoiseModel & ModelData) {
/* Find a multiresolution model for edges:
-- create an SNR edge image: ImaEdge
-- threshold ImaEdge if ImaEdge < NSigma
-- kill isolated pixel in ImaEdge
-- in each band,
. threshold wavelet coefficient if there is no edge
.average the wavelet coefficient
with the two other values in the edge direction
!! This routine works only if the a-trou algorithm is choosen
*/
int Nbr_Band = MR_Data.nbr_band()-1;
int i,j,Nl = MR_Data.size_ima_nl();
int Nc = MR_Data.size_ima_nc();
Ifloat ImaEdge(Nl,Nc,"ImaEdge");
Iint ImaAngle(Nl,Nc,"ImaAngle");
mr_get_edge( MR_Data, MR_Edge, ImaEdge, ImaAngle, ModelData);
for (i = 0; i < Nl; i++)
for (j = 0; j < Nc; j++)
{
ImaEdge(i,j) /= ModelData.NSigma[1];
if (ImaEdge(i,j) > 1) ImaEdge(i,j) = 1.;
else ImaEdge(i,j) = 0.;
}
for (i=0;i < Nl; i++)
for (j=0;j < Nc; j++)
if (isolated_pixel(ImaEdge,i,j,I_MIRROR) == True) ImaEdge(i,j) = 0.;
for (int b = 0; b < Nbr_Band; b++)
{
int Nlb = MR_Data.size_band_nl(b);
int Ncb = MR_Data.size_band_nc(b);
int Step = (MR_Data.band_to_scale(b) == b) ? b : 0;
for (i = 0; i < Nlb; i++)
for (j = 0; j < Ncb; j++)
{
if (ImaEdge(i,j) > FLOAT_EPSILON)
MR_Edge(b,i,j) = val_contour_min(MR_Data.band(b), ImaEdge, ImaAngle,
i,j, FLOAT_EPSILON, Step);
else MR_Edge(b,i,j) = 0.;
}
}
}
int main(int argc, char *argv[])
{
extern softinfo Soft;
Soft.mr3();
lm_check(LIC_MR3);
// licence manager
//lm2();
// init local var
mw_Param o_Param;
// Read param IN
o_Param (argc, argv);
// init Result and Iter classes
mw_Result o_Result (&o_Param);
mw_Iter o_Iter (&o_Result);
for (o_Iter.iter_Begin(); o_Iter.iter_End(); o_Iter++) {}
// write result
o_Result.res_Write ();
exit(0);
}
/******************************************************************************
classe mw_Param
******************************************************************************/
mw_Param::mw_Param () {
//default init of read var
e_Transform = DEFAULT_TRANSFORM;
e_Norm = NORM_L1;
e_SBFilter = F_MALLAT_7_9;
po_FAS = (FilterAnaSynt*)NULL;
i_NbPlan = DEFAULT_NBR_SCALE;
i_NbIter = 1;
e_WithNoiseModel = True; // always use noise model, def gaussian
e_UseReconsAdjoint = False;
e_TypeNoise = DEFAULT_STAT_NOISE;
e_PositivImag = False;
e_MaxImag = False;
e_NormCorrelMatrix = True;
e_CorrelComp = DEF_CORREL_COMP;
po_ImportCorMat = NULL;
e_CorrelNoise = DEF_CORREL_NOISE;
f_NoiseIma = 0.;
f_Gain = 0.;
f_SigmaGauss = 0.;
f_MeanGauss = 0.;
f_NSigmaMr2d = DEF_SIGMA_MR2D;
f_NSigmaPCA = DEF_SIGMA_PCA;
e_Verbose = False;
e_WriteTransf = False;
e_WriteEigenOnDisk = False;
e_WriteSupportMr2d = False;
e_WriteSupportPCA = False;
e_TraceParamIn = False;
f_CvgParam = DEF_CONV_PARAM;
f_RegulVal = 1.;
i_TypeOpt = DEF_MEM_ALPHA_CST;
e_DataEdge = False;
e_DataSNR = False;
e_UseRMSMap = False;
i_SizeBlock = DEF_SIZE_BLK;
i_NiterClip = DEF_ITER_SIGCLP;
i_NbIterEntrop = DEF_ITER_ENTROP;
e_NscaleOpt = False;
e_TransfOpt = False;
#ifdef LARGE_BUFF
e_OptZ = False;
i_VMSSize = -1;
#endif
for (int b=0;b<MAX_NB_BAND;b++) {
ti_NbrUseEigen[b] = 0;
for (int i=0;i<MAX_NBR_PCA_IMA;i++)
tti_TabKill[i][b] = 0;
}
}
void mw_Param::operator () (int argc, char *argv[]) {
int c,i,b;
Bool readfile = False, Optf = False, OptL = False;;
while ((c = GetOpt(argc,argv,"t:m:g:c:n:s:S:x:O:y:WwrkRapvLbPF:K:C:G:U:T:M:B:N:i:ADzZ:")) != -1) {
switch (c) {
case 't': /* -d <type> type of transform */
readint (i, "bad type of multiresolution transform: %s\n");
if (testborn (1 ,NBR_TRANSFORM, i, "bad type of transform: %s\n"))
e_Transform = (type_transform) (i-1);
e_TransfOpt = True;
break;
case 'T':
Optf = True;
e_SBFilter = get_filter_bank(OptArg);
break;
case 'L':
e_Norm = NORM_L2;OptL = True;break;
case 'm':
readint (i, "Error: bad type of noise: %s\n");
if (testborn(1, NBR_NOISE, i, "Error: bad type of noise: %s\n"))
e_TypeNoise = (type_noise) (i-1);
e_WithNoiseModel = True;
break;
case 'n': /* -n <NbPlan> */
readint (i_NbPlan, "bad number of scales: %s\n");
testborn (2, MAX_SCALE, i_NbPlan, "bad number of scales: %s\n");
e_NscaleOpt = True;
break;
//case 'i': /* -i <NbIter> */
// readint (i_NbIter, "bad number of iterarions: %s\n");
// testborn (1, MAX_ITER, i_NbIter, "bad number of iterations: %s\n");
// break;
case 'g': /* -g <sigma_noise> */
readfloat (f_NoiseIma, "Error: bad sigma noise: %s\n");
e_TypeNoise = NOISE_GAUSSIAN;
e_WithNoiseModel = True;
break;
case 'c': /* -c <gain sigma mean> */
readfloat (f_Gain, "Error: bad sigma noise: %s\n");
readfloat (f_SigmaGauss, "Error: bad sigma noise: %s\n");
readfloat (f_MeanGauss, "Error: bad sigma noise: %s\n");
e_TypeNoise = NOISE_POISSON;
e_WithNoiseModel = True;
f_NoiseIma = 1.;
break;
case 's': /* -s <nsigma> */
readfloat (f_NSigmaMr2d, "Error: bad NSigma: %s\n");
break;
case 'S': /* -S <nsigma> */
readfloat (f_NSigmaPCA, "Error: bad NSigma: %s\n");
break;
case 'F':
readint (i, "Error: bad number of eigen vectors: %s\n");
for (b=0;b<MAX_NB_BAND;b++) ti_NbrUseEigen[b] = i;
break;
case 'K':
readint (i, "Error: bad eigen vector number: %s\n");
testborn (1, MAX_NBR_PCA_IMA, i, "Error: bad eigen vector number: %s\n");
for (b=0;b<MAX_NB_BAND;b++) tti_TabKill[i-1][b] = 1;
break;
case 'C':
readfloat (f_CvgParam, "Error: bad Cvg Parameter: %s\n");
if (f_CvgParam <= 0.) f_CvgParam = 0.1;
break;
case 'G':
readfloat (f_RegulVal, "Error: bad Regularization Parameter: %s\n");
if (f_RegulVal < 0.) f_RegulVal = 1.;
break;
case 'U':
readint (i_TypeOpt, "bad type of regularization %s\n");
testborn (1, MAX_NBR_TYPE_OPT, i_TypeOpt, "Error: regularization type must be in [1,3]");
break;
case 'M':
if (sscanf(OptArg,"%s", tc_NameRMSMap) != 1) {
fprintf(stderr, "Error: bad file name: %s\n", OptArg); exit(-1);
}
e_UseRMSMap = True;
break;
case 'B':
readint (i_SizeBlock, "bad block size (sigma clipping): %s\n");
break;
case 'N':
readint (i_NiterClip, "Error: ad it. number for the 3sigma clipping: %s\n");
break;
case 'i':
readint (i_NbIterEntrop, "Error: bad number of iterations: %s\n");
break;
case 'x': /* -x type of compute correlation */
readint (i, "bad type of correlation compute : %s\n");
if (testborn (0 ,MAX_CORREL_COMP-1, i, "bad type of correlation compute: %s\n"))
e_CorrelComp = (CorrelComputeType) (i);
break;
case 'O': /* -C correaltion matrix name file */
if (sscanf(OptArg,"%s", tc_ImportCorMatName) != 1) {
fprintf(stderr, "Error: bad correlation matrix file name: %s\n", OptArg); exit(-1);
}
readfile = True;
break;
case 'y': /* -x type of noise correlation */
readint (i, "bad type of correlation noise : %s\n");
if (testborn (0 ,MAX_CORREL_NOISE-1, i, "bad type of correlation noise: %s\n"))
e_CorrelNoise = (CorrelNoiseType) (i);
break;
#ifdef LARGE_BUFF
case 'z':
if (e_OptZ == True) {
fprintf(OUTMAN, "Error: Z option already set...\n"); exit(-1);
}
e_OptZ = True; break;
case 'Z':
if (sscanf(OptArg,"%d:%s",&i_VMSSize, tc_VMSName) < 1) {
fprintf(OUTMAN, "Error: syntaxe is Size:Directory ... \n"); exit(-1);
}
if (e_OptZ == True) {
fprintf(OUTMAN, "Error: z option already set...\n"); exit(-1);
}
e_OptZ = True;
break;
#endif
case 'p':
e_NormCorrelMatrix = False;break;
case 'P':
e_PositivImag = True;break;
case 'b':
e_MaxImag = True;break;
case 'a':
e_UseReconsAdjoint = True;break;
case 'W':
e_WriteTransf = True;break;
case 'w':
e_WriteEigenOnDisk = True;break;
case 'r':
e_WriteSupportMr2d = True;break;
case 'R':
e_WriteSupportPCA = True;break;
case 'A' :
e_DataEdge = True; break;
case 'D' :
e_DataSNR = True; break;
case 'k':
e_TraceParamIn = True;break;
case 'v':
e_Verbose = True;break;
case '?':
usage(argv);
}
}
if ( (e_Transform != TO_UNDECIMATED_MALLAT)
&& (e_Transform != TO_MALLAT)
&& ((OptL == True) || (Optf == True))) {
fprintf(OUTMAN, "Error: option -T and -L are only valid with Mallat transform ... \n");
exit(0);
}
if ( (e_Transform == TO_UNDECIMATED_MALLAT)
|| (e_Transform == TO_MALLAT) ) {
po_FAS = new FilterAnaSynt(); /* mem loss, never free ... */
po_FAS->alloc(e_SBFilter);
po_FAS->Verbose = e_Verbose;
}
// get optional input file names from trailing parameters and open files
// read input image names */
if (OptInd < argc) strcpy(tc_NameIn, argv[OptInd++]);
else usage(argv);
if (OptInd < argc) strcpy(tc_NameOut, argv[OptInd++]);
else usage(argv);
// make sure there are not too many parameters
if (OptInd < argc) {
fprintf(OUTMAN, "Error: too many parameters: %s ...\n", argv[OptInd]);
usage(argv);
}
// Test inconsistencies in the option call
if (e_TypeNoise == NOISE_EVENT_POISSON) {
if ((e_TransfOpt == True) && (e_Transform != TO_PAVE_BSPLINE)) {
cerr << "WARNING: with this noise model, only the BSPLINE A TROUS can be used ... " << endl;
cerr << " Type transform is set to: BSPLINE A TROUS ALGORITHM " << endl;
}
e_Transform = TO_PAVE_BSPLINE;
if (e_NscaleOpt != True) i_NbPlan = DEF_N_SCALE;
}
if ((e_TypeNoise == NOISE_CORREL) && (e_UseRMSMap != True)) {
cerr << endl << endl;
cerr << " Error: this noise model need a noise map (-R option) " << endl;
exit(-1);
}
if (e_UseRMSMap == True) {
if ((e_TypeNoise != NOISE_NON_UNI_ADD) && (e_TypeNoise != NOISE_CORREL)) {
cerr << "Error: this noise model is not correct when RMS map option is set." << endl;
cerr << " Valid models are: " << endl;
cerr << " " << StringNoise(NOISE_NON_UNI_ADD) << endl;
cerr << " " << StringNoise(NOISE_CORREL) << endl;
exit(-1);
}
// Stat_Noise = NOISE_NON_UNI_ADD;
}
if ((isotrop(e_Transform) == False)
&& ((e_TypeNoise == NOISE_NON_UNI_ADD) || (e_TypeNoise == NOISE_NON_UNI_MULT))) {
cerr << endl << endl;
cerr << " Error: with this transform, non stationary noise models are not valid : " << StringFilter(FILTER_THRESHOLD) << endl;
exit(-1);
}
#ifdef LARGE_BUFF
if (e_OptZ == True) vms_init(i_VMSSize, tc_VMSName, e_Verbose);
#endif
read_image (argv);
// matrix file name
if (e_CorrelComp == E_IMPORT) {
if (readfile != True) {
cout << " -O Matrix_File_Name not initialized" << endl;
exit (-1);
}
fitsstruct Header;
po_ImportCorMat = new Ifloat(i_NbImage, i_NbImage, "");
io_read_ima_float(tc_ImportCorMatName, *po_ImportCorMat, &Header);
int Nl = po_ImportCorMat->nl();
int Nc = po_ImportCorMat->nc();
if (Nl != Nc || Nl != i_NbImage) {
cout << " bad size of Matrix File Name" << endl;
exit (-1);
}
}
if (e_TraceParamIn) trace ();
}
void mw_Param::usage (char *argv[]) {
fprintf(OUTMAN, "Usage: %s options input_image output_image\n", argv[0]);
manline();
transform_usage (e_Transform); manline();
wk_filter (F_MALLAT_7_9); manline();
//wk_noise_usage (); manline();
nbr_scale_usage (i_NbPlan); manline();
gauss_usage (); manline();
//ccd_usage (); manline();
// normalize_correl_matrix (); manline();
correl_compute (DEF_CORREL_COMP); manline();
import_correl_file(); manline();
correl_noise (DEF_CORREL_NOISE); manline();
nsigma_mr2d (DEF_SIGMA_MR2D); manline();
//nsigma_pca (DEF_SIGMA_PCA); manline();
positiv_imag_constraint(); manline();
max_imag_constraint(); manline();
write_eigen_on_disk (); manline();
nb_eigen_used (); manline();
vector_not_used (); manline();
wk_conv_param (DEF_CONV_PARAM); manline();
wk_regul_param (DEF_REGUL_PARAM); manline();
wk_type_opt (); manline();
// wk_model_edge (); manline();
wk_data_snr (); manline();
// wk_rms_map () ; manline();
// wk_size_block_sig_clip (DEF_SIZE_BLK); manline();
// wk_nb_iter_sig_clip (DEF_ITER_SIGCLP); manline();
wk_nb_iter_entrop (DEF_ITER_ENTROP); manline();
//write_support_mr2d (); manline();
//write_support_pca (); manline();
verbose (); manline();
exit(-1);
}
void mw_Param::read_image (char *argv[]) {
if (e_Verbose) cout << "Name file IN : " << tc_NameIn << endl;
// read the data (-> fltarray)
fits_read_fltarr (tc_NameIn, ao_3dDataIn);
i_NbCol = ao_3dDataIn.nx(); //col
i_NbLin = ao_3dDataIn.ny(); //lin
i_NbImage = ao_3dDataIn.nz(); //image
// convert data -> Ifloat
po_TabIma = new Ifloat [i_NbImage];
for (int k=0;k<i_NbImage;k++) {
po_TabIma[k].alloc (i_NbLin, i_NbCol, "");
for (int i=0;i<i_NbLin;i++)
for (int j=0;j<i_NbCol;j++)
po_TabIma[k](i,j) = ao_3dDataIn(j,i,k);
}
// verify that all Mr2d have same size
if (!control_image (i_NbImage, po_TabIma)) exit(-1);
// set by default the number of eigen vectors used for the reconstruction
// to the number of images
for (int b=0;b<MAX_NB_BAND;b++)
if (ti_NbrUseEigen[b] < 1 || ti_NbrUseEigen[b] >= i_NbImage)
ti_NbrUseEigen[b] = i_NbImage;
}
void mw_Param::trace () {
cout << "Param IN :" << endl;
cout << " -- [-t:] : type of transform : " << StringTransform(e_Transform) << endl;
if (e_WithNoiseModel) cout << " -- [-m:] : with noise model : " << StringNoise(e_TypeNoise) << endl;
cout << " -- [-n:] : number of plan : " << i_NbPlan << endl;
//cout << " -- [-i:] : number of iteration : " << i_NbIter << endl;
cout << " : number of iteration : " << i_NbIter << endl;
if (f_NoiseIma != 0.) cout << " -- [-g:] : gauss noise : " << f_NoiseIma << endl;
if (f_Gain != 0.) cout << " -- [-c:] : gain : " << f_Gain << ", sigma : " << f_SigmaGauss << ", mean : " << f_MeanGauss << endl;
if (e_NormCorrelMatrix) cout << " -- [-p] : normalize correl matrix" << endl;
if (e_WithNoiseModel) {
cout << " -- [-x:] : correlation compute : " << CorCompTransform(e_CorrelComp) << endl;
if (e_CorrelComp == E_IMPORT)
cout << " -- [-O:] : import correlation file : " << tc_ImportCorMatName << endl;cout << " -- [-y:] : correlation noise : " << CorNoiseTransform(e_CorrelNoise) << endl;
cout << " -- [-s:] : multiresol nsigma : " << f_NSigmaMr2d << endl;
cout << " -- [-S:] : pca nsigma : " << f_NSigmaPCA << endl;
}
cout << " -- [-F:] : number of eigen vector used : " << ti_NbrUseEigen[0] << endl;
cout << " -- [-C:] : convergence parametre : " << f_CvgParam << endl;
cout << " -- [-G:] : regulation parametre : " << f_RegulVal << endl;
cout << " -- [-T:] : type optimisation : " << getTypeOpt (i_TypeOpt) << endl;
if (e_DataEdge) cout << " -- [-A] : use model edge" << endl;
if (e_DataSNR) cout << " -- [-D] : use data SNR" << endl;
if (e_UseRMSMap) cout << "-- [-M] : RMS Map file : " << tc_NameRMSMap << endl;
cout << " -- [-B:] : block size sigma clipping : " << i_SizeBlock << endl;
cout << " -- [-N:] : number of iteration sigma clipping : " << i_NiterClip << endl;
cout << " -- [-i:] : number of iteration for entrop programm : " << i_NbIterEntrop << endl;
if (e_UseReconsAdjoint) cout << " -- [-a] : use rec_adjoint in recons process" << endl;
if (e_PositivImag) cout << " -- [-P] : positivity constraint" << endl;
if (e_MaxImag) cout << " -- [-b] : max image constraint (255)" << endl;
if (e_WriteTransf) cout << " -- [-W] : write transf vect images" << endl;
if (e_WriteEigenOnDisk) cout << " -- [-w] : write eigen vector images" << endl;
if (e_WriteSupportMr2d) cout << " -- [-r] : write Multiresol support" << endl;
if (e_WriteSupportPCA) cout << " -- [-R] : write PCA support" << endl;
if (e_Verbose) cout << " -- [-v] : verbose" << endl;
}
/******************************************************************************
classe mw_Result
******************************************************************************/
mw_Result::mw_Result (mw_Param* ppo_Param) {
po_Param = ppo_Param;
// allocate fltarray for write result
o_3dDataOut.alloc (po_Param->i_NbCol, po_Param->i_NbLin, po_Param->i_NbImage);
// allocate the memory for all multiresol
po_TabMr2d = new MultiResol [po_Param->i_NbImage];
for (int k=0; k<po_Param->i_NbImage; k++)
po_TabMr2d[k].alloc (po_Param->i_NbLin, po_Param->i_NbCol, po_Param->i_NbPlan,
po_Param->e_Transform, po_Param->po_FAS, po_Param->e_Norm);
// init number of band
po_Param->i_NbBand = po_TabMr2d[0].nbr_band();
// class for image correlation analysis
o_Mr2dPca.alloc (po_Param->i_NbImage, po_Param->i_NbBand);
for (int b=0; b<po_Param->i_NbBand-1; b++) {
o_Mr2dPca.MatCor[b].Verbose = po_Param->e_Verbose;
o_Mr2dPca.MatCor[b].NormAna = po_Param->e_NormEigen;
}
// allocate memory for Noise Model classes
if (po_Param->e_WithNoiseModel)
po_TabNoiseModel = new MRNoiseModel [po_Param->i_NbImage];
else
po_TabNoiseModel = (MRNoiseModel*)NULL;
}
mw_Result::~mw_Result () {
delete [] po_TabMr2d;
if (po_Param->e_WithNoiseModel) delete [] po_TabNoiseModel;
}
void mw_Result::res_FirstCompute () {
// create all multiresol
if (po_Param->e_Verbose) cout << "Multiresol transform of data ..." << endl;
for (int k=0; k<po_Param->i_NbImage; k++)
po_TabMr2d[k].transform (po_Param->po_TabIma[k]);
if (po_Param->e_WriteTransf) {
char Mr2dRecons[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(Mr2dRecons, "mr2d_Transf_%d",k+1);
po_TabMr2d[k].write (Mr2dRecons);
}
}
// create all noise model
if (po_Param->e_WithNoiseModel)
res_InitNoiseModelMr2d();
if (po_Param->e_WriteTransf) {
char Mr2dRecons[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(Mr2dRecons, "mr2d_Transf_Thresh_%d",k+1);
po_TabMr2d[k].write (Mr2dRecons);
}
}
// calculate the correlation matrix and its eigen values
if (po_Param->e_Verbose) cout << "Principal component analysis ..." << endl;
if (po_Param->e_WithNoiseModel)
o_Mr2dPca.compute (po_TabMr2d, po_TabNoiseModel,
po_Param->e_NormCorrelMatrix,
po_Param->e_CorrelComp,
po_Param->e_CorrelNoise,
po_Param->po_ImportCorMat);
else
o_Mr2dPca.compute(po_TabMr2d, (MRNoiseModel*)NULL);
// print the result to the standard output
if (po_Param->e_Verbose) o_Mr2dPca.print();
// calculate the eigen vector images
if (po_Param->e_Verbose) cout << "Compute eigen vector images ..." << endl;
o_Mr2dPca.pca_TransfSignal (po_TabMr2d, po_TabMr2d);
if (po_Param->e_WriteTransf) {
char NameEigen[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(NameEigen, "pca_%dEigenVectors_Aft",k+1);
po_TabMr2d[k].write (NameEigen);
}
}
if (po_Param->e_WithNoiseModel) {
res_InitNoiseModelPca ();
//o_Mr2dPca.pca_Thresold (po_TabMr2d, po_TabNoiseModel);
// entrop filter
// -------------
if (po_Param->e_Verbose) cout << "Multiscale Entropy Filtering ..." << endl;
for (int k=0; k<po_Param->i_NbImage; k++) {
fltarray o_TabAlpha(po_Param->i_NbBand-1);
for (int b=0; b < po_Param->i_NbBand-1; b++) o_TabAlpha(b) = po_Param->f_RegulVal;
MultiResol *o_MR_Model = NULL;
if ((po_Param->e_DataEdge == True) && (po_Param->e_Transform == TO_PAVE_BSPLINE)) {
o_MR_Model = new MultiResol(po_Param->i_NbLin, po_Param->i_NbCol,
po_Param->i_NbPlan, po_Param->e_Transform, "Model");
mr_getmodel_from_edge(po_TabMr2d[k], *o_MR_Model, po_TabNoiseModel[k]);
(*o_MR_Model).write("xx_model.mr");
}
for (int b=0; b<po_Param->i_NbBand-1; b++) {
mw_mcfilter (b, po_TabMr2d[k], po_TabNoiseModel[k], po_Param->i_TypeOpt,
o_TabAlpha, po_Param->e_DataSNR, po_Param->e_DataEdge,
o_MR_Model, po_Param->f_CvgParam, po_Param->i_NbIterEntrop,
po_Param->e_PositivImag, po_Param->e_Verbose);
}
}
}
if (po_Param->e_WriteEigenOnDisk) {
char NameEigen[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(NameEigen, "wk_ev_%d",k+1);
po_TabMr2d[k].write (NameEigen);
}
}
}
void mw_Result::res_CurrentCompute () {
// not used
cout << "!!!!! NOT USED !!!!!" << endl;
}
void mw_Result::res_Recons () {
if (po_Param->e_Verbose) cout << "Reconstruction process ..." << endl;
int ai_NbEigen=0;
for (int i=0; i<po_Param->ti_NbrUseEigen[0]; i++) //same value for all bands
if (po_Param->tti_TabKill[i][0] == 0) ai_NbEigen++;
if (po_Param->e_Verbose) cout << "Number of eigen vector used for the reconstruction : " ;
if (po_Param->e_Verbose) cout << "Ne = " << ai_NbEigen << " (in all band)" << endl;
// apply the inverse reconstruction from a subset of eigen vectors
o_Mr2dPca.invsubtransform (po_TabMr2d, po_TabMr2d, po_Param->ti_NbrUseEigen,
po_Param->tti_TabKill);
// inv transform Mr2d
for (int k=0; k<po_Param->i_NbImage; k++)
if (po_Param->e_UseReconsAdjoint) po_TabMr2d[k].rec_adjoint(po_Param->po_TabIma[k]);
else po_TabMr2d[k].recons(po_Param->po_TabIma[k]);
// Write Mr2d recons
if (po_Param->e_WriteTransf == True) {
char Mr2dRecons[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(Mr2dRecons, "mr2d_pca_InvTransf_%d",k+1);
po_TabMr2d[k].write (Mr2dRecons);
sprintf(Mr2dRecons, "mr2d_pca_InvImag_%d", k+1);
io_write_ima_float(Mr2dRecons, po_Param->po_TabIma[k]);
}
}
}
void mw_Result::res_Write () {
if (po_Param->e_Verbose) cout << "Write result ..." << endl;
for (int k=0;k<po_Param->i_NbImage;k++)
for (int i=0;i<po_Param->i_NbLin;i++)
for (int j=0;j<po_Param->i_NbCol;j++)
o_3dDataOut(j,i,k) = po_Param->po_TabIma[k](i,j);
// write the data
fits_write_fltarr (po_Param->tc_NameOut, o_3dDataOut);
}
void mw_Result::res_InitNoiseModelMr2d () {
// noise model class initialization
if (po_Param->e_Verbose) cout << "Create mr2d noise model ..." << endl;
for (int k=0; k<po_Param->i_NbImage; k++) {
po_TabNoiseModel[k].alloc (po_Param->e_TypeNoise, po_Param->i_NbLin,
po_Param->i_NbCol, po_Param->i_NbPlan,
po_Param->e_Transform);
if (po_Param->f_NoiseIma > FLOAT_EPSILON)
po_TabNoiseModel[k].SigmaNoise = po_Param->f_NoiseIma;
po_TabNoiseModel[k].CCD_Gain = po_Param->f_Gain;
po_TabNoiseModel[k].CCD_ReadOutSigma = po_Param->f_SigmaGauss;
po_TabNoiseModel[k].CCD_ReadOutMean = po_Param->f_MeanGauss;
// entrop
po_TabNoiseModel[k].NiterSigmaClip = po_Param->i_NiterClip;
po_TabNoiseModel[k].SizeBlockSigmaNoise = po_Param->i_SizeBlock;
if (po_Param->e_UseRMSMap == True) {
po_TabNoiseModel[k].UseRmsMap = True;
io_read_ima_float(po_Param->tc_NameRMSMap, po_TabNoiseModel[k].RmsMap);
}
if (po_Param->e_TypeNoise == NOISE_SPECKLE)
po_TabNoiseModel[k].SigmaApprox = True;
// end entrop
if (po_Param->f_NSigmaMr2d >= 0)
for (int i=0; i<po_Param->i_NbPlan; i++)
po_TabNoiseModel[k].NSigma[i] = po_Param->f_NSigmaMr2d;
//po_TabNoiseModel[k].SupIsol = po_Param->e_SupIsolPixel;
po_TabNoiseModel[k].model (po_Param->po_TabIma[k]);
if (po_Param->e_WriteSupportMr2d) {
char NameSupport[256];
sprintf(NameSupport, "mr2d_Support_%d",k+1);
po_TabNoiseModel[k].write_support_mr (NameSupport);
}
}
//if (po_Param->e_ModNoiseModelMr2d) res_ModSupport (po_Param->f_ModNsigmaMr2d);
}
void mw_Result::res_InitNoiseModelPca () {
// noise model class initialization
if (po_Param->e_Verbose) cout << "Create pca noise model ..." << endl;
int k;
o_Mr2dPca.pca_ComputeNoise (po_TabMr2d, po_TabNoiseModel, po_TabNoiseModel);
for (k=0; k<po_Param->i_NbImage; k++) {
//if (po_Param->e_DilateSupportPCA) po_TabNoiseModel[k].DilateSupport = True;
if (po_Param->f_NSigmaPCA >= 0)
for (int i=0; i<po_Param->i_NbPlan; i++)
po_TabNoiseModel[k].NSigma[i] = po_Param->f_NSigmaPCA;
else {
po_TabNoiseModel[k].NSigma[0] = 4;
for (int i=1; i<po_Param->i_NbPlan; i++)
po_TabNoiseModel[k].NSigma[i] = 3;
}
po_TabNoiseModel[k].set_support (po_TabMr2d[k]);
//if (po_Param->e_DestroyRings) res_DestroyRingsInPcaSup ();
}
//if (po_Param->e_ModNoiseModelEntrop) res_ModSupport (po_Param->f_ModNsigmaEntrop);
for (k=0; k<po_Param->i_NbImage; k++)
if (po_Param->e_WriteSupportPCA) {
char NameSupport[256];
sprintf(NameSupport, "pca_Support_%d",k+1);
po_TabNoiseModel[k].write_support_mr (NameSupport);
}
}
to_Param* mw_Result::res_GetpParam () {return po_Param;}
/******************************************************************************
classe pca_Iter
******************************************************************************/
Bool mw_Iter::iter_End () {
//cout << " ==> END" << endl;
NbIter++;
if (NbIter > po_Result->po_Param->i_NbIter) {
for (int k=0;k<po_Result->po_Param->i_NbImage;k++)
for (int i=0;i<po_Result->po_Param->i_NbLin;i++)
for (int j=0;j<po_Result->po_Param->i_NbCol;j++) {
po_Result->po_Param->po_TabIma[k](i,j) = o_3dResidu(i,j,k);
if ( po_Result->po_Param->e_PositivImag
&& po_Result->po_Param->po_TabIma[k](i,j)<0.)
po_Result->po_Param->po_TabIma[k](i,j) = 0.0;
if ( po_Result->po_Param->e_MaxImag
&& po_Result->po_Param->po_TabIma[k](i,j)>MAX_IMAG_VALUE)
po_Result->po_Param->po_TabIma[k](i,j) = MAX_IMAG_VALUE;
}
return False;
} else return True;
}
void mw_Iter::iter_Residu () {
for (int k=0;k<po_Result->po_Param->i_NbImage;k++)
for (int i=0;i<po_Result->po_Param->i_NbLin;i++)
for (int j=0;j<po_Result->po_Param->i_NbCol;j++) {
// positiv constraint
if ( po_Result->po_Param->e_PositivImag
&& po_Result->po_Param->po_TabIma[k](i,j)<0.)
po_Result->po_Param->po_TabIma[k](i,j) = 0.0;
if ( po_Result->po_Param->e_MaxImag
&& po_Result->po_Param->po_TabIma[k](i,j)>MAX_IMAG_VALUE)
po_Result->po_Param->po_TabIma[k](i,j) = MAX_IMAG_VALUE;
// I(i) = I(i) + E(i)
o_3dResidu(i,j,k) += po_Result->po_Param->po_TabIma[k](i,j);
// E(i) = Einit - I(i)
po_Result->po_Param->po_TabIma[k](i,j) = o_3dInit(i,j,k) - o_3dResidu(i,j,k);
}
}
to_Result* mw_Iter::iter_getpResult() {return po_Result;}
| 33.946369 | 185 | 0.567737 | sfarrens |
6ae360a34abc4f5893f82ff330cafa3afa08a271 | 3,073 | cpp | C++ | mlir/lib/Dialect/SCF/Transforms/Utils.cpp | elizabethandrews/llvm | 308498236c1c4778fdcba0bfbb556adf8aa333ea | [
"Apache-2.0"
] | 5 | 2021-02-21T22:35:08.000Z | 2022-02-01T18:22:50.000Z | mlir/lib/Dialect/SCF/Transforms/Utils.cpp | elizabethandrews/llvm | 308498236c1c4778fdcba0bfbb556adf8aa333ea | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/SCF/Transforms/Utils.cpp | elizabethandrews/llvm | 308498236c1c4778fdcba0bfbb556adf8aa333ea | [
"Apache-2.0"
] | 1 | 2021-03-30T11:22:52.000Z | 2021-03-30T11:22:52.000Z | //===- LoopUtils.cpp ---- Misc utilities for loop transformation ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements miscellaneous loop transformation routines.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/SCF/Utils.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/IR/BlockAndValueMapping.h"
using namespace mlir;
scf::ForOp mlir::cloneWithNewYields(OpBuilder &b, scf::ForOp loop,
ValueRange newIterOperands,
ValueRange newYieldedValues,
bool replaceLoopResults) {
assert(newIterOperands.size() == newYieldedValues.size() &&
"newIterOperands must be of the same size as newYieldedValues");
// Create a new loop before the existing one, with the extra operands.
OpBuilder::InsertionGuard g(b);
b.setInsertionPoint(loop);
auto operands = llvm::to_vector<4>(loop.getIterOperands());
operands.append(newIterOperands.begin(), newIterOperands.end());
scf::ForOp newLoop =
b.create<scf::ForOp>(loop.getLoc(), loop.lowerBound(), loop.upperBound(),
loop.step(), operands);
auto &loopBody = *loop.getBody();
auto &newLoopBody = *newLoop.getBody();
// Clone / erase the yield inside the original loop to both:
// 1. augment its operands with the newYieldedValues.
// 2. automatically apply the BlockAndValueMapping on its operand
auto yield = cast<scf::YieldOp>(loopBody.getTerminator());
b.setInsertionPoint(yield);
auto yieldOperands = llvm::to_vector<4>(yield.getOperands());
yieldOperands.append(newYieldedValues.begin(), newYieldedValues.end());
auto newYield = b.create<scf::YieldOp>(yield.getLoc(), yieldOperands);
// Clone the loop body with remaps.
BlockAndValueMapping bvm;
// a. remap the induction variable.
bvm.map(loop.getInductionVar(), newLoop.getInductionVar());
// b. remap the BB args.
bvm.map(loopBody.getArguments(),
newLoopBody.getArguments().take_front(loopBody.getNumArguments()));
// c. remap the iter args.
bvm.map(newIterOperands,
newLoop.getRegionIterArgs().take_back(newIterOperands.size()));
b.setInsertionPointToStart(&newLoopBody);
// Skip the original yield terminator which does not have enough operands.
for (auto &o : loopBody.without_terminator())
b.clone(o, bvm);
// Replace `loop`'s results if requested.
if (replaceLoopResults) {
for (auto it : llvm::zip(loop.getResults(), newLoop.getResults().take_front(
loop.getNumResults())))
std::get<0>(it).replaceAllUsesWith(std::get<1>(it));
}
// TODO: this is unsafe in the context of a PatternRewrite.
newYield.erase();
return newLoop;
}
| 41.527027 | 80 | 0.639115 | elizabethandrews |
6ae6a7e0e48180369557b67610a597b9a1dc3d7e | 35 | hpp | C++ | src/boost_mpl_erase_key.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_erase_key.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_erase_key.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/erase_key.hpp>
| 17.5 | 34 | 0.771429 | miathedev |
6ae8e74c21d8b4d41a188d60ed3432e257810ccb | 3,094 | cpp | C++ | hotspot/src/share/vm/utilities/accessFlags.cpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | hotspot/src/share/vm/utilities/accessFlags.cpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | hotspot/src/share/vm/utilities/accessFlags.cpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "oops/oop.inline.hpp"
#include "utilities/accessFlags.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
void AccessFlags::atomic_set_bits(jint bits) {
// Atomically update the flags with the bits given
jint old_flags, new_flags, f;
do {
old_flags = _flags;
new_flags = old_flags | bits;
f = Atomic::cmpxchg(new_flags, &_flags, old_flags);
} while(f != old_flags);
}
void AccessFlags::atomic_clear_bits(jint bits) {
// Atomically update the flags with the bits given
jint old_flags, new_flags, f;
do {
old_flags = _flags;
new_flags = old_flags & ~bits;
f = Atomic::cmpxchg(new_flags, &_flags, old_flags);
} while(f != old_flags);
}
#if !defined(PRODUCT) || INCLUDE_JVMTI
void AccessFlags::print_on(outputStream* st) const {
if (is_public ()) st->print("public " );
if (is_private ()) st->print("private " );
if (is_protected ()) st->print("protected " );
if (is_static ()) st->print("static " );
if (is_final ()) st->print("final " );
if (is_synchronized()) st->print("synchronized ");
if (is_volatile ()) st->print("volatile " );
if (is_transient ()) st->print("transient " );
if (is_native ()) st->print("native " );
if (is_interface ()) st->print("interface " );
if (is_abstract ()) st->print("abstract " );
if (is_strict ()) st->print("strict " );
if (is_synthetic ()) st->print("synthetic " );
if (is_old ()) st->print("{old} " );
if (is_obsolete ()) st->print("{obsolete} " );
if (on_stack ()) st->print("{on_stack} " );
}
#endif // !PRODUCT || INCLUDE_JVMTI
void accessFlags_init() {
assert(sizeof(AccessFlags) == sizeof(jint), "just checking size of flags");
}
| 35.159091 | 79 | 0.672269 | dbac |
6aea0025ac40348e55610fe95499e54f4e368d9a | 10,704 | cc | C++ | src/Basics/IsotopeData.cc | pygamma-mrs/gamma | c83a7c242c481d2ecdfd49ba394fea3d5816bccb | [
"BSD-3-Clause"
] | 4 | 2021-03-15T10:02:13.000Z | 2022-01-16T11:06:28.000Z | src/Basics/IsotopeData.cc | pygamma-mrs/gamma | c83a7c242c481d2ecdfd49ba394fea3d5816bccb | [
"BSD-3-Clause"
] | 1 | 2022-01-27T15:35:03.000Z | 2022-01-27T15:35:03.000Z | src/Basics/IsotopeData.cc | pygamma-mrs/gamma | c83a7c242c481d2ecdfd49ba394fea3d5816bccb | [
"BSD-3-Clause"
] | null | null | null | /* IsotopeData.cc ***********************************************-*-c++-*-
** **
** G A M M A **
** **
** IsotopeData Implementation **
** **
** Copyright (c) 1990, 1999 **
** Tilo Levante, Scott A. Smith **
** Eidgenoessische Technische Hochschule **
** Labor fur physikalische Chemie **
** 8092 Zurich / Switzerland **
** **
** $Header: $
** **
*************************************************************************/
/*************************************************************************
** **
** Description **
** **
** Class IsotopeData embodies a single spin isotope. Each object of **
** this type contains all the required data corresponding to a single **
** Isotope for use in magnetic resonance computation. Some access **
** functions & output constants are provided. **
** **
** Note that users will rarely (if ever) deal with this file. GAMMA **
** contains a linked list of most known spin isotopes, each element of **
** the list being an object of type IsotopeData. Higher classes and **
** GAMMA based programs use the linked list and class Isotope (a **
** pointer into the isotopes list) rather than objects of this type. **
** **
*************************************************************************/
#ifndef IsotopeData_cc_ // Is this file already included?
# define IsotopeData_cc_ 1 // If no, then remember it
# if defined(GAMPRAGMA) // Using the GNU compiler?
# pragma implementation // Then this is the implementation
# endif
#include <Basics/IsotopeData.h> // Include the interface
#include <Basics/StringCut.h> // Include string cutting
#include <iostream> // Include libstdc++ iostreams
#include <vector> // Include llibstdc++ STL vectors
using std::string; // Using libstdc++ strings
// ----------------------------------------------------------------------------
// --------------------------- PRIVATE FUNCTIONS ------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ---------------------------- PUBLIC FUNCTIONS ------------------------------
// ----------------------------------------------------------------------------
// ____________________________________________________________________________
// A SINGLE ISOTOPE CONSTRUCTORS
// ____________________________________________________________________________
/* In these constructors the individual values are best set in the
same order as they exist in the class definition. */
// Input HS_ : Int for Isotope Hilbert space (2, 3, 4)
// symb_ : String for Isotope symbol (1H, 2H, 14N)
// name_ : String for Isotope name (Hydrogen)
// elem_ : String for Isotope element (H, Li, C)
// numb_ : Int for the Isotope number (1@H, 3@Li)
// mass_ : Int for the Isotope mass (1@H, 13@C)
// wght_ : Double Isotope weight (in g/mol)
// rcpt_ : Double Isotope receptivity ()
// rfrq_ : Double Isotope rel. freq. ()
// elec_ : bool flag for electron/nucleus
// Output this : Constructs IsotopeData from
// all information each isotope contains
// Note : Construction with string for symbol will
// ONLY sets the isotope symbol, nothing
// else and will produce problems if the
// other data parameters aren't filled.
IsotopeData::IsotopeData()
{
_HS=0;
_number=0;
_mass=0;
_weight=0;
_receptivity=0;
_relfreq=0;
_iselectron=false;
}
IsotopeData::IsotopeData(const IsotopeData& ID)
: _HS(ID._HS),
_symbol(ID._symbol),
_name(ID._name),
_element(ID._element),
_number(ID._number),
_mass(ID._mass),
_weight(ID._weight),
_receptivity(ID._receptivity),
_relfreq(ID._relfreq),
_iselectron(ID._iselectron) {}
IsotopeData::IsotopeData(int HS_, const string& symb_, const string& name_,
string elem_, int numb_, int mass_, double wght_,
double rcpt_, double rfrq_, bool elec_)
: _HS(HS_),
_symbol(symb_),
_name(name_),
_element(elem_),
_number(numb_),
_mass(mass_),
_weight(wght_),
_receptivity(rcpt_),
_relfreq(rfrq_),
_iselectron(elec_) {}
IsotopeData::IsotopeData(const string& symb) : _symbol(symb)
{
_HS = 0;
_name = string("Unknown");
_element = string("XXX");
_number = 0;
_mass = 0;
_weight = 0;
_receptivity = 0;
_relfreq = 0;
_iselectron = false;
}
IsotopeData& IsotopeData::operator= (const IsotopeData& ID1)
{
_HS = ID1._HS;
_symbol = ID1._symbol;
_name = ID1._name;
_element = ID1._element;
_number = ID1._number;
_mass = ID1._mass;
_weight = ID1._weight;
_receptivity = ID1._receptivity;
_relfreq = ID1._relfreq;
_iselectron = ID1._iselectron;
return (*this);
}
IsotopeData::~IsotopeData() {}
// ____________________________________________________________________________
// B SINGLE ISOTOPE ACCESS FUNCTIONS
// ____________________________________________________________________________
/* Function Return Value Example(s)
-------- ------- ------ ------------------------------------------
qn double mz 0.5, 1.0, 1.5, ...... in units of hbar
HS integer 2*mz+1 2<-1/2, 3<-1,...... spin Hilbert space
momentum string mz 1/2, 1, 3/2, ...... in units of hbar
symbol string 1H, 2H, 19F, 13C, ......
name string Hydrogen, Lithium, Carbon, ....
element string H, Li, F, C, ....
number integer at.# 1<-H, 3<-Li, 6<-C, ....
mass integer at.mass 1<-1H, 2<-2H, 13<-13C, .... in amu units
weight double at.wt. 1.00866<-1H, 7.016<-7Li, ... in grams/mole
recept. double 5680, 1540, .....
rel.frq. double 400.13, 155.503, .. in MHz (1H based) */
double IsotopeData::qn() const { return (_HS ? (_HS-1)/2.0 : 0); }
int IsotopeData::HS() const { return _HS; }
const string& IsotopeData::symbol() const { return _symbol; }
const string& IsotopeData::name() const { return _name; }
const string& IsotopeData::element() const { return _element; }
int IsotopeData::number() const { return _number; }
int IsotopeData::mass() const { return _mass; }
double IsotopeData::weight() const { return _weight; }
bool IsotopeData::electron() const { return _iselectron; }
double IsotopeData::recept() const { return _receptivity; }
double IsotopeData::rel_freq() const { return _relfreq; }
string IsotopeData::momentum() const
{
if(!_HS) return string("0"); // If no _HS, then it's zero
else if(_HS%2) return Gdec(int((_HS-1)/2)); // If odd _HS, return fraction
else return string(Gdec(int(_HS-1)))+ string("/2"); // If even _HS, return whole int
}
// ____________________________________________________________________________
// C SINGLE ISOTOPE I/O FUNCTIONS
// ____________________________________________________________________________
/* These send basic information about the isotope to the output stream.*/
// Input ID : An IsotopeData (this)
// ostr : An output stream ostr
// lf : Line feed flag
// hdr : Flag if header output
// Output ostr : The output stream, modified to
// contain the information about ID
std::vector<string> IsotopeData::printStrings(bool hdr) const
{
std::vector<string> PStrings;
if(hdr)
PStrings.push_back(string("Isotope ") + _symbol);
if(_name.length())
PStrings.push_back(string(" Name ") + _name);
else
PStrings.push_back(string(" Name Unknown"));
if(_element.length())
PStrings.push_back(string(" Element ") + _element);
else
PStrings.push_back(string(" Element Unknown"));
PStrings.push_back(string(" Number ") + Gdec(_number));
PStrings.push_back(string(" Mass ") + Gdec(_mass) + string(" amu"));
string Stmp(" Weight ");
string Sfrm("%8.4f");
if(_weight < 100) Sfrm = string("%7.4f");
if(_weight < 10) Sfrm = string("%6.4f");
PStrings.push_back( Stmp + Gform(Sfrm, _weight) + string(" g/m"));
PStrings.push_back(string(" Spin ") + Gform("%3.1f", qn()) + string(" (hbar)"));
string X = " Type ";
if(_iselectron) X += "electron";
else X += "nucleus";
PStrings.push_back(X);
return PStrings;
}
std::ostream& IsotopeData::print(std::ostream& ostr, int lf, bool hdr) const
{
std::vector<string> PStrings = printStrings(hdr);
for(unsigned i=0; i<PStrings.size(); i++)
ostr << PStrings[i] << std::endl;
if(lf) ostr << std::endl;
return ostr;
}
std::ostream& operator<< (std::ostream& ostr, const IsotopeData& ID)
{ return ID.print(ostr); }
#endif // IsotopeData.cc
| 44.414938 | 93 | 0.484679 | pygamma-mrs |
6aea3a9622f0284b176a7c00991e70f413a9a702 | 21,305 | hpp | C++ | include/UnityEngine/TouchScreenKeyboard.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/UnityEngine/TouchScreenKeyboard.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/UnityEngine/TouchScreenKeyboard.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
// Including type: UnityEngine.TouchScreenKeyboardType
#include "UnityEngine/TouchScreenKeyboardType.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: RangeInt
struct RangeInt;
// Forward declaring type: TouchScreenKeyboard_InternalConstructorHelperArguments
struct TouchScreenKeyboard_InternalConstructorHelperArguments;
}
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.TouchScreenKeyboard
// [TokenAttribute] Offset: FFFFFFFF
// [NativeHeaderAttribute] Offset: DB5D48
// [NativeConditionalAttribute] Offset: DB5D48
// [NativeHeaderAttribute] Offset: DB5D48
class TouchScreenKeyboard : public ::Il2CppObject {
public:
// Nested type: UnityEngine::TouchScreenKeyboard::Status
struct Status;
// System.IntPtr m_Ptr
// Size: 0x8
// Offset: 0x10
System::IntPtr m_Ptr;
// Field size check
static_assert(sizeof(System::IntPtr) == 0x8);
// Creating value type constructor for type: TouchScreenKeyboard
TouchScreenKeyboard(System::IntPtr m_Ptr_ = {}) noexcept : m_Ptr{m_Ptr_} {}
// Creating conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept {
return m_Ptr;
}
// Get instance field reference: System.IntPtr m_Ptr
System::IntPtr& dyn_m_Ptr();
// static public System.Boolean get_isSupported()
// Offset: 0x235B8D8
static bool get_isSupported();
// static public System.Boolean get_isInPlaceEditingAllowed()
// Offset: 0x235B960
static bool get_isInPlaceEditingAllowed();
// public System.String get_text()
// Offset: 0x235BABC
::Il2CppString* get_text();
// public System.Void set_text(System.String value)
// Offset: 0x235BAFC
void set_text(::Il2CppString* value);
// static public System.Void set_hideInput(System.Boolean value)
// Offset: 0x235BB4C
static void set_hideInput(bool value);
// public System.Boolean get_active()
// Offset: 0x235BB8C
bool get_active();
// public System.Void set_active(System.Boolean value)
// Offset: 0x235BBCC
void set_active(bool value);
// public UnityEngine.TouchScreenKeyboard/UnityEngine.Status get_status()
// Offset: 0x235BC1C
UnityEngine::TouchScreenKeyboard::Status get_status();
// public System.Void set_characterLimit(System.Int32 value)
// Offset: 0x235BC5C
void set_characterLimit(int value);
// public System.Boolean get_canGetSelection()
// Offset: 0x235BCAC
bool get_canGetSelection();
// public System.Boolean get_canSetSelection()
// Offset: 0x235BCEC
bool get_canSetSelection();
// public UnityEngine.RangeInt get_selection()
// Offset: 0x235BD2C
UnityEngine::RangeInt get_selection();
// public System.Void set_selection(UnityEngine.RangeInt value)
// Offset: 0x235BDD8
void set_selection(UnityEngine::RangeInt value);
// public System.Void .ctor(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure, System.Boolean alert, System.String textPlaceholder, System.Int32 characterLimit)
// Offset: 0x235B71C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TouchScreenKeyboard* New_ctor(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, ::Il2CppString* textPlaceholder, int characterLimit) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::TouchScreenKeyboard::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TouchScreenKeyboard*, creationType>(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, characterLimit)));
}
// static private System.Void Internal_Destroy(System.IntPtr ptr)
// Offset: 0x235B5C0
static void Internal_Destroy(System::IntPtr ptr);
// private System.Void Destroy()
// Offset: 0x235B600
void Destroy();
// static private System.IntPtr TouchScreenKeyboard_InternalConstructorHelper(ref UnityEngine.TouchScreenKeyboard_InternalConstructorHelperArguments arguments, System.String text, System.String textPlaceholder)
// Offset: 0x235B880
static System::IntPtr TouchScreenKeyboard_InternalConstructorHelper(ByRef<UnityEngine::TouchScreenKeyboard_InternalConstructorHelperArguments> arguments, ::Il2CppString* text, ::Il2CppString* textPlaceholder);
// static public UnityEngine.TouchScreenKeyboard Open(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure, System.Boolean alert, System.String textPlaceholder, System.Int32 characterLimit)
// Offset: 0x235B968
static UnityEngine::TouchScreenKeyboard* Open(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, ::Il2CppString* textPlaceholder, int characterLimit);
// static public UnityEngine.TouchScreenKeyboard Open(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure)
// Offset: 0x235BA28
static UnityEngine::TouchScreenKeyboard* Open(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure);
// static private System.Void GetSelection(out System.Int32 start, out System.Int32 length)
// Offset: 0x235BD88
static void GetSelection(ByRef<int> start, ByRef<int> length);
// static private System.Void SetSelection(System.Int32 start, System.Int32 length)
// Offset: 0x235BEE0
static void SetSelection(int start, int length);
// protected override System.Void Finalize()
// Offset: 0x235B6B4
// Implemented from: System.Object
// Base method: System.Void Object::Finalize()
void Finalize();
}; // UnityEngine.TouchScreenKeyboard
#pragma pack(pop)
static check_size<sizeof(TouchScreenKeyboard), 16 + sizeof(System::IntPtr)> __UnityEngine_TouchScreenKeyboardSizeCheck;
static_assert(sizeof(TouchScreenKeyboard) == 0x18);
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TouchScreenKeyboard*, "UnityEngine", "TouchScreenKeyboard");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_isSupported
// Il2CppName: get_isSupported
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&UnityEngine::TouchScreenKeyboard::get_isSupported)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_isSupported", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_isInPlaceEditingAllowed
// Il2CppName: get_isInPlaceEditingAllowed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&UnityEngine::TouchScreenKeyboard::get_isInPlaceEditingAllowed)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_isInPlaceEditingAllowed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_text
// Il2CppName: get_text
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_text)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_text
// Il2CppName: set_text
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(::Il2CppString*)>(&UnityEngine::TouchScreenKeyboard::set_text)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_hideInput
// Il2CppName: set_hideInput
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(bool)>(&UnityEngine::TouchScreenKeyboard::set_hideInput)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_hideInput", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_active
// Il2CppName: get_active
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_active)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_active", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_active
// Il2CppName: set_active
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(bool)>(&UnityEngine::TouchScreenKeyboard::set_active)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_active", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_status
// Il2CppName: get_status
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard::Status (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_status)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_status", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_characterLimit
// Il2CppName: set_characterLimit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(int)>(&UnityEngine::TouchScreenKeyboard::set_characterLimit)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_characterLimit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_canGetSelection
// Il2CppName: get_canGetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_canGetSelection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_canGetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_canSetSelection
// Il2CppName: get_canSetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_canSetSelection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_canSetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_selection
// Il2CppName: get_selection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::RangeInt (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_selection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_selection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_selection
// Il2CppName: set_selection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(UnityEngine::RangeInt)>(&UnityEngine::TouchScreenKeyboard::set_selection)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "RangeInt")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_selection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Internal_Destroy
// Il2CppName: Internal_Destroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(System::IntPtr)>(&UnityEngine::TouchScreenKeyboard::Internal_Destroy)> {
static const MethodInfo* get() {
static auto* ptr = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Internal_Destroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ptr});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Destroy
// Il2CppName: Destroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::Destroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Destroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::TouchScreenKeyboard_InternalConstructorHelper
// Il2CppName: TouchScreenKeyboard_InternalConstructorHelper
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IntPtr (*)(ByRef<UnityEngine::TouchScreenKeyboard_InternalConstructorHelperArguments>, ::Il2CppString*, ::Il2CppString*)>(&UnityEngine::TouchScreenKeyboard::TouchScreenKeyboard_InternalConstructorHelper)> {
static const MethodInfo* get() {
static auto* arguments = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboard_InternalConstructorHelperArguments")->this_arg;
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* textPlaceholder = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "TouchScreenKeyboard_InternalConstructorHelper", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{arguments, text, textPlaceholder});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Open
// Il2CppName: Open
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard* (*)(::Il2CppString*, UnityEngine::TouchScreenKeyboardType, bool, bool, bool, bool, ::Il2CppString*, int)>(&UnityEngine::TouchScreenKeyboard::Open)> {
static const MethodInfo* get() {
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* keyboardType = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboardType")->byval_arg;
static auto* autocorrection = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* multiline = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* secure = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* alert = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* textPlaceholder = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* characterLimit = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Open", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, characterLimit});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Open
// Il2CppName: Open
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard* (*)(::Il2CppString*, UnityEngine::TouchScreenKeyboardType, bool, bool, bool)>(&UnityEngine::TouchScreenKeyboard::Open)> {
static const MethodInfo* get() {
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* keyboardType = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboardType")->byval_arg;
static auto* autocorrection = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* multiline = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* secure = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Open", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{text, keyboardType, autocorrection, multiline, secure});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::GetSelection
// Il2CppName: GetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(ByRef<int>, ByRef<int>)>(&UnityEngine::TouchScreenKeyboard::GetSelection)> {
static const MethodInfo* get() {
static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "GetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{start, length});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::SetSelection
// Il2CppName: SetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(int, int)>(&UnityEngine::TouchScreenKeyboard::SetSelection)> {
static const MethodInfo* get() {
static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "SetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{start, length});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Finalize
// Il2CppName: Finalize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::Finalize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Finalize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 64.560606 | 290 | 0.751936 | Fernthedev |
6aeb0a76c41d41c7ea33721bd2927145d84513e9 | 515 | cpp | C++ | TextRPG/src/UIScreen.cpp | UniqueVN/TextRPG | 78c585a61692c8470145d755d2da3f1a3586af88 | [
"MIT",
"Unlicense"
] | 1 | 2021-03-12T09:47:20.000Z | 2021-03-12T09:47:20.000Z | TextRPG/src/UIScreen.cpp | UniqueVN/TextRPG | 78c585a61692c8470145d755d2da3f1a3586af88 | [
"MIT",
"Unlicense"
] | null | null | null | TextRPG/src/UIScreen.cpp | UniqueVN/TextRPG | 78c585a61692c8470145d755d2da3f1a3586af88 | [
"MIT",
"Unlicense"
] | null | null | null | #include "UIComponent.h"
#include "UIManager.h"
#include "UIScreen.h"
UIScreen::UIScreen(UIComponent* parent) : UIComponent(parent)
{
// Register this screen with the UIManager
}
UIScreen::~UIScreen(void)
{
}
void UIScreen::OnInit()
{
UIComponent::OnInit();
UIManager* manager = UIManager::GetInstance();
manager->RegisterScreen(this);
// Auto make the screen align to the top-left of the screen if its position not specified
if (Pos == vector2i(-1, -1))
Pos = vector2i(0, 0);
} | 21.458333 | 93 | 0.679612 | UniqueVN |
6aeb21231db00566f58228ffe2b3efc2e1faf4c8 | 4,562 | cpp | C++ | tools/config_handlers/dp_handler.cpp | mcorino/dancex11 | 297cb17066873ad7f30e88b0e8d64cd0e6ed2f68 | [
"MIT"
] | 4 | 2016-04-12T15:09:28.000Z | 2020-01-16T10:42:55.000Z | tools/config_handlers/dp_handler.cpp | mcorino/dancex11 | 297cb17066873ad7f30e88b0e8d64cd0e6ed2f68 | [
"MIT"
] | null | null | null | tools/config_handlers/dp_handler.cpp | mcorino/dancex11 | 297cb17066873ad7f30e88b0e8d64cd0e6ed2f68 | [
"MIT"
] | 4 | 2016-04-12T18:40:25.000Z | 2019-11-16T14:41:45.000Z | /**
* @file dp_handler.cpp
* @author Marijke Hengstmengel
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "dp_handler.h"
#include "ccd_handler.h"
#include "add_handler.h"
#include "mdd_handler.h"
#include "idd_handler.h"
#include "id_handler.h"
#include "pl_handler.h"
#include "property_handler.h"
#include "cdp.hpp"
#include "pcd_handler.h"
#include "dancex11/logger/log.h"
#include <unordered_map>
namespace DAnCEX11
{
namespace Config_Handlers
{
std::unique_ptr<Deployment::DeploymentPlan>
DP_Handler::resolve_plan (const DAnCE::Config_Handlers::deploymentPlan &xsc_dp) const
{
DANCEX11_LOG_TRACE ("DP_Handler::resolve_plan");
std::unique_ptr<Deployment::DeploymentPlan> idl_dp = std::make_unique<Deployment::DeploymentPlan> ();
if (xsc_dp.label_p ())
{
idl_dp->label (xsc_dp.label ());
}
if (xsc_dp.UUID_p ())
{
idl_dp->UUID (xsc_dp.UUID ());
}
std::transform(xsc_dp.begin_dependsOn (),
xsc_dp.end_dependsOn (),
std::back_inserter(idl_dp->dependsOn()),
DAnCEX11::Config_Handlers::convert_implementationdependency);
std::transform(xsc_dp.begin_infoProperty (),
xsc_dp.end_infoProperty (),
std::back_inserter(idl_dp->infoProperty()),
DAnCEX11::Config_Handlers::convert_property);
if (xsc_dp.realizes_p ())
{
idl_dp->realizes(DAnCEX11::Config_Handlers::convert_componentinterfacedescription (xsc_dp.realizes ()));
}
std::unordered_map<std::string, size_t> artifact_map;
std::transform(xsc_dp.begin_artifact (),
xsc_dp.end_artifact (),
std::back_inserter(idl_dp->artifact()),
[&](const DAnCE::Config_Handlers::ArtifactDeploymentDescription& src)
{
if (src.id_p ())
{
artifact_map.insert({src.id (), idl_dp->artifact().size () });
}
return DAnCEX11::Config_Handlers::convert_artifactdeploymentdescription(src);
});
std::unordered_map<std::string, size_t> monolithicdeploymentdescription_map;
std::transform(xsc_dp.begin_implementation (),
xsc_dp.end_implementation (),
std::back_inserter(idl_dp->implementation()),
[&](const DAnCE::Config_Handlers::MonolithicDeploymentDescription& src)
{
if (src.id_p ())
{
monolithicdeploymentdescription_map.insert({src.id (), idl_dp->implementation().size () });
}
return DAnCEX11::Config_Handlers::convert_monolithicdeploymentdescription(src, artifact_map);
});
std::unordered_map<std::string, size_t> instancedeploymentdescription_map;
std::transform(xsc_dp.begin_instance (),
xsc_dp.end_instance (),
std::back_inserter(idl_dp->instance()),
[&](const DAnCE::Config_Handlers::InstanceDeploymentDescription& src)
{
if (src.id_p ())
{
instancedeploymentdescription_map.insert({src.id (), idl_dp->instance().size () });
}
return DAnCEX11::Config_Handlers::convert_instancedeploymentdescription(src, monolithicdeploymentdescription_map);
});
std::transform(xsc_dp.begin_connection (),
xsc_dp.end_connection (),
std::back_inserter(idl_dp->connection()),
[&](const DAnCE::Config_Handlers::PlanConnectionDescription& src)
{
return DAnCEX11::Config_Handlers::convert_planconnectiondescription(src, instancedeploymentdescription_map);
});
std::transform(xsc_dp.begin_localityConstraint (),
xsc_dp.end_localityConstraint (),
std::back_inserter(idl_dp->localityConstraint()),
[&](const DAnCE::Config_Handlers::PlanLocality& src)
{
return DAnCEX11::Config_Handlers::convert_planlocality(src, instancedeploymentdescription_map);
});
return idl_dp;
}
}
}
| 39.327586 | 137 | 0.563788 | mcorino |
6aec5eb63f5a8bda8283c931d3477b8504a38058 | 1,574 | cpp | C++ | native/Sparky-core/src/sp/app/Input.cpp | Itay2805/Sparky4j-core-3D | 0ac75c217c4d74c2fb8a9c226992ac6c4662718d | [
"Apache-2.0"
] | null | null | null | native/Sparky-core/src/sp/app/Input.cpp | Itay2805/Sparky4j-core-3D | 0ac75c217c4d74c2fb8a9c226992ac6c4662718d | [
"Apache-2.0"
] | null | null | null | native/Sparky-core/src/sp/app/Input.cpp | Itay2805/Sparky4j-core-3D | 0ac75c217c4d74c2fb8a9c226992ac6c4662718d | [
"Apache-2.0"
] | null | null | null | #include "sp/sp.h"
#include "Input.h"
namespace sp {
InputManager* Input::s_InputManager = nullptr;
InputManager::InputManager()
{
ClearKeys();
ClearMouseButtons();
m_MouseGrabbed = true;
Input::s_InputManager = this;
}
void InputManager::Update()
{
for (int i = 0; i < MAX_BUTTONS; i++)
m_MouseClicked[i] = m_MouseButtons[i] && !m_MouseState[i];
memcpy(m_LastKeyState, m_KeyState, MAX_KEYS);
memcpy(m_MouseState, m_MouseButtons, MAX_BUTTONS);
}
void InputManager::ClearKeys()
{
for (int i = 0; i < MAX_KEYS; i++)
{
m_KeyState[i] = false;
m_LastKeyState[i] = false;
}
m_KeyModifiers = 0;
}
void InputManager::ClearMouseButtons()
{
for (int i = 0; i < MAX_BUTTONS; i++)
{
m_MouseButtons[i] = false;
m_MouseState[i] = false;
m_MouseClicked[i] = false;
}
}
bool InputManager::IsKeyPressed(uint keycode) const
{
// TODO: Log this!
if (keycode >= MAX_KEYS)
return false;
return m_KeyState[keycode];
}
bool InputManager::IsMouseButtonPressed(uint button) const
{
// TODO: Log this!
if (button >= MAX_BUTTONS)
return false;
return m_MouseButtons[button];
}
bool InputManager::IsMouseButtonClicked(uint button) const
{
// TODO: Log this!
if (button >= MAX_BUTTONS)
return false;
return m_MouseClicked[button];
}
const maths::vec2& InputManager::GetMousePosition() const
{
return m_MousePosition;
}
const bool InputManager::IsMouseGrabbed() const
{
return m_MouseGrabbed;
}
void InputManager::SetMouseGrabbed(bool grabbed)
{
m_MouseGrabbed = grabbed;
}
} | 17.685393 | 61 | 0.680432 | Itay2805 |
6aef6a491cb032857999c179347498c293e0705b | 734 | hpp | C++ | ares/fc/fds/drive.hpp | moon-chilled/Ares | 909fb098c292f8336d0502dc677050312d8b5c81 | [
"0BSD"
] | 7 | 2020-07-25T11:44:39.000Z | 2021-01-29T13:21:31.000Z | ares/fc/fds/drive.hpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | null | null | null | ares/fc/fds/drive.hpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | 1 | 2021-03-22T16:15:30.000Z | 2021-03-22T16:15:30.000Z | struct FDSDrive {
auto clock() -> void;
auto change() -> void;
auto powerup() -> void;
auto rewind() -> void;
auto advance() -> void;
auto crc(uint8 data) -> void;
auto read() -> void;
auto write() -> void;
auto read(uint16 address, uint8 data) -> uint8;
auto write(uint16 address, uint8 data) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
uint1 enable;
uint1 power;
uint1 changing;
uint1 ready;
uint1 scan;
uint1 rewinding;
uint1 scanning;
uint1 reading; //0 = writing
uint1 writeCRC;
uint1 clearCRC;
uint1 irq;
uint1 pending;
uint1 available;
uint32 counter;
uint32 offset;
uint1 gap;
uint8 data;
uint1 completed;
uint16 crc16;
};
| 20.388889 | 49 | 0.640327 | moon-chilled |
6af4d646d3dd17f02a38d84f06fba84c3a9550ee | 12,441 | cpp | C++ | lib/test/AMRElliptic/testBiCGStab.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 10 | 2018-02-01T20:57:36.000Z | 2022-03-17T02:57:49.000Z | lib/test/AMRElliptic/testBiCGStab.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 19 | 2018-10-04T21:37:18.000Z | 2022-02-25T16:20:11.000Z | lib/test/AMRElliptic/testBiCGStab.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 11 | 2019-01-12T23:33:32.000Z | 2021-08-09T15:19:50.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include <iostream>
using std::endl;
#include "BRMeshRefine.H"
#include "LoadBalance.H"
#include "CH_HDF5.H"
#include "parstream.H"
#include "BoxIterator.H"
#include "FABView.H"
#include "NewPoissonOp.H"
#include "AMRPoissonOp.H"
#include "BCFunc.H"
#include "BiCGStabSolver.H"
#include "RelaxSolver.H"
#include "UsingNamespace.H"
/// Global variables for handling output:
static const char* pgmname = "testBiCGStab" ;
static const char* indent = " ";
static const char* indent2 = " " ;
static bool verbose = true ;
///
// Parse the standard test options (-v -q) out of the command line.
///
void
parseTestOptions( int argc ,char* argv[] )
{
for ( int i = 1 ; i < argc ; ++i )
{
if ( argv[i][0] == '-' ) //if it is an option
{
// compare 3 chars to differentiate -x from -xx
if ( strncmp( argv[i] ,"-v" ,3 ) == 0 )
{
verbose = true ;
// argv[i] = "" ;
}
else if ( strncmp( argv[i] ,"-q" ,3 ) == 0 )
{
verbose = false ;
// argv[i] = "" ;
}
}
}
return ;
}
// u = x*x + y*y + z*z
// du/dx = 2*x
// du/dy = 2*y
// du/dz = 2*z
// Laplace(u) = 2*CH_SPACEDIM
// #define __USE_GNU
// #include <fenv.h>
// #undef __USE_GNU
//static Box domain = Box(IntVect(D_DECL(-64,-64,-64)), IntVect(D_DECL(63,63,63)));
static Box domain = Box(IntVect(D_DECL(0,0,0)), IntVect(D_DECL(63,63,63)));
static Real dx = 0.0125;
static int blockingFactor = 8;
static Real xshift = 0.0;
int
testBiCGStab();
int
main(int argc ,char* argv[])
{
#ifdef CH_MPI
MPI_Init (&argc, &argv);
#endif
// int except = FE_DIVBYZERO | FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID ;
// feenableexcept(except);
parseTestOptions( argc ,argv ) ;
if ( verbose )
pout () << indent2 << "Beginning " << pgmname << " ..." << endl ;
int overallStatus = 0;
int status = testBiCGStab();
if ( status == 0 )
{
pout() << indent << pgmname << " passed." << endl ;
}
else
{
overallStatus = 1;
pout() << indent << pgmname << " failed with return code " << status << endl ;
}
xshift = 0.2;
blockingFactor = 4;
status = testBiCGStab();
if ( status == 0 )
{
pout() << indent << pgmname << " passed." << endl ;
}
else
{
overallStatus = 1;
pout() << indent << pgmname << " failed with return code " << status << endl ;
}
#ifdef CH_MPI
MPI_Finalize ();
#endif
return overallStatus;
}
extern "C"
{
void Parabola_neum(Real* pos,
int* dir,
Side::LoHiSide* side,
Real* a_values)
{
switch (*dir)
{
case 0:
a_values[0]=2.*(pos[0]-xshift);
return;
case 1:
a_values[0]=2.*pos[1];
return;
case 2:
a_values[0]=2.*pos[2];
return;
default:
MayDay::Error("no such dimension");
};
}
void Parabola_diri(Real* pos,
int* dir,
Side::LoHiSide* side,
Real* a_values)
{
a_values[0] = D_TERM((pos[0]-xshift)*(pos[0]-xshift),+pos[1]*pos[1],+pos[2]*pos[2]);
}
void DirParabolaBC(FArrayBox& a_state,
const Box& valid,
const ProblemDomain& a_domain,
Real a_dx,
bool a_homogeneous)
{
for (int i=0; i<CH_SPACEDIM; ++i)
{
DiriBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_diri,
i,
Side::Lo);
DiriBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_diri,
i,
Side::Hi);
}
}
void NeumParabolaBC(FArrayBox& a_state,
const ProblemDomain& a_domain,
Real a_dx,
bool a_homogeneous)
{
Box valid = a_state.box();
valid.grow(-1);
for (int i=0; i<CH_SPACEDIM; ++i)
{
NeumBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_neum,
i,
Side::Lo);
NeumBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_neum,
i,
Side::Hi);
}
}
}
static BCValueFunc pointFunc = Parabola_diri;
void parabola(const Box& box, int comps, FArrayBox& t)
{
RealVect pos;
Side::LoHiSide side;
int dir;
int num = 1;
ForAllXBNN(Real,t, box, 0, comps)
{
num=nR;
D_TERM(pos[0]=dx*(iR+0.5);, pos[1]=dx*(jR+0.5);, pos[2]=dx*(kR+0.5));
pointFunc(&(pos[0]), &dir, &side, &tR);
}EndFor;
}
void makeGrids(DisjointBoxLayout& a_dbl, const Box& a_domain)
{
BRMeshRefine br;
Box domain = a_domain;
domain.coarsen(blockingFactor);
domain.refine(blockingFactor);
CH_assert(domain == a_domain);
domain.coarsen(blockingFactor);
ProblemDomain junk(domain);
IntVectSet pnd(domain);
IntVectSet tags;
for (BoxIterator bit(domain); bit.ok(); ++bit)
{
const IntVect& iv = bit();
if (D_TERM(true, && iv[1]< 2*iv[0] && iv[1]>iv[0]/2, && iv[2] < domain.bigEnd(2)/2))
{
tags|=iv;
}
}
Vector<Box> boxes;
br.makeBoxes(boxes, tags, pnd, junk, 32/blockingFactor, 1);
Vector<int> procs;
LoadBalance(procs, boxes);
for (int i=0; i<boxes.size(); ++i) boxes[i].refine(blockingFactor);
a_dbl.define(boxes, procs);
}
struct setvalue
{
static Real val;
static void setFunc(const Box& box,
int comps, FArrayBox& t)
{
t.setVal(val);
}
};
Real setvalue::val = 0;
int
testBiCGStab()
{
ProblemDomain regularDomain(domain);
pout()<<"\n GSRB unigrid solver \n";
// GSRB single grid solver test
{
Box phiBox = domain;
phiBox.grow(1);
FArrayBox phi(phiBox, 1);
FArrayBox rhs(domain, 1);
FArrayBox error(domain, 1);
FArrayBox phi_exact(domain, 1);
FArrayBox residual(domain, 1);
FArrayBox correction(phiBox, 1);
phi.setVal(0.0);
correction.setVal(0.0);
rhs.setVal(2*CH_SPACEDIM);
parabola(domain, 1, phi_exact);
RealVect pos(IntVect::Unit);
pos*=dx;
NewPoissonOp op;
op.define(pos, regularDomain, DirParabolaBC);
for (int i=0; i<15; ++i)
{
op.residual(residual, phi, rhs);
Real rnorm = residual.norm();
op.preCond(correction, residual);
op.incr(phi, correction, 1.0);
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<"Residual L2 norm "<<rnorm<<" Error max norm = "
<<norm<<std::endl;
}
}
pout()<<"\n unigrid solver \n";
// single grid solver test
{
Box phiBox = domain;
phiBox.grow(1);
FArrayBox phi(phiBox, 1);
FArrayBox rhs(domain, 1);
FArrayBox error(domain, 1);
FArrayBox phi_exact(domain, 1);
FArrayBox residual(domain, 1);
FArrayBox correction(phiBox, 1);
phi.setVal(0.0);
rhs.setVal(2*CH_SPACEDIM);
parabola(domain, 1, phi_exact);
RealVect pos(IntVect::Unit);
pos*=dx;
NewPoissonOp op;
op.define(pos, regularDomain, DirParabolaBC);
BiCGStabSolver<FArrayBox> solver;
solver.define(&op, true);
int iter = 1;
pout()<< "homogeneous solver mode : solver.solve(correction, reisdual)\n"
<< "solver.i_max= "<<solver.m_imax<<" iter = "<<iter<<std::endl;
op.residual(residual, phi, rhs);
Real rnorm = residual.norm();
pout()<<"initial residual "<<rnorm<<"\n";
for (int i=0; i<iter; ++i)
{
correction.setVal(0.0);
solver.solve(correction, residual);
op.incr(phi, correction, 1);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<"residual L2 norm "<< rnorm
<<" Error max norm = "<<norm<<std::endl;
}
pout()<< "\n\n inhomogeneous solver mode : solver.solve(a_phi, a_rhs)\n"<<std::endl;
solver.setHomogeneous(false);
op.scale(phi, 0.0);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
pout()<<"initial residual "<<rnorm<<"\n";
for (int i=0; i<iter; ++i)
{
solver.solve(phi, rhs);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<" residual L2 norm "<< rnorm
<<" Error max norm = "<<norm<<std::endl;
}
}
pout()<<"\n level solver \n";
// Level solve
{
DisjointBoxLayout dbl;
makeGrids(dbl, domain);
dbl.close();
DataIterator dit(dbl);
LevelData<FArrayBox> phi(dbl, 1, IntVect::Unit);
LevelData<FArrayBox> correction(dbl, 1, IntVect::Unit);
LevelData<FArrayBox> phi_exact(dbl, 1);
LevelData<FArrayBox> error(dbl, 1);
LevelData<FArrayBox> rhs(dbl, 1);
LevelData<FArrayBox> residual(dbl, 1);
setvalue::val = 2*CH_SPACEDIM;
rhs.apply(setvalue::setFunc);
setvalue::val = 0;
phi.apply(setvalue::setFunc);
phi_exact.apply(parabola);
RealVect pos(IntVect::Unit);
pos*=dx;
AMRPoissonOp amrop;
amrop.define(dbl, pos[0], regularDomain, DirParabolaBC);
BiCGStabSolver<LevelData<FArrayBox> > bsolver;
RelaxSolver<LevelData<FArrayBox> > rsolver;
bsolver.define(&amrop, true);
rsolver.define(&amrop, true);
int iter = 1;
amrop.scale(phi, 0.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
Real rnorm = amrop.norm(residual, 2);
Real enorm = amrop.norm(error, 0);
pout()<< "homogeneous solver mode : solver.solve(correction, residual)\n"
<< "solver.i_max= "<<bsolver.m_imax<<" iter = "<<iter<<std::endl;
pout()<<"\nInitial residual norm "<<rnorm<<" Error max norm "<<enorm<<"\n\n";
pout()<<indent2<<"BiCGStab\n";
for (int i=0; i<iter; ++i)
{
amrop.scale(correction, 0.0);
bsolver.solve(correction, residual);
amrop.incr(phi, correction, 1.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"RelaxSolver\n";
for (int i=0; i<iter; ++i)
{
amrop.scale(correction, 0.0);
rsolver.solve(correction, residual);
amrop.incr(phi, correction, 1.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
pout()<< "\n\ninhomogeneous solver mode : solver.solve(phi, rhs)\n"
<< "solver.i_max= "<<bsolver.m_imax<<" iter = "<<iter<<std::endl;
bsolver.setHomogeneous(false);
rsolver.setHomogeneous(false);
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"BiCGStab\n";
for (int i=0; i<iter; ++i)
{
bsolver.solve(phi, rhs);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"RelaxSolver\n";
for (int i=0; i<iter; ++i)
{
rsolver.solve(phi, rhs);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
}
return 0;
}
| 25.441718 | 90 | 0.553332 | rmrsk |
6af57725a93cd086d95cfcecee83c8ba6d5d4478 | 434 | cpp | C++ | 03. Inheritance-Homework/Problem 01. Student System/schoolMember.cpp | Jorka7a13/SoftUni_CppProgramming | 3f7dcd5f5d1ce9bd38542911a476d57d8825aacd | [
"MIT"
] | null | null | null | 03. Inheritance-Homework/Problem 01. Student System/schoolMember.cpp | Jorka7a13/SoftUni_CppProgramming | 3f7dcd5f5d1ce9bd38542911a476d57d8825aacd | [
"MIT"
] | null | null | null | 03. Inheritance-Homework/Problem 01. Student System/schoolMember.cpp | Jorka7a13/SoftUni_CppProgramming | 3f7dcd5f5d1ce9bd38542911a476d57d8825aacd | [
"MIT"
] | null | null | null | #include "schoolMember.h"
SchoolMember::SchoolMember(unsigned short id, std::string name, std::string currentCourse)
: id_(id),
name_(name),
currentCourse_(currentCourse)
{}
SchoolMember::~SchoolMember()
{}
unsigned short SchoolMember::getId() const
{
return this->id_;
}
std::string SchoolMember::getName() const
{
return this->name_;
}
std::string SchoolMember::getCurrentCourse() const
{
return this->currentCourse_;
} | 17.36 | 90 | 0.739631 | Jorka7a13 |
6af62b453e66e057e9b1fef81df24a9388d64184 | 1,354 | cpp | C++ | nau/src/nau/render/opengl/glMaterialGroup.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 29 | 2015-09-16T22:28:30.000Z | 2022-03-11T02:57:36.000Z | nau/src/nau/render/opengl/glMaterialGroup.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 1 | 2017-03-29T13:32:58.000Z | 2017-03-31T13:56:03.000Z | nau/src/nau/render/opengl/glMaterialGroup.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 10 | 2015-10-15T14:20:15.000Z | 2022-02-17T10:37:29.000Z | #include "nau/render/opengl/glMaterialGroup.h"
#include "nau/render/opengl/glIndexArray.h"
#include "nau/render/opengl/glVertexArray.h"
#include <glbinding/gl/gl.h>
using namespace gl;
//#include <GL/glew.h>
using namespace nau::render::opengl;
GLMaterialGroup::GLMaterialGroup(IRenderable *parent, std::string materialName) :
MaterialGroup(parent, materialName),
m_VAO(0) {
}
GLMaterialGroup::~GLMaterialGroup() {
if (m_VAO)
glDeleteVertexArrays(1, &m_VAO);
}
void
GLMaterialGroup::compile() {
if (m_VAO)
return;
std::shared_ptr<VertexData> &v = m_Parent->getVertexData();
if (!v->isCompiled())
v->compile();
if (!m_IndexData->isCompiled())
m_IndexData->compile();
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
v->bind();
m_IndexData->bind();
glBindVertexArray(0);
v->unbind();
m_IndexData->unbind();
}
void
GLMaterialGroup::resetCompilationFlag() {
if (!m_VAO)
return;
glDeleteVertexArrays(1, &m_VAO);
m_VAO = 0;
std::shared_ptr<VertexData> &v = m_Parent->getVertexData();
v->resetCompilationFlag();
m_IndexData->resetCompilationFlag();
}
bool
GLMaterialGroup::isCompiled() {
return (m_VAO != 0);
}
void
GLMaterialGroup::bind() {
glBindVertexArray(m_VAO);
}
void
GLMaterialGroup::unbind() {
glBindVertexArray(0);
}
unsigned int
GLMaterialGroup::getVAO() {
return m_VAO;
} | 14.55914 | 81 | 0.711226 | Khirion |
6af7c42167ac543991c97671617ee685a88a0102 | 10,580 | cpp | C++ | src/Game.cpp | R3alCl0ud/CREST-Capstone-Project | 10f90404908e4f947c861adff901088b71d4d310 | [
"BSD-3-Clause"
] | null | null | null | src/Game.cpp | R3alCl0ud/CREST-Capstone-Project | 10f90404908e4f947c861adff901088b71d4d310 | [
"BSD-3-Clause"
] | null | null | null | src/Game.cpp | R3alCl0ud/CREST-Capstone-Project | 10f90404908e4f947c861adff901088b71d4d310 | [
"BSD-3-Clause"
] | null | null | null | #include "headers/Game.hpp"
#include <stdlib.h>
#include <algorithm>
#include <list>
#include <iostream>
#include <string>
#include <sstream>
namespace engine {
Game* Game::gGame = NULL;
engine::Level* Game::gLevel = NULL;
engine::GameObjectList Game::gObjects = engine::GameObjectList();
sf::Clock Game::gFrameClock = sf::Clock();
sf::Clock Game::gPhysicsClock = sf::Clock();
sf::Uint16 Game::gPixelMeters = 75;
Game::Game(const std::string title) {
mWindowTitle = title;
mWindow.create(sf::VideoMode(1920, 1080), mWindowTitle);
mWindow.setFramerateLimit(60);
mUpdateRate = 1.0f / 20.0f;
mPhysicsUpdateRate = 1.0f / 300000.0f;
mMaxUpdates = 5;
mMaxPhysicsUpdates = 5000;
gGame = this;
}
Game::~Game() {
// mWindowTitle.~string();
// gObjects.~GameObjectList();
// gFrameClock.~Clock();
// gPhysicsClock.~Clock();
gGame = NULL;
}
int Game::run(void) {
this->GameLoop();
return 0;
}
void Game::GameLoop(void) {
bool lc = false;
bool collision = false;
bool collisionDown = false;
bool collisionUp = false;
bool collisionRight = false;
bool collisionLeft = false;
sf::Event event;
sf::Clock anUpdateClock;
sf::Clock anPhysicsUpdateClock;
sf::Clock anSecondCounter;
anUpdateClock.restart();
anPhysicsUpdateClock.restart();
anSecondCounter.restart();
// When do we need to update next (in milliseconds)?
sf::Int32 anUpdateNext = anUpdateClock.getElapsedTime().asMilliseconds();
sf::Int32 anPhysicsUpdateNext = anPhysicsUpdateClock.getElapsedTime().asMilliseconds();
// game Stats
int FPS = 0;
sf::Uint32 frames = 0;
sf::Font textFont;
textFont.loadFromFile("src/fonts/arial.ttf");
sf::Text textPS("FPS: ", textFont);
// sf::Text textVel("Velocity: <0.0, 0.0>", textFont);
// sf::Text textPos("Position: (0.0, 0.0)", textFont);
textPS.setFont(textFont);
textPS.setCharacterSize(64);
textPS.setStyle(sf::Text::Bold);
textPS.setFillColor(sf::Color::White);
// textVel.setFont(textFont);
// textVel.setCharacterSize(64);
// textVel.setStyle(sf::Text::Bold);
// textVel.setFillColor(sf::Color::White);
// textPos.setFont(textFont);
// textPos.setCharacterSize(64);
// textPos.setStyle(sf::Text::Bold);
// textPos.setFillColor(sf::Color::White);
engine::RectangleCollider2D* rect2D = NULL;
engine::CircleCollider2D* circle2D = NULL;
engine::PolygonCollider2D* poly2D = NULL;
// run window loop
while (mWindow.isOpen()) {
mWindow.clear(); // sf::Color::Green
sf::Uint32 anUpdates = 0;
sf::Uint32 anPhysicsUpdates = 0;
while (mWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
mWindow.close();
} else if (event.type == sf::Event::KeyPressed) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
mWindow.close();
}
}
}
sf::Int32 anUpdateTime = anUpdateClock.getElapsedTime().asMilliseconds();
sf::Int32 anPhysicsUpdateTime = anPhysicsUpdateClock.getElapsedTime().asMilliseconds();
if (gLevel != NULL) {
GameObjectList gObjs = gLevel->getGameObjects();
if (!lc){
printf("Running all level things\n");
lc = true;
}
// run physics updates
while((anPhysicsUpdateTime - anPhysicsUpdateNext) >= mPhysicsUpdateRate && anPhysicsUpdates++ < mMaxPhysicsUpdates) {
gPhysicsClock.restart(); // reset clock before loop resets or ends
for (engine::GameObject* gm : gObjs) {
collision = false;
collisionDown = false;
collisionUp = false;
collisionRight = false;
collisionLeft = false;
rect2D = NULL;
circle2D = NULL;
poly2D = NULL;
if (gm->getCollider2D() != NULL) {
for (engine::GameObject* ogm : gObjs) {
if (gm == ogm || !ogm->getCollider2D()) continue;
if ((rect2D = dynamic_cast<engine::RectangleCollider2D*>(ogm->getCollider2D()))) collision = gm->getCollider2D()->intersects(rect2D);
else if ((circle2D = dynamic_cast<engine::CircleCollider2D*>(ogm->getCollider2D()))) collision = gm->getCollider2D()->intersects(circle2D);
else if ((poly2D = dynamic_cast<engine::PolygonCollider2D*>(ogm->getCollider2D()))) collision = gm->getCollider2D()->intersects(poly2D);
else collision = gm->getCollider2D()->intersects(ogm->getCollider2D());
collisionDown = collisionDown || (collision && gm->getPosition().y < ogm->getPosition().y);
collisionUp = (collision && gm->getPosition().y > ogm->getPosition().y);
collisionRight = (collision && !collisionDown && gm->getPosition().x < ogm->getPosition().x);
collisionLeft = (collision && !collisionDown && gm->getPosition().x > ogm->getPosition().x);
if (collision) {
gm->onCollision(ogm->getCollider2D());
if (rect2D) gm->onCollision(rect2D);
if (!gm->getCollider2D()->hasCollision(ogm->getCollider2D())) {
gm->onCollisionEnter(ogm->getCollider2D());
// if ()
gm->getCollider2D()->addCollision(ogm->getCollider2D());
}
} else if (!collision && gm->getCollider2D()->hasCollision(ogm->getCollider2D())) {
gm->onCollisionExit(ogm->getCollider2D());
gm->getCollider2D()->removeCollision(ogm->getCollider2D());
}
}
}
engine::Physics2D* p2d = gm->getPhysics();
sf::Vector2f velocity = p2d->getVelocity();
if (!collisionDown) {
if (p2d->hasGravity()) {
p2d->addForce(sf::Vector2f(0.0f, (G_C * 2 * DeltaPhysicsTime())));
}
velocity = p2d->getVelocity();
if (velocity.y > 0.0f) {
gm->move(0.0f, p2d->deltaV().y * gPixelMeters);
}
} else {
if (velocity.x > 0.0f) {
p2d->addForce(sf::Vector2f(-6 * (velocity.x) * DeltaPhysicsTime(), 0.0f)); // * DeltaPhysicsTime()
}
velocity = p2d->getVelocity();
if (velocity.x < 0.0f) {
p2d->addForce(sf::Vector2f(-6 * (velocity.x) * DeltaPhysicsTime(), 0.0f)); // * DeltaPhysicsTime()
}
}
velocity = p2d->getVelocity();
if (!collisionUp && velocity.y < 0) {
gm->move(0.0f, p2d->deltaV().y * gPixelMeters);
}
if (!collisionRight && velocity.x > 0) {
gm->move(p2d->deltaV().x * gPixelMeters, 0.0f);
}
if (!collisionLeft && velocity.x < 0) {
gm->move(p2d->deltaV().x * gPixelMeters, 0.0f);
}
velocity = p2d->getVelocity();
if (collisionDown && velocity.y > 0.0f) {
// gm->move(0.0f, p2d->deltaV().y * -gPixelMeters);
// printf("reseting vertical velocity\n");
p2d->addForce(sf::Vector2f(0, -1 * velocity.y));
}
velocity = p2d->getVelocity();
if (collisionUp && velocity.y < 0.0f){
p2d->addForce(sf::Vector2f(0, -1 * velocity.y));
}
velocity = p2d->getVelocity();
if (collisionRight && velocity.x > 0.0f && !collisionDown && !collisionUp) {
printf("reseting horizontal velocity\n");
p2d->addForce(sf::Vector2f(-1 * velocity.x, 0));
}
velocity = p2d->getVelocity();
if (collisionLeft && velocity.x < 0.0f && !collisionDown && !collisionUp) {
printf("reseting horizontal velocity\n");
p2d->addForce(sf::Vector2f(-1 * velocity.x, 0));
}
}
}
// printf("P2d Updates: %d\n", anPhysicsUpdates);
// run fixed updates
while((anUpdateTime - anUpdateNext) >= mUpdateRate && anUpdates++ < mMaxUpdates) {
for (engine::GameObject* gm : gObjs) {
// printf("Fixed Updating GM\n");
gm->fixedUpdate();
}
anUpdateNext += mUpdateRate;
}
for (engine::GameObject* gm : gObjs) {
// printf("Updating gameobject\n");
gm->update();
// printf("Updating gm drawable positions\n");
gm->sprite.setPosition(gm->getPosition());
gm->shape.setPosition(gm->getPosition());
// printf("Drawing gameobject\n");
gm->draw(mWindow);
}
}
if (anSecondCounter.getElapsedTime().asSeconds() > 0.25f) {
// printf("Velocity<%f, %f>\n", p2d->getVelocity().x, p2d->getVelocity().y);
// printf("FPS: %d, DeltaTime: %f\n", , DeltaTime());
// printf("Physics speed: %f\n", DeltaPhysicsTime() * 205000);
FPS = frames * 4;
anSecondCounter.restart();
frames = 0;
}
if (FPS == 0) FPS = 1.0f / DeltaTime();
std::ostringstream tframes;
tframes.precision(2);
tframes.width(7);
tframes << "FPS: " << std::fixed << FPS;
textPS.setString(tframes.str());
// textVel.setString("Velocity: <" + ());
textPS.setPosition(mWindow.getView().getCenter() - sf::Vector2f(970, 500));
// textVel.setPosition(mWindow.getView().getCenter() - sf::Vector2f(940, 430));
// textPos.setPosition(mWindow.getView().getCenter() - sf::Vector2f(940, 360));
mWindow.draw(textPS);
// mWindow.draw(textVel);
// mWindow.draw(textPos);
mWindow.display();
gFrameClock.restart(); // reset FrameClock as the last frame has just been drawn
frames+=1;
}
}
void Game::RunPhysicsUpdates(void) {
}
float Game::DeltaTime(void) {
return gFrameClock.getElapsedTime().asSeconds();
}
float Game::DeltaPhysicsTime(void) {
//return gPhysicsClock.getElapsedTime().asSeconds();//.asMilliseconds() / 1000.0f;
return gGame->mPhysicsUpdateRate;
}
sf::Uint16 Game::GetPixelMeters(void) {
return gPixelMeters;
}
engine::Level* Game::GetLevel(void) {
return gLevel;
}
Game* Game::GetGame(void) {
return gGame;
}
GameObjectList Game::GetGameObjects(void) {
return gObjects;
}
void Game::SetLevel(engine::Level* level) {
gLevel = level;
// gObjects = level->getGameObjects();
}
}
| 37.385159 | 155 | 0.568336 | R3alCl0ud |
1390f4a6b8e5901176235d44262abf445294de8a | 466 | cc | C++ | src/strings.cc | maxidea1024/simple-lexer | ba3cd91a6a9cdd77aa52bc0965553aa7858c8827 | [
"MIT"
] | null | null | null | src/strings.cc | maxidea1024/simple-lexer | ba3cd91a6a9cdd77aa52bc0965553aa7858c8827 | [
"MIT"
] | null | null | null | src/strings.cc | maxidea1024/simple-lexer | ba3cd91a6a9cdd77aa52bc0965553aa7858c8827 | [
"MIT"
] | null | null | null | #include "strings.h"
std::vector<std::string> Strings::registry_;
const char* Strings::Add(const char* str) { return Add(str, strlen(str)); }
const char* Strings::Add(const char* str, size_t length) {
for (auto& s : registry_) {
if (s.length() == length) {
if (memcmp(s.c_str(), str, length) == 0) {
return s.c_str();
}
}
}
std::string new_str(str, length);
registry_.push_back(new_str);
return registry_.back().c_str();
}
| 22.190476 | 75 | 0.613734 | maxidea1024 |
1391ad0b167b21189b455fa117e579f004a98df5 | 1,939 | cc | C++ | Core/DianYing/Source/Builtin/Shader/RenderPass.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | 4 | 2019-03-17T19:46:54.000Z | 2019-12-09T20:11:01.000Z | Core/DianYing/Source/Builtin/Shader/RenderPass.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | Core/DianYing/Source/Builtin/Shader/RenderPass.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | #include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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.
///
/// Header file
#include <Dy/Builtin/ShaderGl/RenderPass.h>
namespace
{
constexpr std::string_view vertexShaderCode = R"dy(
#version 430 core
// Quad
layout (location = 0) in vec3 dyPosition;
layout (location = 1) in vec2 dyTexCoord0;
out gl_PerVertex { vec4 gl_Position; };
out VS_OUT { vec2 texCoord; } vs_out;
void main() {
vs_out.texCoord = dyTexCoord0;
gl_Position = vec4(dyPosition, 1.0);
}
)dy";
constexpr std::string_view fragmentShaderCode = R"dy(
#version 430
in VS_OUT { vec2 texCoord; } fs_in;
layout (location = 0) out vec4 outColor;
uniform sampler2D uUnlit;
uniform sampler2D uNormal;
uniform sampler2D uSpecular;
uniform sampler2D uViewPosition;
vec3 dirLight = normalize(vec3(-1, 1, 0));
vec3 ambientColor = vec3(1);
void main() {
vec4 normalValue = (texture(uNormal, fs_in.texCoord) - 0.5f) * 2.0f;
vec4 unlitValue = texture(uUnlit, fs_in.texCoord);
float ambientFactor = 0.1f;
float diffuseFactor = max(dot(normalValue.xyz, dirLight), 0.1);
outColor = vec4(
vec3(1) * diffuseFactor +
ambientColor * ambientFactor,
1.0f);
}
)dy";
} /// ::unnamed namespace
namespace dy::builtin
{
FDyBuiltinShaderGLRenderPass::FDyBuiltinShaderGLRenderPass()
{
this->mSpecifierName = sName;
this->mVertexBuffer = vertexShaderCode;
this->mPixelBuffer = fragmentShaderCode;
}
} /// ::dy::builtin namespace | 24.858974 | 81 | 0.7246 | liliilli |
1398f14647089bd2313b867b4146e186a072a2b7 | 8,305 | cpp | C++ | windows/pw6e.official/CPlusPlus/Chapter17/PrintableTomKitten/PrintableTomKitten/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:18:08.000Z | 2016-11-23T08:18:08.000Z | windows/pw6e.official/CPlusPlus/Chapter17/PrintableTomKitten/PrintableTomKitten/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | null | null | null | windows/pw6e.official/CPlusPlus/Chapter17/PrintableTomKitten/PrintableTomKitten/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:17:34.000Z | 2016-11-23T08:17:34.000Z | //
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
using namespace PrintableTomKitten;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Printing;
using namespace Windows::Graphics::Printing::OptionDetails;
using namespace Windows::UI;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Printing;
MainPage::MainPage()
{
InitializeComponent();
std::array<UIElement^, 57> bookPagesInitialized =
{
ref new TomKitten03(), ref new TomKitten04(), ref new TomKitten05(), ref new TomKitten06(),
ref new TomKitten07(), ref new TomKitten08(), ref new TomKitten09(), ref new TomKitten10(),
ref new TomKitten11(), ref new TomKitten12(), ref new TomKitten13(), ref new TomKitten14(),
ref new TomKitten15(), ref new TomKitten16(), ref new TomKitten17(), ref new TomKitten18(),
ref new TomKitten19(), ref new TomKitten20(), ref new TomKitten21(), ref new TomKitten22(),
ref new TomKitten23(), ref new TomKitten24(), ref new TomKitten25(), ref new TomKitten26(),
ref new TomKitten27(), ref new TomKitten28(), ref new TomKitten29(), ref new TomKitten30(),
ref new TomKitten31(), ref new TomKitten32(), ref new TomKitten33(), ref new TomKitten34(),
ref new TomKitten35(), ref new TomKitten36(), ref new TomKitten37(), ref new TomKitten38(),
ref new TomKitten39(), ref new TomKitten40(), ref new TomKitten41(), ref new TomKitten42(),
ref new TomKitten43(), ref new TomKitten44(), ref new TomKitten45(), ref new TomKitten46(),
ref new TomKitten47(), ref new TomKitten48(), ref new TomKitten49(), ref new TomKitten50(),
ref new TomKitten51(), ref new TomKitten52(), ref new TomKitten53(), ref new TomKitten54(),
ref new TomKitten55(), ref new TomKitten56(), ref new TomKitten57(), ref new TomKitten58(),
ref new TomKitten59()
};
bookPages = bookPagesInitialized;
// Create PrintDocument and attach handlers
printDocument = ref new PrintDocument();
printDocumentSource = printDocument->DocumentSource;
printDocument->Paginate += ref new PaginateEventHandler(this, &MainPage::OnPrintDocumentPaginate);
printDocument->GetPreviewPage += ref new GetPreviewPageEventHandler(this, &MainPage::OnPrintDocumentGetPreviewPage);
printDocument->AddPages += ref new AddPagesEventHandler(this, &MainPage::OnPrintDocumentAddPages);
}
void MainPage::OnNavigatedTo(NavigationEventArgs^ args)
{
// Attach PrintManager handler
PrintManager^ printManager = PrintManager::GetForCurrentView();
printTaskRequestedEventToken = printManager->PrintTaskRequested += ref new TypedEventHandler<PrintManager^, PrintTaskRequestedEventArgs^>(this, &MainPage::OnPrintManagerPrintTaskRequested);
}
void MainPage::OnNavigatedFrom(NavigationEventArgs^ args)
{
// Detach PrintManager handler
PrintManager::GetForCurrentView()->PrintTaskRequested -= printTaskRequestedEventToken;
}
void MainPage::OnPrintManagerPrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ args)
{
PrintTask^ printTask = args->Request->CreatePrintTask("Hello Printer",
ref new PrintTaskSourceRequestedHandler(this, &MainPage::OnPrintTaskSourceRequested));
// Get PrintTaskOptionDetails for making changing to options
PrintTaskOptionDetails^ optionDetails = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTask->Options);
// Create the custom item
PrintCustomItemListOptionDetails^ pageRange = optionDetails->CreateItemListOption("idPrintRange", "Print range");
pageRange->AddItem("idPrintAll", "Print all pages");
pageRange->AddItem("idPrintCustom", "Print custom range");
// Add it to the options
optionDetails->DisplayedOptions->Append("idPrintRange");
// Create a page-range edit item also, but this only
// comes into play when user select "Print custom range"
optionDetails->CreateTextOption("idCustomRangeEdit", "Custom Range");
// Set a handler for the OptionChanged event
optionDetails->OptionChanged += ref new TypedEventHandler<PrintTaskOptionDetails^, PrintTaskOptionChangedEventArgs^>(this, &MainPage::OnOptionDetailsOptionChanged);
}
void MainPage::OnPrintTaskSourceRequested(PrintTaskSourceRequestedArgs^ args)
{
args->SetSource(printDocumentSource);
}
void MainPage::OnOptionDetailsOptionChanged(PrintTaskOptionDetails^ sender, PrintTaskOptionChangedEventArgs^ args)
{
if (args->OptionId == nullptr)
return;
String^ optionId = dynamic_cast<String^>(args->OptionId);
String^ strValue = sender->Options->Lookup(optionId)->Value->ToString();
String^ errorText = "";
if (optionId == "idPrintRange")
{
if (strValue == "idPrintAll")
{
unsigned int index = 0;
if (sender->DisplayedOptions->IndexOf("idCustomRangeEdit", &index))
sender->DisplayedOptions->RemoveAt(index);
}
else if (strValue == "idPrintCustom")
{
sender->DisplayedOptions->Append("idCustomRangeEdit");
}
}
else if (optionId == "idCustomRangeEdit")
{
// Check to see if CustomPageRange accepts this
CustomPageRange^ pageRange = ref new CustomPageRange(strValue, bookPages.size());
if (!pageRange->IsValid)
{
errorText = "Use the form 2-4, 7, 9-11";
}
}
sender->Options->Lookup(optionId)->ErrorText = errorText;
// If there's no error, then invalidate the preview
if (errorText == "")
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler(
[this]()
{
printDocument->InvalidatePreview();
}));
}
}
void MainPage::OnPrintDocumentPaginate(Object^ sender, PaginateEventArgs^ args)
{
// Obtain the print range option
PrintTaskOptionDetails^ optionDetails = PrintTaskOptionDetails::GetFromPrintTaskOptions(args->PrintTaskOptions);
String^ strValue = dynamic_cast<String^>(optionDetails->Options->Lookup("idPrintRange")->Value);
if (strValue == "idPrintCustom")
{
// Parse the print range for GetPreviewPage and AddPages
String^ strPageRange = dynamic_cast<String^>(optionDetails->Options->Lookup("idCustomRangeEdit")->Value);
customPageRange = ref new CustomPageRange(strPageRange, bookPages.size());
}
else
{
// Make sure field is null if printing all pages
customPageRange = nullptr;
}
int pageCount = bookPages.size();
if (customPageRange != nullptr && customPageRange->IsValid)
pageCount = customPageRange->PageMapping->Size;
printDocument->SetPreviewPageCount(pageCount, PreviewPageCountType::Final);
}
void MainPage::OnPrintDocumentGetPreviewPage(Object^ sender, GetPreviewPageEventArgs^ args)
{
int oneBasedIndex = args->PageNumber;
if (customPageRange != nullptr && customPageRange->IsValid)
oneBasedIndex = customPageRange->PageMapping->GetAt(args->PageNumber - 1);
printDocument->SetPreviewPage(args->PageNumber, bookPages[oneBasedIndex - 1]);
}
void MainPage::OnPrintDocumentAddPages(Object^ sender, AddPagesEventArgs^ args)
{
if (customPageRange != nullptr && customPageRange->IsValid)
{
for (unsigned int index = 0; index < customPageRange->PageMapping->Size; index++)
printDocument->AddPage(bookPages[customPageRange->PageMapping->GetAt(index) - 1]);
}
else
{
for (unsigned int index = 0; index < bookPages.size(); index++)
printDocument->AddPage(bookPages[index]);
}
printDocument->AddPagesComplete();
}
| 41.944444 | 194 | 0.692354 | nnaabbcc |
13994026e8d8e3067ba572c5770893178c5d84a2 | 3,886 | cpp | C++ | Model/BCorner2DInteraction.cpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | Model/BCorner2DInteraction.cpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | Model/BCorner2DInteraction.cpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////
// //
// Copyright (c) 2003-2017 by The University of Queensland //
// Centre for Geoscience Computing //
// http://earth.uq.edu.au/centre-geoscience-computing //
// //
// Primary Business: Brisbane, Queensland, Australia //
// Licensed under the Open Software License version 3.0 //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
/////////////////////////////////////////////////////////////
#include "BCorner2DInteraction.h"
// -- Project includes --
#include "Foundation/vec3.h"
#include "tml/message/packed_message_interface.h"
#include "console.h"
/*!
default constructor
*/
BCorner2DInteraction::BCorner2DInteraction()
{
m_p=NULL;
m_corner=NULL;
m_pid=-1;
m_cid=-1;
}
/*!
constructor with parameters
\param p a pointer to the particle
\param c a pointer to the corner
\param param the interaction parameters
\param iflag
*/
BCorner2DInteraction::BCorner2DInteraction(CParticle* p,Corner2D* c,BMesh2DIP param,bool iflag)
{
m_p=p;
m_corner=c;
m_k=param.k;
m_break=param.brk*m_p->getRad();
// setup anchor point coefficients
int m_ne=m_corner->getNEdges();
if (m_ne==1){ // single edge case
console.Critical() << "Signle Edge Case not implemented\n";
} else if (m_ne==2){ // two edge (normal) case
Vec3 n1=m_corner->getEdgeNormal(1);
Vec3 n2=m_corner->getEdgeNormal(2);
Vec3 p=m_p->getPos()-m_corner->getPos();
k1=(n2.Y()*p.X()-n2.X()*p.Y())/(n1.X()*n2.Y()-n1.Y()*n2.X());
k2=(n1.Y()*p.X()-n1.X()*p.Y())/(n2.X()*n1.Y()-n2.Y()*n1.X());
// check
Vec3 check=k1*n1+k2*n2;
console.XDebug() << "BCorner2DInteraction check: " << check-p << "\n";
// cout << "BCorner2DInteraction check: n1,n2,p,k1,k2 [" << n1 << "] [" << n2 << "] [" << p << "] , " << k1 << " , " << k2 << " [" << check-p<< "]\n";
} else {
console.Critical() << "ERROR: Corner appears to have 0 Edges\n";
}
m_dist=0.0; // inital distance is always 0.0 !
m_pid=m_p->getID();
m_cid=m_corner->getID();
}
/*!
calculate & apply forces
*/
void BCorner2DInteraction::calcForces()
{
// get number of adjacent edges
int m_ne=m_corner->getNEdges();
// transform anchor point to world coords
Vec3 ap_global;
if(m_ne==1){
} else if (m_ne==2){
ap_global=m_corner->getPos()+k1*m_corner->getEdgeNormal(1)+k2*m_corner->getEdgeNormal(2);
}
// get dist between anchor and particle
const Vec3 D=ap_global-m_p->getPos();
m_dist=sqrt(D*D);
// calc force
Vec3 force=D*m_k;
Vec3 pos=m_p->getPos();
// apply force
m_p->applyForce(force,pos);
if(m_ne==1){
} else if (m_ne==2){
Vec3 hf=force*(-0.5);
m_corner->applyForceToEdge(1,hf);
m_corner->applyForceToEdge(2,hf);
}
}
/*!
return if the interaction is broken, i.e. the distance between
particle and anchor point exceeds breaking distance, i.e. relative
breaking distance x particle readius
*/
bool BCorner2DInteraction::broken()
{
return (m_dist>m_break);
}
/*!
Pack a BCorner2DInteraction into a TML packed message
\param I the interaction
*/
template<>
void TML_PackedMessageInterface::pack<BCorner2DInteraction>(const BCorner2DInteraction& I)
{
append(I.m_k);
append(I.m_dist);
append(I.m_break);
append(I.k1);
append(I.k2);
append(I.getCid());
append(I.getPid());
}
/*!
Unpack a BCorner2DInteraction from a TML packed message
\param I the interaction
*/
template<>
void TML_PackedMessageInterface::unpack<BCorner2DInteraction>(BCorner2DInteraction& I)
{
I.m_k=pop_double();
I.m_dist=pop_double();
I.m_break=pop_double();
I.k1=pop_double();
I.k2=pop_double();
I.m_cid=pop_int();
I.m_pid=pop_int();
}
| 27.560284 | 155 | 0.602419 | danielfrascarelli |
139a2f4bc394bfb31a2f5d8fe83bfe6872ae445f | 12,124 | cc | C++ | src/theia/io/read_calibration.cc | urbste/pyTheiaSfM | 814034c96b602fef1dc76ae6692278d61179ebcc | [
"BSD-3-Clause"
] | 3 | 2021-11-10T19:50:36.000Z | 2022-03-03T08:16:54.000Z | src/theia/io/read_calibration.cc | urbste/TheiaSfM | a92fa27e90b6182e2a2511a46d24283afad1a995 | [
"BSD-3-Clause"
] | null | null | null | src/theia/io/read_calibration.cc | urbste/TheiaSfM | a92fa27e90b6182e2a2511a46d24283afad1a995 | [
"BSD-3-Clause"
] | 2 | 2020-03-20T03:06:55.000Z | 2021-08-04T08:08:52.000Z | // Copyright (C) 2019 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Victor Fragoso (victor.fragoso@mail.wvu.edu)
#include "theia/io/read_calibration.h"
#include <glog/logging.h>
#include <stdio.h>
#include <string>
#include <unordered_map>
#include <vector>
#include <cereal/external/rapidjson/document.h>
#include <stlplus3/file_system.hpp>
#include "theia/sfm/camera/camera_intrinsics_model_type.h"
#include "theia/sfm/camera_intrinsics_prior.h"
namespace theia {
namespace {
static const char* kPinholeType = "PINHOLE";
static const char* kPriorsEntry = "priors";
static const char* kCameraIntrinsicsPrior = "CameraIntrinsicsPrior";
static const char* kImageName = "image_name";
static const char* kCameraType = "camera_intrinsics_type";
// Pinhole camera parameters.
static const char* kFocalLength = "focal_length";
static const char* kImageWidth = "width";
static const char* kImageHeight = "height";
static const char* kPrincipalPoint = "principal_point";
static const char* kAspectRatio = "aspect_ratio";
static const char* kSkew = "skew";
static const char* kRadialDistortionCoeffs = "radial_distortion_coeffs";
static const char* kTangentialDistortionCoeffs = "tangential_distortion_coeffs";
static const char* kPosition = "position";
static const char* kOrientation = "orientation";
static const char* kLatitude = "latitude";
static const char* kLongitude = "longitude";
static const char* kAltitude = "altitude";
bool ExtractPriorParameters(const cereal::rapidjson::Value& entry,
CameraIntrinsicsPrior* prior) {
// Get the focal length.
if (entry.HasMember(kFocalLength)) {
prior->focal_length.is_set = true;
prior->focal_length.value[0] = entry[kFocalLength].GetDouble();
}
// Get the principal points.
if (entry.HasMember(kPrincipalPoint) && entry[kPrincipalPoint].IsArray()) {
const int num_entries =
std::min(static_cast<int>(entry[kPrincipalPoint].Size()), 2);
bool all_doubles = true;
for (int i = 0; i < num_entries; ++i) {
bool is_double = entry[kPrincipalPoint][i].IsDouble() ||
entry[kPrincipalPoint][i].IsInt();
if (is_double) {
prior->principal_point.value[i] = entry[kPrincipalPoint][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->principal_point.is_set =
!entry[kPrincipalPoint].Empty() && all_doubles;
if (prior->principal_point.is_set) {
prior->image_width =
static_cast<int>(2 * prior->principal_point.value[0]);
prior->image_height =
static_cast<int>(2 * prior->principal_point.value[1]);
}
}
// Get the camera intrincisc type.
if (entry.HasMember(kCameraType) && entry[kCameraType].IsString()) {
std::string model_type_str = entry[kCameraType].GetString();
if (IsCameraIntrinsicsModelTypeValid(model_type_str)) {
prior->camera_intrinsics_model_type = std::move(model_type_str);
} else {
LOG(WARNING) << "Could not identify camera intrinsics model type: "
<< model_type_str;
}
}
// Get width.
if (entry.HasMember(kImageWidth) && entry[kImageWidth].IsInt()) {
prior->image_width = entry[kImageWidth].GetInt();
}
// Get height.
if (entry.HasMember(kImageHeight) && entry[kImageHeight].IsInt()) {
prior->image_height = entry[kImageHeight].GetInt();
}
// Get aspect ratio.
if (entry.HasMember(kAspectRatio) &&
(entry[kAspectRatio].IsDouble() || entry[kAspectRatio].IsInt())) {
prior->aspect_ratio.is_set = true;
prior->aspect_ratio.value[0] = entry[kAspectRatio].GetDouble();
}
// Get skew.
if (entry.HasMember(kSkew) &&
(entry[kSkew].IsDouble() || entry[kSkew].IsInt())) {
prior->skew.is_set = true;
prior->skew.value[0] = entry[kSkew].GetDouble();
}
// Get radial distortion coeffs.
if (entry.HasMember(kRadialDistortionCoeffs) &&
entry[kRadialDistortionCoeffs].IsArray()) {
const int num_dist_coeffs =
std::min(static_cast<int>(entry[kRadialDistortionCoeffs].Size()), 4);
bool all_doubles = true;
for (int i = 0; i < num_dist_coeffs; ++i) {
bool is_double = entry[kRadialDistortionCoeffs][i].IsDouble() ||
entry[kRadialDistortionCoeffs][i].IsInt();
if (is_double) {
prior->radial_distortion.value[i] =
entry[kRadialDistortionCoeffs][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->radial_distortion.is_set =
!entry[kRadialDistortionCoeffs].Empty() && all_doubles;
}
// Get tangential distortion coeffs.
if (entry.HasMember(kTangentialDistortionCoeffs) &&
entry[kTangentialDistortionCoeffs].IsArray()) {
const int num_dist_coeffs = std::min(
static_cast<int>(entry[kTangentialDistortionCoeffs].Size()), 2);
bool all_doubles = true;
for (int i = 0; i < num_dist_coeffs; ++i) {
bool is_double = entry[kTangentialDistortionCoeffs][i].IsDouble() ||
entry[kTangentialDistortionCoeffs][i].IsInt();
if (is_double) {
prior->tangential_distortion.value[i] =
entry[kTangentialDistortionCoeffs][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->tangential_distortion.is_set =
!entry[kTangentialDistortionCoeffs].Empty() && all_doubles;
}
// Get position.
if (entry.HasMember(kPosition) && entry[kPosition].IsArray()) {
const int num_entries =
std::min(static_cast<int>(entry[kPosition].Size()), 3);
bool all_doubles = true;
for (int i = 0; i < num_entries; ++i) {
bool is_double =
entry[kPosition][i].IsDouble() || entry[kPosition][i].IsInt();
if (is_double) {
prior->position.value[i] = entry[kPosition][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->position.is_set = !entry[kPosition].Empty() && all_doubles;
}
// Get orientation using Angle-Axis.
if (entry.HasMember(kOrientation) && entry[kOrientation].IsArray()) {
const int num_entries =
std::min(static_cast<int>(entry[kOrientation].Size()), 3);
bool all_doubles = true;
for (int i = 0; i < num_entries; ++i) {
bool is_double =
entry[kOrientation][i].IsDouble() || entry[kOrientation][i].IsInt();
if (is_double) {
prior->orientation.value[i] = entry[kOrientation][i].GetDouble();
}
all_doubles = all_doubles && is_double;
}
prior->orientation.is_set = !entry[kOrientation].Empty() && all_doubles;
}
// Get GPS priors.
if (entry.HasMember(kLatitude) &&
(entry[kLatitude].IsDouble() || entry[kLatitude].IsInt())) {
prior->latitude.value[0] = entry[kLatitude].GetDouble();
prior->latitude.is_set = true;
}
if (entry.HasMember(kLongitude) &&
(entry[kLongitude].IsDouble() || entry[kLongitude].IsInt())) {
prior->longitude.value[0] = entry[kLongitude].GetDouble();
prior->longitude.is_set = true;
}
if (entry.HasMember(kAltitude) &&
(entry[kAltitude].IsDouble() || entry[kAltitude].IsInt())) {
prior->altitude.value[0] = entry[kAltitude].GetDouble();
prior->altitude.is_set = true;
}
return true;
}
bool ExtractCameraIntrinsicsPrior(const cereal::rapidjson::Value& entry,
std::string* view_name,
CameraIntrinsicsPrior* prior) {
// Get the view name.
if (!entry.HasMember(kImageName)) {
LOG(ERROR) << "Could not find the image name.";
return false;
}
*view_name = entry[kImageName].GetString();
VLOG(3) << "Loading camera intrinsics prior for image name: " << *view_name;
// Get the camera type.
std::string camera_type_str;
if (!entry.HasMember(kCameraType)) {
LOG(WARNING) << "Unknown camera for view: " << *view_name
<< ". Setting to PINHOLE.";
camera_type_str = kPinholeType;
} else {
camera_type_str = entry[kCameraType].GetString();
VLOG(3) << "Camera type: [" << camera_type_str << "]";
}
// Get the camera type. This will verify if that the camera type is valid.
StringToCameraIntrinsicsModelType(camera_type_str);
ExtractPriorParameters(entry, prior);
return true;
}
} // namespace
bool ExtractCameraIntrinsicPriorsFromJson(
const char* json_str,
std::unordered_map<std::string, CameraIntrinsicsPrior>* view_to_priors) {
using cereal::rapidjson::Document;
using cereal::rapidjson::SizeType;
using cereal::rapidjson::Value;
Document json;
json.Parse(json_str);
if (!json.HasMember(kPriorsEntry) || !json[kPriorsEntry].IsArray()) {
LOG(ERROR) << "Expected \"priors\" array entry in JSON.";
return false;
}
const Value& entries = json[kPriorsEntry];
std::string view_name;
for (SizeType i = 0; i < entries.Size(); ++i) {
CameraIntrinsicsPrior prior;
if (!entries[i].HasMember(kCameraIntrinsicsPrior) ||
!ExtractCameraIntrinsicsPrior(
entries[i][kCameraIntrinsicsPrior], &view_name, &prior)) {
LOG(WARNING) << "Could not parse entry at position: " << i;
continue;
}
// Add to the map.
(*view_to_priors)[view_name] = prior;
}
return true;
}
bool ReadCalibration(const std::string& calibration_file,
std::unordered_map<std::string, CameraIntrinsicsPrior>*
camera_intrinsics_priors) {
// Get the size of the file.
const size_t buffer_size = stlplus::file_size(calibration_file);
// Allocate a buffer
std::vector<char> file_buffer(buffer_size, 0);
// Open and read the whole file.
FILE* file = fopen(calibration_file.c_str(), "rb");
if (file == nullptr) {
LOG(ERROR) << "Cannot read file: " << calibration_file;
return false;
}
// Read the whole file.
CHECK_EQ(fread(file_buffer.data(), sizeof(file_buffer[0]), buffer_size, file),
buffer_size);
fclose(file);
// Remove spurious chars after the closing curly brace.
std::string file_content(file_buffer.begin(), file_buffer.end());
const size_t last_curly_idx = file_content.rfind('}');
if (last_curly_idx == std::string::npos) {
LOG(ERROR) << "Could not fid a proper JSON file: " << calibration_file;
return false;
}
file_content.resize(last_curly_idx + 1);
const bool json_parsed = ExtractCameraIntrinsicPriorsFromJson(
file_content.c_str(), camera_intrinsics_priors);
return json_parsed;
}
} // namespace theia
| 36.299401 | 80 | 0.677664 | urbste |
139acc720aefcfdcb96eacaabf95f02ae9559e2c | 30,183 | cpp | C++ | src/clrefl/Generator.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | 578 | 2019-05-04T09:09:42.000Z | 2022-03-27T23:02:21.000Z | src/clrefl/Generator.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | 14 | 2019-05-11T14:34:56.000Z | 2021-02-02T07:06:46.000Z | src/clrefl/Generator.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | 42 | 2019-05-11T16:04:19.000Z | 2022-01-24T02:21:43.000Z | #include <clrefl/Generator.h>
#include <clrefl/Codegen.h>
#include <infra/ToString.h>
#include <stl/vector.hpp>
#include <stl/unordered_map.hpp>
#include <stl/unordered_set.hpp>
#include <json11.hpp>
#include <cctype>
#define RESOLVE_TEMPLATES 1
#define DEBUG_CLANG_ARGS 0
namespace two
{
using Json = json11::Json;
struct TopoSort
{
vector<vector<size_t>> links;
vector<bool> perm_marks;
vector<bool> temp_marks;
vector<size_t> order;
vector<size_t> sorted;
};
auto visit_sort_topological(TopoSort& sort, size_t n) //, T& elem)
{
if(sort.perm_marks[n]) return;
if(sort.temp_marks[n]) return;
sort.temp_marks[n] = true;
for (size_t c : sort.links[n])
{
visit_sort_topological(sort, c);
}
sort.perm_marks[n] = true;
sort.order[n] = sort.sorted.size();
sort.sorted.push_back(n);
};
TopoSort sort_topological(vector<vector<size_t>> links)
{
TopoSort sort;
sort.links = links;
sort.perm_marks.resize(links.size(), false);
sort.temp_marks.resize(links.size(), false);
sort.order.resize(links.size());
for(size_t n = 0; n < links.size(); ++n)
{
visit_sort_topological(sort, n);
}
return sort;
}
void sort_classes(vector<unique<CLClass>>& classes)
{
for(size_t n = 0; n < classes.size(); ++n)
{
classes[n]->m_index = n;
}
vector<vector<size_t>> links;
links.resize(classes.size());
for(size_t n = 0; n < classes.size(); ++n)
{
CLClass& item = *classes[n];
for(CLClass* base : item.m_deep_bases)
{
if(base == &*classes[base->m_index])
links[n].push_back(base->m_index);
}
}
const TopoSort sort = sort_topological(links);
stable_sort(classes, [&](const unique<CLClass>& a, const unique<CLClass>& b) { return sort.order[a->m_index] < sort.order[b->m_index]; });
}
const CLType& element_type(const CLType& t)
{
if(t.m_type_kind == CLTypeKind::Alias)
return element_type(*((CLAlias&)t).m_target);
if(t.m_type_kind == CLTypeKind::Class)
{
const CLClass& c = (CLClass&)t;
if(c.m_sequence) return *c.m_element_type;
else if(c.m_array) return *c.m_array_type;
}
return t;
}
const CLType& reduce_element(const CLType& t)
{
if(t.m_type_kind == CLTypeKind::Alias)
return reduce_element(*((CLAlias&)t).m_target);
if(t.m_type_kind == CLTypeKind::Class)
{
const CLClass& c = (CLClass&)t;
if(c.m_sequence) return reduce_element(*c.m_element_type);
else if(c.m_array) return reduce_element(*c.m_array_type);
}
return t;
}
bool should_visit(CXCursor cursor, CLModule& module)
{
auto fix_path = [](const string& path) { return replace(path, "\\", "/"); };
string location = fix_path(file(cursor));
return module.m_parsed_files.find(location) == module.m_parsed_files.end();
}
bool should_reflect(CXCursor cursor, CLModule& module)
{
auto fix_path = [](const string& path) { return replace(path, "\\", "/"); };
string location = fix_path(file(cursor));
return location.find(module.m_path) == 0 && location.find("meta") == string::npos;
}
CLQualType qual_type(CLModule& module, const CLPrimitive& parent, CXType type, bool real_type)
{
//if(upointee(type).kind == CXType_Unexposed && !parent.m_is_templated)
// type = canonical(type);
bool templated = parent.m_is_templated && upointee(type).kind == CXType_Unexposed;
CLQualType t;
auto fix = [&](const string& name) { return templated ? parent.fix_template(name) : name; };
t.m_spelling = fix(spelling(type));
t.m_type_name = fix(spelling(class_type(type, !templated)));
t.m_array = type.kind == CXType_ConstantArray;
if(!real_type) return t;
t.m_type = templated ? module.get_type(type, t.m_type_name) : module.get_type(type);
// fixing type names because of spellings from libclang are not always fully qualified (mostly namespaces)
t.m_spelling = (t.isconst() ? "const " : "") + t.m_type->m_id + (t.pointer() ? "*" : "") + (t.reference() ? "&" : "");
t.m_type_name = t.m_type->m_id;
// substitute real aliased type only after fixing the spellings, so we see the alias types in reflection/bindings code
if(t.m_type->m_type_kind == CLTypeKind::Alias)
t.m_type = ((CLAlias*)t.m_type)->m_target;
if(t.m_type->m_type_kind == CLTypeKind::Class)
t.m_class = (CLClass*)t.m_type;
return t;
}
void decl_enum(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLEnum& e = vector_emplace<CLEnum>(module.m_enums, module, parent, type(cursor));
module.register_type(e);
e.m_cursor = cursor;
e.m_annotations = get_annotations(e.m_cursor);
e.m_reflect = has(e.m_annotations, "refl") && should_reflect(cursor, module);
module.m_has_reflected |= e.m_reflect;
}
void decl_callable(CLModule& module, CLPrimitive& parent, CLCallable& f, CXCursor cursor)
{
f.m_name = spelling(cursor);
f.m_cursor = cursor;
f.m_module = &module;
f.m_reflect = should_reflect(cursor, module);
const int template_args = clang_Cursor_getNumTemplateArguments(cursor);
if(cursor.kind == CXCursor_FunctionDecl && template_args > 0)
{
vector<string> types;
for(int i = 0; i < template_args; ++i)
{
CXType t = clang_Cursor_getTemplateArgumentType(cursor, 0);
types.push_back(spelling(t));
//f.m_templated_types.push_back(find_type(t));
}
f.m_name += "<" + comma(types) + ">";
f.m_id += "<" + comma(types) + ">";
}
f.m_is_template = cursor.kind == CXCursor_FunctionTemplate || (parent.m_is_template);
parent.m_reflect_content |= f.m_reflect;
module.m_has_reflected |= f.m_reflect;
}
void decl_function(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
//print "Function ", cursor.displayname
CLFunction& f = vector_emplace<CLFunction>(module.m_functions, parent, spelling(cursor));
decl_callable(module, parent, f, cursor);
f.m_index = module.m_functions.size() - 1;
}
// @todo cleanup this isn't really used, we declare specializations directly
void decl_function_template(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
//printf("Function Template %s %s\n", displayname(cursor).c_str(), spelling(cursor).c_str());
CLFunction& f = vector_emplace<CLFunction>(module.m_func_templates, parent, spelling(cursor));
f.m_is_template = true;
decl_callable(module, parent, f, cursor);
}
void decl_function_method(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLFunction& f = vector_emplace<CLFunction>(module.m_methods, parent, spelling(cursor));
decl_callable(module, parent, f, cursor);
}
void resolve_templates(CLModule& module, CLClass& c)
{
//printf("Resolve templates for %s\n", c.m_id.c_str());
c.m_template = &module.get_class_template(c.m_template_name);
if(c.m_template == nullptr)
{
c.m_reflect = false;
printf("[ERROR] %s - could not find template type definition\n", c.m_name.c_str());
return;
}
for(size_t i = 0; i < c.m_template_types.size(); ++i)
{
CXType t = clang_Type_getTemplateArgumentAsType(type(c.m_cursor), i);
CLType* type = module.find_alias(t, c.m_template_types[i]);
if(type == nullptr)
type = module.get_type(t);
c.m_templated_types.push_back(type);
bool pointer = c.m_template_types[i].find("*") != string::npos;
c.m_template_types[i] = type->m_id + string(pointer && type->m_type_kind != CLTypeKind::VoidPtr ? "*" : "");
}
c.set_name(c.m_template_name + "<" + comma(c.m_template_types) + ">");
if(c.m_sequence)
{
c.m_element = c.m_template_types[0];
c.m_element_type = c.m_templated_types[0];
}
}
void decl_class(CLModule& module, CLPrimitive& parent, CLClass& c, CXCursor cursor, CXType cxtype, bool sequence)
{
c.m_cursor = cursor;
c.m_annotations = get_annotations(cursor);
c.m_struct = has(c.m_annotations, "struct") || cursor.kind == CXCursor_StructDecl;
c.m_move_only = has(c.m_annotations, "nocopy");
c.m_reflect = has(c.m_annotations, "refl") && should_reflect(cursor, module);
c.m_array = has(c.m_annotations, "array");
c.m_span = has(c.m_annotations, "span");
c.m_sequence = has(c.m_annotations, "seque") || c.m_span;
c.m_extern = has(c.m_annotations, "extern");
c.m_is_template = cursor.kind == CXCursor_ClassTemplate;
c.m_is_templated = c.m_name.find("<") != string::npos && !c.m_is_template;
if(c.m_is_template)
c.set_name(displayname(cursor));
if(c.m_is_template || c.m_is_templated)
{
c.m_template_types = template_types(c.m_name);
c.m_template_name = template_name(c.m_name);
}
parent.m_reflect_content |= c.m_reflect;
module.m_has_reflected |= c.m_reflect;
}
CLClass& decl_class_type(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLClass& c = vector_emplace<CLClass>(module.m_classes, module, parent, type(cursor));
module.register_type(c);
decl_class(module, parent, c, cursor, type(cursor));
return c;
}
CLClass& decl_sequence_type(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLClass& c = vector_emplace<CLClass>(module.m_sequences, module, parent, type(cursor));
module.register_type(c);
decl_class(module, parent, c, cursor, type(cursor), true);
return c;
}
CLClass& decl_class_template(CLModule& module, CLPrimitive& parent, CXCursor cursor)
{
CLClass& c = vector_emplace<CLClass>(module.m_class_templates, module, parent, type(cursor));
decl_class(module, parent, c, cursor, type(cursor));
return c;
}
void parse_enum(CLModule& module, CLEnum& e)
{
UNUSED(module);
e.m_scoped = is_scoped(e.m_cursor);
e.m_enum_type = spelling(enum_type(e.m_cursor));
e.m_prefix = e.m_scoped ? e.m_id + "::" : e.m_parent->m_prefix;
const CXType integer_type = canonical(clang_getEnumDeclIntegerType(e.m_cursor));
bool is_signed = has({ CXType_SChar, CXType_Short, CXType_Int, CXType_Long, CXType_LongLong }, integer_type.kind);
visit_children(e.m_cursor, [&](CXCursor c)
{
if(c.kind == CXCursor_EnumConstantDecl)
{
e.m_ids.push_back(displayname(c));
e.m_values.push_back(is_signed ? to_string(clang_getEnumConstantDeclValue(c))
: to_string(clang_getEnumConstantDeclUnsignedValue(c)));
e.m_scoped_ids.push_back(e.m_prefix + displayname(c));
}
});
e.m_count = e.m_ids.size();
}
void parse_static(CLModule& module, CLClass& c, CXCursor cursor)
{
UNUSED(module);
CLStatic& s = push(c.m_statics, c);
s.m_member = spelling(cursor);
s.m_name = replace(spelling(cursor), "m_", "");
}
void find_default_value(CXCursor cursor, CLType& value_type, bool& has_default, string& default_value)
{
if(type(cursor).kind == CXType_ConstantArray)
return;
visit_children(cursor, [&](CXCursor c)
{
if(has({ CXCursor_CXXBoolLiteralExpr, CXCursor_FloatingLiteral, CXCursor_IntegerLiteral, CXCursor_StringLiteral }, c.kind))
{
has_default = true;
default_value = first_token(c);
if(default_value == "")
default_value = last_token(cursor);
}
else if(has({ CXCursor_BinaryOperator, CXCursor_UnaryOperator, CXCursor_CallExpr, CXCursor_DeclRefExpr, CXCursor_UnexposedExpr }, c.kind))
{
has_default = true;
visit_tokens(c, [&](CXToken t) {
string token = spelling(c, t);
if(ends_with(default_value + token, value_type.m_name))
default_value += token;
else if(kind(t) == CXToken_Identifier && value_type.m_name == token) default_value += value_type.m_id;
else if(token != "=") default_value += token;
});
}
});
}
void parse_param(CLModule& module, CLPrimitive& parent, CLCallable& f, CLParam& p, CXCursor cursor)
{
p.m_name = spelling(cursor);
p.m_type = qual_type(module, parent, type(cursor), !parent.m_is_template);
p.m_output = p.m_name.substr(0, 6) == "output";
if(p.m_type.m_type)
{
find_default_value(cursor, *p.m_type.m_type, p.m_has_default, p.m_default);
if(parent.m_is_templated)
p.m_default = parent.fix_template(p.m_default);
}
}
void parse_callable(CLModule& module, CLCallable& f)
{
//printf("Parsing %s\n", f.m_name.c_str());
f.m_return_type = qual_type(module, *f.m_parent, result_type(f.m_cursor), !f.m_is_template);
visit_children(f.m_cursor, [&](CXCursor a)
{
if(a.kind == CXCursor_ParmDecl)
{
f.m_params.push_back(CLParam(f, f.m_params.size()));
parse_param(module, *f.m_parent, f, f.m_params.back(), a);
}
});
for(size_t i = 0; i < f.m_params.size(); ++i)
if(!f.m_params[i].m_has_default)
f.m_min_args = i + 1;
}
void parse_constructor(CLModule& module, CLClass& c, CXCursor cursor)
{
CLConstructor& ctor = push(c.m_constructors, c, spelling(cursor));
decl_callable(module, c, ctor, cursor);
parse_callable(module, ctor);
ctor.m_overload_index = c.m_constructors.size() - 1;
}
void parse_method(CLModule& module, CLClass& c, CLMethod& m, CXCursor cursor)
{
decl_callable(module, c, m, cursor);
parse_callable(module, m);
m.m_const = is_const_method(cursor);
}
void parse_method(CLModule& module, CLClass& c, CXCursor cursor)
{
CLMethod& m = push(c.m_methods, c, spelling(cursor));
parse_method(module, c, m, cursor);
}
void parse_function_method(CLModule& module, CLFunction& f)
{
parse_callable(module, f);
CLClass& c = *f.m_params[0].m_type.m_class;
//parse_method(module, c, f.m_cursor);
CLMethod& m = push(c.m_methods, c, f.m_name);
decl_callable(module, c, m, f.m_cursor);
m.m_return_type = f.m_return_type;
m.m_params = vector<CLParam>(f.m_params.begin() + 1, f.m_params.end());
m.m_function = &f;
}
void parse_member(CLModule& module, CLClass& c, CXCursor cursor)
{
CLMember& m = push(c.m_members, c);
m.m_member = spelling(cursor);
m.m_name = replace(spelling(cursor), "m_", "");
m.m_capname = string(1, char(toupper(m.m_name[0]))) + m.m_name.substr(1, string::npos);
CXType member_type = type(cursor);
if(cursor.kind == CXCursor_CXXMethod)
{
m.m_method = make_unique<CLMethod>(c, spelling(cursor));
parse_method(module, c, *m.m_method, cursor);
member_type = result_type(cursor);
}
m.m_type = qual_type(module, c, member_type, !c.m_is_template);
m.m_annotations = get_annotations(cursor);
m.m_nonmutable = has(m.m_annotations, "nomut");
m.m_structure = has(m.m_annotations, "graph");
m.m_link = has(m.m_annotations, "link");
m.m_component = has(m.m_annotations, "comp");
if(!c.m_is_template)
{
m.m_nonmutable |= m.m_type.reference();
m.m_nonmutable |= !m.m_type.pointer() && (m.m_type.isconst() || !m.m_type.m_type->copyable());
m.m_nonmutable |= !m.m_setter && m.m_method;
}
visit_children(cursor, [&](CXCursor s)
{
if(s.kind == CXCursor_CXXMethod && spelling(s) == "set" + m.m_capname || spelling(s) == "set_" + m.m_name)
{
m.m_setter = make_unique<CLMethod>(c, spelling(s));
parse_method(module, c, *m.m_setter, s);
}
});
if(m.m_type.m_type)
{
find_default_value(cursor, *m.m_type.m_type, m.m_has_default, m.m_default);
if(c.m_is_templated)
m.m_default = c.fix_template(m.m_default);
}
}
void parse_class_child(CLModule& module, CLClass& c, CXCursor cursor)
{
const vector<string> annotations = get_annotations(cursor);
if(cursor.kind == CXCursor_TemplateTypeParameter)
c.m_template_types.push_back(spelling(cursor));
else if(cursor.kind == CXCursor_CXXBaseSpecifier)
{
const string name = spelling(type(cursor));
//if(c.m_is_templated && name.find("<") != string::npos)
// name = c.fix_template(name);
if(!c.m_is_templated && name.find("<") == string::npos)
{
CLType* base = module.find_type(name);
if(base && base->m_type_kind == CLTypeKind::Alias)
base = static_cast<CLAlias*>(base)->m_target;
if(base && (base->m_reflect || has(base->m_annotations, "refl")))
{
CLClass* basecls = static_cast<CLClass*>(base);
c.m_bases.push_back(basecls);
c.m_deep_bases.push_back(basecls);
extend(c.m_deep_bases, basecls->m_bases);
}
}
}
else if(cursor.kind == CXCursor_Constructor && has(annotations, "constr"))
parse_constructor(module, c, cursor);
else if(cursor.kind == CXCursor_CXXMethod && has(annotations, "attr"))
parse_member(module, c, cursor);
else if(cursor.kind == CXCursor_CXXMethod && has(annotations, "meth"))
parse_method(module, c, cursor);
else if(cursor.kind == CXCursor_FieldDecl && has(annotations, "attr"))
parse_member(module, c, cursor);
else if(cursor.kind == CXCursor_VarDecl && has(annotations, "attr"))
parse_static(module, c, cursor);
else if(cursor.kind == CXCursor_UnionDecl || cursor.kind == CXCursor_StructDecl)
{
if(clang_Cursor_isAnonymous(cursor))
visit_children(cursor, [&](CXCursor a) {
parse_class_child(module, c, a);
});
}
}
void parse_class(CLModule& module, CLClass& c)
{
//printf("Parsing %s\n", c.m_id.c_str());
CXCursor cursor = c.m_cursor;
#if !RESOLVE_TEMPLATES
if(c.m_is_templated)
resolve_templates(module, c);
#endif
if(c.m_is_templated && c.m_template) // && is_template_decl(cursor))
cursor = c.m_template->m_cursor;
visit_children(cursor, [&](CXCursor a) {
parse_class_child(module, c, a);
});
if(c.m_array)
{
c.m_array_size = c.m_members.size();
c.m_array_type = c.m_members[0].m_type.m_type;
}
set<string> method_names;
for(CLMethod& method : c.m_methods)
{
if(method_names.find(method.m_name) != method_names.end())
method.m_overloaded = true;
method_names.insert(method.m_name);
}
if(c.m_struct && c.m_constructors.empty())
{
CLConstructor& ctor = push(c.m_constructors, c, c.m_name);
ctor.m_module = &module;
ctor.m_overload_index = 0;
}
}
void parse_sequence(CLModule& module, CLClass& c)
{
parse_class(module, c);
c.m_name = c.m_template_name + "<" + c.m_element + ">";
}
void build_classes(CXCursor cursor, CLModule& module, CLPrimitive& parent)
{
visit_children(cursor, [&](CXCursor c)
{
if(!should_visit(c, module)) return;
vector<string> annotations = get_annotations(c);
if(c.kind == CXCursor_Namespace)
{
CLNamespace& ns = module.get_namespace(spelling(c), parent);
build_classes(c, module, ns);
}
else if(c.kind == CXCursor_VarDecl && has(annotations, "base"))
{
module.base_type(type(c));
}
else if(c.kind == CXCursor_TypeAliasDecl || c.kind == CXCursor_TypedefDecl)
{
CXType cxalias = type(c);
CXType cxtarget = canonical(type(c));
CLType* target = module.find_type(cxtarget);
if(target && !target->iscstring() && parent.m_kind == CLPrimitiveKind::Namespace)
{
CLAlias& t = vector_emplace<CLAlias>(module.m_aliases, module, parent, cxalias, cxtarget);
//printf("aliased %s to %s\n", t.m_id.c_str(), target->m_id.c_str());
t.m_target = target;
t.m_reflect = should_reflect(c, module);
module.register_type(t);
}
}
else if(is_definition(c) && has(annotations, "refl"))
{
if(c.kind == CXCursor_EnumDecl)
decl_enum(module, parent, c);
else if((c.kind == CXCursor_ClassDecl || c.kind == CXCursor_StructDecl))
{
CLClass& cl = has(annotations, "seque") || has(annotations, "span")
? decl_sequence_type(module, parent, c)
: decl_class_type(module, parent, c);
build_classes(c, module, cl);
}
else if(c.kind == CXCursor_ClassTemplate)
{
CLClass& cl = decl_class_template(module, parent, c);
build_classes(c, module, cl);
}
}
else if(c.kind == CXCursor_FunctionTemplate && has(annotations, "func"))
decl_function_template(module, parent, c);
else if(c.kind == CXCursor_FunctionDecl && has(annotations, "func") && should_reflect(c, module))
decl_function(module, parent, c);
else if(c.kind == CXCursor_FunctionDecl && has(annotations, "meth") && should_reflect(c, module))
decl_function_method(module, parent, c);
});
}
class CLGenerator
{
public:
CLGenerator() {}
vector<unique<CLModule>> m_modules = {};
vector<CLModule*> m_generator_queue = {};
CLModule& module(const string& id)
{
for(auto& module : m_modules)
if(id == module->m_id)
return *module;
printf("[ERROR] fetching inexistent module\n");
static CLModule invalid; return invalid;
}
void print_diagnostics(CXTranslationUnit tu)
{
uint num_diagnostics = clang_getNumDiagnostics(tu);
for(uint i = 0; i < num_diagnostics; ++i)
{
CXDiagnostic diagnostic = clang_getDiagnostic(tu, i);
CXDiagnosticSeverity severity = clang_getDiagnosticSeverity(diagnostic);
CXSourceLocation location = clang_getDiagnosticLocation(diagnostic);
CXString filename;
unsigned int line;
unsigned int column;
clang_getPresumedLocation(location, &filename, &line, &column);
printf("severity: %i, ", int(severity));
printf("location: %s (%i, %i), ", clang_string(filename).c_str(), line, column);
printf("%s\n", clang_string(clang_getDiagnosticSpelling(diagnostic)).c_str());
//print diag.option
clang_disposeString(filename);
}
}
CXTranslationUnit parse(CLModule& module)
{
printf("Module path : %s\n", module.m_path.c_str());
bool debug_diagnostic = true;
vector<string> compiler_args = {
"-x",
"c++",
"-std=c++17",
"-fdelayed-template-parsing",
"-fms-compatibility",
"-fms-extensions",
"-fmsc-version=1900",
"-Wmicrosoft",
"-isystemC:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.16.27023/include",
"-isystemC:/Program Files (x86)/Windows Kits/10/Include/10.0.10240.0/ucrt",
"-DTWO_META_GENERATOR",
//"-DTWO_NO_GLM", // @todo
};
for(string attr : { "base", "refl", "struct", "nocopy", "extern", "gpu", "array", "span", "seque", "comp", "constr", "meth", "func", "attr", "nomut", "graph", "link" })
compiler_args.push_back("-D" + attr + "_=__attribute__((annotate(\"" + attr + "\")))");
for(string dir : module.m_includedirs)
compiler_args.push_back("-I" + dir);
for(CLModule* m : module.m_modules)
compiler_args.push_back("-I" + m->m_rootdir);
#if DEBUG_CLANG_ARGS
printf("Parsing with compiler args: \n");
for(string arg : compiler_args)
printf("%s\n", arg.c_str());
#endif
vector<cstring> compiler_cargs;
for(const string& arg : compiler_args)
compiler_cargs.push_back(arg.c_str());
string file = "Api.h";
string path = module.m_path + "/" + file;
CXIndex index = clang_createIndex(0, 0);
printf("Parsing %s\n", file.c_str());
// only for debugging : these two ways of parsing don"t give the correct output, but can give more diagnostics as to what might be wrong
// int options = 0;
// int options = CXTranslationUnit_SkipFunctionBodies;
//int options = CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete;
int options = CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_KeepGoing;
CXTranslationUnit translation_unit = clang_parseTranslationUnit(index, path.c_str(), compiler_cargs.data(), int(compiler_cargs.size()), nullptr, 0, options);
constexpr bool debug = true;
if(debug)
print_diagnostics(translation_unit);
return translation_unit;
}
void generate_module(CLModule& module)
{
if(!file_exists(module.m_path + "/" + "Types.h"))
{
//with open(os.path.join(module.path, "Types.h"), "w") as f :
// pass
}
printf("NUM CLASSES : %i\n", int(module.m_classes.size()));
//string forward_h = clgen::forward_h_template(module);
//update_file((module.m_path + "/" + "Forward.h", forward_h);
CXTranslationUnit tu = this->parse(module);
build_classes(cursor(tu), module, module.m_global);
#if RESOLVE_TEMPLATES
for(auto& c : module.m_classes)
if(c->m_is_templated)
resolve_templates(module, *c);
for(auto& c : module.m_sequences)
if(c->m_is_templated)
resolve_templates(module, *c);
#endif
for(auto& e : module.m_enums)
parse_enum(module, *e);
for(auto& c : module.m_classes)
parse_class(module, *c);
for(auto& c : module.m_sequences)
parse_sequence(module, *c);
for(auto& f : module.m_functions)
parse_callable(module, *f);
for(auto& f : module.m_methods)
parse_function_method(module, *f);
clang_disposeTranslationUnit(tu);
auto cmp_types = [](CLType& a, CLType& b) -> int
{
int result = a.m_name.compare(b.m_name);
return result < 0;
};
stable_sort(module.m_types, [&](CLType* a, CLType* b) { return cmp_types(*a, *b) < 0; });
stable_sort(module.m_enums, [&](const unique<CLEnum>& a, const unique<CLEnum>& b) { return cmp_types(*a, *b) < 0; });
stable_sort(module.m_sequences, [&](const unique<CLClass>& a, const unique<CLClass>& b) { return cmp_types(*a, *b) < 0; });
stable_sort(module.m_basetypes, [&](const unique<CLBaseType>& a, const unique<CLBaseType>& b) { return cmp_types(*a, *b) < 0; });
sort_classes(module.m_classes);
//if(module.m_classes.size() == 0 && module.m_enums.size() == 0)
// return;
if(!directory_exists(module.m_refl_path))
create_directory_tree(module.m_refl_path);
printf("Generating meta reflection files for %s:\n", module.m_name.c_str());
string types_h = clgen::types_h_template(module);
update_file(module.m_path + "/" + "Types.h", types_h);
if(!module.m_notypes)
{
string types_cpp = clgen::types_cpp_template(module);
update_file(module.m_path + "/" + module.m_dotname + ".types.cpp", types_cpp);
}
string module_h = clgen::module_h_template(module);
update_file(module.m_refl_path + "/" + module.m_dotname + ".meta.h", module_h);
string module_cpp = clgen::module_cpp_template(module);
update_file(module.m_refl_path + "/" + module.m_dotname + ".meta.cpp", module_cpp);
string convert_h = clgen::convert_h_template(module);
update_file(module.m_refl_path + "/" + module.m_dotname + ".conv.h", convert_h);
printf("Generating bindings files for %s:\n", module.m_name.c_str());
if(!directory_exists(module.m_bind_path))
create_directory_tree(module.m_bind_path);
clgen::bind_javascript(module);
}
void add_module(const Json& m)
{
auto tos = [](const Json& j) -> string { return j.string_value().c_str(); };
vector<CLModule*> dependencies = {};
for(const Json& dep : m["dependencies"].array_items())
{
dependencies.push_back(&this->module(tos(dep)));
}
vector<string> includedirs = {};
for(const Json& inc : m["includedirs"].array_items())
{
includedirs.push_back(tos(inc));
}
CLModule& module = vector_emplace<CLModule>(m_modules, tos(m["namespace"]), tos(m["name"]), tos(m["dotname"]), tos(m["idname"]),
tos(m["root"]), tos(m["subdir"]), tos(m["path"]), includedirs, dependencies);
if(m["notypes"].bool_value())
module.m_notypes = true;
m_generator_queue.push_back(&module);
if(module.m_name == "type")
module.m_decl_basetypes = true;
}
void generate_module(const string& id)
{
CLModule& module = this->module(id);
this->generate_module(module);
}
void generate_all_modules()
{
for(CLModule* module : m_generator_queue)
this->generate_module(*module);
}
};
}
using namespace two;
int main(int argc, char *argv[])
{
string all = "d:/Documents/Programmation/toy/build/refl/two_infra_refl.json d:/Documents/Programmation/toy/build/refl/two_jobs_refl.json d:/Documents/Programmation/toy/build/refl/two_type_refl.json d:/Documents/Programmation/toy/build/refl/two_tree_refl.json d:/Documents/Programmation/toy/build/refl/two_pool_refl.json d:/Documents/Programmation/toy/build/refl/two_refl_refl.json d:/Documents/Programmation/toy/build/refl/two_ecs_refl.json d:/Documents/Programmation/toy/build/refl/two_srlz_refl.json d:/Documents/Programmation/toy/build/refl/two_math_refl.json d:/Documents/Programmation/toy/build/refl/two_geom_refl.json d:/Documents/Programmation/toy/build/refl/two_noise_refl.json d:/Documents/Programmation/toy/build/refl/two_wfc_refl.json d:/Documents/Programmation/toy/build/refl/two_fract_refl.json d:/Documents/Programmation/toy/build/refl/two_lang_refl.json d:/Documents/Programmation/toy/build/refl/two_ctx_refl.json d:/Documents/Programmation/toy/build/refl/two_ui_refl.json d:/Documents/Programmation/toy/build/refl/two_uio_refl.json d:/Documents/Programmation/toy/build/refl/two_snd_refl.json d:/Documents/Programmation/toy/build/refl/two_bgfx_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_refl.json d:/Documents/Programmation/toy/build/refl/two_gltf_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_pbr_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_obj_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_gltf_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_ui_refl.json d:/Documents/Programmation/toy/build/refl/two_gfx_edit_refl.json d:/Documents/Programmation/toy/build/refl/two_tool_refl.json d:/Documents/Programmation/toy/build/refl/two_wfc_gfx_refl.json d:/Documents/Programmation/toy/build/refl/two_frame_refl.json d:/Documents/Programmation/toy/build/refl/toy_util_refl.json d:/Documents/Programmation/toy/build/refl/toy_core_refl.json d:/Documents/Programmation/toy/build/refl/toy_visu_refl.json d:/Documents/Programmation/toy/build/refl/toy_edit_refl.json d:/Documents/Programmation/toy/build/refl/toy_block_refl.json d:/Documents/Programmation/toy/build/refl/toy_shell_refl.json d:/Documents/Programmation/toy/build/refl/_test_refl.json d:/Documents/Programmation/toy/build/refl/_minimal_refl.json d:/Documents/Programmation/toy/build/refl/_boids_refl.json d:/Documents/Programmation/toy/build/refl/_space_refl.json d:/Documents/Programmation/toy/build/refl/_platform_refl.json d:/Documents/Programmation/toy/build/refl/_blocks_refl.json d:/Documents/Programmation/toy/build/refl/_wren_refl.json d:/Documents/Programmation/toy/build/refl/_godot_refl.json";
CLGenerator generator;
vector<string> locations = split(all, " ");
for(int i = 1; i < argc; ++i)
locations.push_back(argv[i]);
for(string loc : locations)
{
std::string errors;
string text_module = read_text_file(loc);
Json json_module = Json::parse(text_module.c_str(), errors);
generator.add_module(json_module);
}
//generator.generate_module("two_math");
//generator.generate_module("two_geom");
//generator.generate_module("two_gfx");
generator.generate_all_modules();
return 0;
}
| 34.028185 | 2,644 | 0.695358 | raptoravis |
139d5eb44977f8cba61672d95216750ad571ced0 | 530 | hpp | C++ | splitter/header/predicates/IBMtimePredicate.hpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | splitter/header/predicates/IBMtimePredicate.hpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | splitter/header/predicates/IBMtimePredicate.hpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | #ifndef IBMTIMEPREDICATE_H
#define IBMTIMEPREDICATE_H
#include "AbstractPredicate.hpp"
#include <set>
namespace splitter
{
class IBMtimePredicate : public AbstractPredicate
{
public:
IBMtimePredicate(unsigned long time);
virtual bool ps(const events::AbstractEvent &event) const;
virtual bool pc(const events::AbstractEvent &event, selection::AbstractSelection &abstractSelection);
virtual ~IBMtimePredicate() {}
private:
unsigned long timeOpen;
set<string> symbols;
};
}
#endif // IBMTIMEPREDICATE_H
| 21.2 | 105 | 0.764151 | spectreCEP |
139d83eae53539c796788bae08d8633796d4e4d3 | 397 | hpp | C++ | chaine/src/mesh/mesh/all.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/mesh/mesh/all.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/mesh/mesh/all.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | #pragma once
#include "create_triangle.hpp"
#include "create_vertex.hpp"
#include "geometry.hpp"
#include "inner_triangle_edges.hpp"
#include "insert_vertex.hpp"
#include "lawson_algorithm.hpp"
#include "mesh.hpp"
#include "random_triangle_edge.hpp"
#include "topology.hpp"
#include "triangle.hpp"
#include "triangles.hpp"
#include "vertex_count.hpp"
#include "vertices.hpp"
#include "split.hpp"
| 23.352941 | 35 | 0.778338 | the-last-willy |
139db5e77c40d06224a6ab25bc72bd6626aa885f | 4,348 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR/ConstructorBuilder_SetSymCustomAttribute/CPP/constructorbuilder_setsymcustomattribute.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR/ConstructorBuilder_SetSymCustomAttribute/CPP/constructorbuilder_setsymcustomattribute.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR/ConstructorBuilder_SetSymCustomAttribute/CPP/constructorbuilder_setsymcustomattribute.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z | // System.Reflection.Emit.ConstructorBuilder.SetSymCustomAttribute()
/* The following program demonstrates the 'SetSymCustomAttribute' method
of ConstructorBuilder class. It creates an assembly in the current
domain with dynamic module in the assembly. Constructor builder is
used in conjunction with the 'TypeBuilder' class to create constructor
at run time. It then sets this constructor's custom attribute associated
with symbolic information.
*/
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
public ref class MyConstructorBuilder
{
private:
Type^ myType1;
ModuleBuilder^ myModuleBuilder;
AssemblyBuilder^ myAssemblyBuilder;
public:
MyConstructorBuilder()
{
myModuleBuilder = nullptr;
myAssemblyBuilder = nullptr;
// <Snippet1>
MethodBuilder^ myMethodBuilder = nullptr;
AppDomain^ myCurrentDomain = AppDomain::CurrentDomain;
// Create assembly in current CurrentDomain.
AssemblyName^ myAssemblyName = gcnew AssemblyName;
myAssemblyName->Name = "TempAssembly";
// Create a dynamic assembly.
myAssemblyBuilder = myCurrentDomain->DefineDynamicAssembly(
myAssemblyName, AssemblyBuilderAccess::Run );
// Create a dynamic module in the assembly.
myModuleBuilder = myAssemblyBuilder->DefineDynamicModule( "TempModule", true );
FieldInfo^ myFieldInfo =
myModuleBuilder->DefineUninitializedData( "myField", 2, FieldAttributes::Public );
// Create a type in the module.
TypeBuilder^ myTypeBuilder = myModuleBuilder->DefineType( "TempClass", TypeAttributes::Public );
FieldBuilder^ myGreetingField = myTypeBuilder->DefineField( "Greeting",
String::typeid, FieldAttributes::Public );
array<Type^>^ myConstructorArgs = {String::typeid};
// Define a constructor of the dynamic class.
ConstructorBuilder^ myConstructor = myTypeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, myConstructorArgs );
// Display the name of the constructor.
Console::WriteLine( "The constructor name is : {0}", myConstructor->Name );
array<Byte>^ temp0 = {01,00,00};
myConstructor->SetSymCustomAttribute( "MySimAttribute", temp0 );
// </Snippet1>
// Generate the IL for the method and call its superclass constructor.
ILGenerator^ myILGenerator3 = myConstructor->GetILGenerator();
myILGenerator3->Emit( OpCodes::Ldarg_0 );
ConstructorInfo^ myConstructorInfo = Object::typeid->GetConstructor( gcnew array<Type^>(0) );
myILGenerator3->Emit( OpCodes::Call, myConstructorInfo );
myILGenerator3->Emit( OpCodes::Ldarg_0 );
myILGenerator3->Emit( OpCodes::Ldarg_1 );
myILGenerator3->Emit( OpCodes::Stfld, myGreetingField );
myILGenerator3->Emit( OpCodes::Ret );
// Add a method to the type.
myMethodBuilder = myTypeBuilder->DefineMethod(
"HelloWorld", MethodAttributes::Public, nullptr, nullptr );
// Generate IL for the method.
ILGenerator^ myILGenerator2 = myMethodBuilder->GetILGenerator();
myILGenerator2->EmitWriteLine( "Hello World from global" );
myILGenerator2->Emit( OpCodes::Ret );
myModuleBuilder->CreateGlobalFunctions();
myType1 = myTypeBuilder->CreateType();
}
property Type^ MyTypeProperty
{
Type^ get()
{
return this->myType1;
}
}
};
int main()
{
MyConstructorBuilder^ myConstructorBuilder = gcnew MyConstructorBuilder;
Type^ myType1 = myConstructorBuilder->MyTypeProperty;
if ( nullptr != myType1 )
{
Console::WriteLine( "Instantiating the new type..." );
array<Object^>^ myObject = {"hello"};
Object^ myObject1 = Activator::CreateInstance( myType1, myObject, nullptr );
MethodInfo^ myMethodInfo = myType1->GetMethod( "HelloWorld" );
if ( nullptr != myMethodInfo )
{
Console::WriteLine( "Invoking dynamically created HelloWorld method..." );
myMethodInfo->Invoke( myObject1, nullptr );
}
else
{
Console::WriteLine( "Could not locate HelloWorld method" );
}
}
else
{
Console::WriteLine( "Could not access Type." );
}
}
| 40.635514 | 153 | 0.682383 | hamarb123 |
139f18eb59ff836ac2714255978d14d2cf42df13 | 25,382 | cpp | C++ | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/Kasan.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/Kasan.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 2 | 2020-11-02T08:01:00.000Z | 2022-03-27T02:59:18.000Z | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/Kasan.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 11 | 2020-08-06T03:59:45.000Z | 2022-02-25T02:31:59.000Z | #include <s2e/S2E.h>
#include "Kasan.h"
#include "util.h"
using namespace klee;
namespace s2e {
namespace plugins {
// #define DEBUG_KASAN
S2E_DEFINE_PLUGIN(KernelAddressSanitizer, "kernel address sanitizer",
"KernelAddressSanitizer", "KernelFunctionModels",
"AllocManager", "OptionsManager", "LinuxMonitor");
#define DEFAULT_STACK_DEPTH 2
#define REPORT_STACK_DEPTH 3
void KernelAddressSanitizer::initialize() {
m_kernelFunc = s2e()->getPlugin<models::KernelFunctionModels>();
m_allocManager = s2e()->getPlugin<AllocManager>();
m_options = s2e()->getPlugin<OptionsManager>();
m_linuxMonitor = s2e()->getPlugin<LinuxMonitor>();
m_pcMonitor = s2e()->getPlugin<PcMonitor>();
assert(m_linuxMonitor && "Only support Linux");
initializeConfiguration();
getDebugStream() << "Mode: " << m_options->mode << "\n";
switch (m_options->mode) {
case MODE_PRE_ANALYSIS:
// m_handlers["kasan_report"] = &KernelAddressSanitizer::handleReport;
break;
case MODE_ANALYSIS:
case MODE_RESOLVE:
// m_handlers["kasan_report"] = &KernelAddressSanitizer::handleReport;
m_handlers["__asan_store1"] = &KernelAddressSanitizer::handleStore1;
m_handlers["__asan_store2"] = &KernelAddressSanitizer::handleStore2;
m_handlers["__asan_store4"] = &KernelAddressSanitizer::handleStore4;
m_handlers["__asan_store8"] = &KernelAddressSanitizer::handleStore8;
m_handlers["__asan_store16"] = &KernelAddressSanitizer::handleStore16;
m_handlers["__asan_storeN"] = &KernelAddressSanitizer::handleStoreN;
m_handlers["check_memory_region"] =
&KernelAddressSanitizer::handleCheckMemoryRegion;
if (!m_options->write_only) {
m_handlers["__asan_load1"] = &KernelAddressSanitizer::handleLoad1;
m_handlers["__asan_load2"] = &KernelAddressSanitizer::handleLoad2;
m_handlers["__asan_load4"] = &KernelAddressSanitizer::handleLoad4;
m_handlers["__asan_load8"] = &KernelAddressSanitizer::handleLoad8;
m_handlers["__asan_load16"] = &KernelAddressSanitizer::handleLoad16;
m_handlers["__asan_loadN"] = &KernelAddressSanitizer::handleLoadN;
}
m_additionChecks["csum_partial_copy_generic"] =
&KernelAddressSanitizer::handleCsumPartialCopyGeneric;
break;
default:
break;
}
}
void KernelAddressSanitizer::initializeConfiguration() {
bool ok = false;
ConfigFile *cfg = s2e()->getConfig();
ConfigFile::string_list funcList =
cfg->getListKeys(getConfigKey() + ".functions");
if (funcList.size() == 0) {
getWarningsStream() << "no functions configured\n";
// exit(1);
}
foreach2(it, funcList.begin(), funcList.end()) {
std::stringstream s;
s << getConfigKey() << ".functions." << *it;
std::string funcName = cfg->getString(s.str() + ".funcName", "", &ok);
EXIT_ON_ERROR(ok, "You must specify funcName");
uint64_t entry = cfg->getInt(s.str() + ".entry", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify entry");
uint64_t exitAddr = cfg->getInt(s.str() + ".exit", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify exit");
m_funcMap[funcName] = entry;
m_ranges[exitAddr] = entry;
}
funcList = cfg->getListKeys(getConfigKey() + ".checks");
foreach2(it, funcList.begin(), funcList.end()) {
std::stringstream s;
s << getConfigKey() << ".checks." << *it;
uint64_t address = cfg->getInt(s.str(), 0, &ok);
EXIT_ON_ERROR(ok, "You must specify " + s.str());
m_checkMap[*it] = address;
}
m_kasanReport = cfg->getInt(getConfigKey() + ".kasan_report", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify kasan_report")
m_kasanRet = cfg->getInt(getConfigKey() + ".kasan_ret", 0, &ok);
m_symbolicoverflow =
cfg->getBool(getConfigKey() + ".checksymbol", true, &ok);
}
void KernelAddressSanitizer::registerHandler(PcMonitor *PcMonitor,
S2EExecutionState *state,
uint64_t cr3) {
foreach2(it, m_funcMap.begin(), m_funcMap.end()) {
// we already filter out any other process at PcMonitor, it's ok not to
// give
// cr3 here
PcMonitor::CallSignalPtr CallSignal =
PcMonitor->getCallSignal(state, it->second, cr3);
auto itt = m_handlers.find(it->first);
if (itt == m_handlers.end()) {
continue;
}
getDebugStream() << "Hook Function: " << it->first << " at "
<< hexval(it->second) << "\n";
CallSignal->connect(
sigc::bind(sigc::mem_fun(*this, &KernelAddressSanitizer::onCall),
(*itt).second),
KASAN_PRIORITY);
}
foreach2(it, m_checkMap.begin(), m_checkMap.end()) {
PcMonitor::CallSignalPtr CallSignal =
PcMonitor->getCallSignal(state, it->second, cr3);
auto itt = m_additionChecks.find(it->first);
if (itt == m_additionChecks.end()) {
continue;
}
getDebugStream() << "Check Function: " << it->first << " at "
<< hexval(it->second) << "\n";
CallSignal->connect(
sigc::bind(sigc::mem_fun(*this, &KernelAddressSanitizer::onCheck),
(*itt).second),
KASAN_PRIORITY);
}
// KASAN report
PcMonitor::CallSignalPtr Callsignal =
PcMonitor->getCallSignal(state, m_kasanReport, cr3);
Callsignal->connect(
sigc::mem_fun(*this, &KernelAddressSanitizer::handleReport),
KASAN_PRIORITY);
}
void KernelAddressSanitizer::onCall(S2EExecutionState *state,
PcMonitorState *pcs, uint64_t pc,
KernelAddressSanitizer::OpHandler handler) {
// skip these functions because they will introduce more constraints that we
// dont want
if (m_options->mode == MODE_RESOLVE) {
state->bypassFunction(0);
throw CpuExitException();
}
bool result = ((*this).*handler)(state, pc);
if (!result) {
// report here
// set timer to stop execution
m_options->halt = true;
}
}
void KernelAddressSanitizer::onCheck(
S2EExecutionState *state, PcMonitorState *pcs, uint64_t pc,
KernelAddressSanitizer::OpHandler handler) {
// bool result =
if (m_options->mode == MODE_RESOLVE) {
return;
}
((*this).*handler)(state, pc);
}
// determine the type of the memory address given the layout of the kernel space
// 0000000000000000 - 00007fffffffffff (=47 bits) user space, different per mm
// ffff880000000000 - ffffc7ffffffffff (=64 TB) direct mapping of all phys.
// memory
// ffffffff80000000 - ffffffff9fffffff (=512 MB) kernel text mapping, from phys
// 0
// We don't consider stack vaiable here. Stack address should be taken care of
// before.
MemoryType getMemType(uint64_t addr) {
if (addr < 4096) {
return NULL_ADDR;
} else if (addr < 0x7fffffffffff) {
return USER_ADDR;
} else if (addr < 0xffffffff80000000) {
return HEAP_ADDR;
} else {
return GLOBAL_ADDR;
}
}
bool KernelAddressSanitizer::getPossibleBaseAddrs(S2EExecutionState *state,
ref<Expr> dstExpr) {
uint64_t base_addr = 0;
if (!m_allocManager->getBaseAddr(state, dstExpr, base_addr)) {
ref<ConstantExpr> base;
ConstraintManager variableConstraints;
// Solution two: Assign zero to all symbolic variables
std::set<ReadExpr *> collection;
collectRead(dstExpr, collection);
foreach2(it, collection.begin(), collection.end()) {
variableConstraints.addConstraint(
E_EQ(*it, E_CONST(0, Expr::Int8)));
}
if (!findMin(state, variableConstraints, dstExpr, base,
state->concolics)) {
getDebugStream(state) << "Failed to get the minimum value of edi\n";
exit(1);
}
getDebugStream(state) << "Min address for dst: " << base << "\n";
base_addr = base->getZExtValue();
}
if (!base_addr) {
m_allocManager->print(this);
}
getDebugStream(state) << "Base addr: " << hexval(base_addr) << "\n";
assert(base_addr && "Failed to get base address from allocManager");
// Find one in busy list
uint64_t objAddr = m_allocManager->find(state, base_addr);
if (objAddr == 0) {
getDebugStream(state)
<< "Failed to find obj for " << hexval(base_addr) << "\n";
return false;
}
std::vector<target_ulong> backtrace;
if (!m_allocManager->getCallsite(objAddr, backtrace)) {
getDebugStream(state)
<< "Failed to find callsite for " << hexval(objAddr) << "\n";
return false;
}
AllocObj vul_obj;
if (!m_allocManager->get(state, objAddr, vul_obj)) {
return false;
}
m_allocManager->concretize(state, vul_obj);
getDebugStream(state) << "Vul address: " << hexval(objAddr) << "\n";
if (base_addr > objAddr + vul_obj.width + 1024) {
getDebugStream(state) << "The vuln object it found looks incorrect!\n";
return false;
}
std::stringstream ss;
ss << "[Busy Object] {";
ss << "\"Callsite\": [";
for (int i = 0; i < backtrace.size(); i++) {
if (i != 0) ss << ", ";
ss << std::to_string(backtrace[i]);
}
ss << "], \"Size\": " << std::to_string(vul_obj.width);
ss << ", \"Allocator\": \"" << m_allocManager->getAllocator(vul_obj)
<< "\"";
ss << ", \"Symbolic\": "
<< (vul_obj.tag == AllocObj::SYMBOLIC ? "true" : "false") << "}\n";
getDebugStream(state) << ss.str();
return true;
}
// unsigned long addr, size_t size, bool is_write, unsigned long ip
void KernelAddressSanitizer::handleReport(S2EExecutionState *state,
PcMonitorState *pcs, uint64_t pc) {
if (m_options->mode == MODE_PRE_ANALYSIS) {
if (m_options->write_only) {
uint64_t isWrite;
m_kernelFunc->readArgument(state, 2, isWrite, false);
if (!isWrite) {
return;
}
}
ref<Expr> addr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
uint64_t ip;
m_kernelFunc->readArgument(state, 3, ip, false);
getDebugStream(state) << "DstExpr: " << addr << "\n";
getDebugStream(state) << "SizeExpr: " << size << "\n";
getDebugStream(state) << "ip: " << hexval(ip) << "\n";
report(state, readExpr<uint64_t>(state, addr),
readExpr<uint64_t>(state, size), false, false, REPORT_STACK_DEPTH, 0);
// check if it's a heap object
uint64_t concrete_addr = readExpr<uint64_t>(state, addr);
switch (getMemType(concrete_addr)) {
case HEAP_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] heap-memory-access\n";
break; // continue to execute
case NULL_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] null-ptr-deref\n";
return;
case USER_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] user-memory-access\n";
return;
case GLOBAL_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] global-memory-access\n";
return;
case STACK_ADDR:
getDebugStream(state) << "[KASAN-CAUSE] stack-memory-access\n";
return;
}
if (!getPossibleBaseAddrs(state, addr)) {
return;
}
uint64_t pid = m_linuxMonitor->getPid(state);
getDebugStream(state) << "Pid: " << pid << "\n";
s2e()->getExecutor()->terminateState(*state,
"Stop tracing at the target");
} else if (m_options->mode == MODE_ANALYSIS) {
uint64_t addr, size, ip;
m_kernelFunc->readArgument(state, 0, addr, false);
m_kernelFunc->readArgument(state, 1, size, false);
m_kernelFunc->readArgument(state, 3, ip, false);
if (m_options->concrete) {
// Try to use our heuristics to get the base address
m_vulAddr = m_vulAddr ? m_vulAddr : addr;
report(state, addr, size, true, false, REPORT_STACK_DEPTH, 0);
// we jump out of the normal control flow later, so handle everything here.
}
m_confirmCounter++;
getDebugStream(state)
<< "[KASAN-CONFIRM] {\"Addr\": " << std::to_string(addr)
<< ", \"ip\": " << std::to_string(ip) << "}\n";
// we may want to stop
m_options->halt = true;
if (m_confirmCounter > m_reportCounter) {
m_confirmCounter -= m_reportCounter;
if (m_confirmCounter > m_options->max_kasan) {
s2e()->getExecutor()->terminateState(*state,
"Stop tracing on KASAN");
}
}
m_reportCounter = 0;
// We dont need report
skipKasan(state);
} else if (m_options->mode == MODE_RESOLVE) {
// skip these functions because they will introduce more constraints that we dont want
skipKasan(state);
}
return;
}
bool KernelAddressSanitizer::report(S2EExecutionState *state, uint64_t dstAddr,
uint64_t len, bool reliable, bool isWrite,
unsigned depth, uint64_t stack) {
std::vector<target_ulong> stacks;
bool ok = m_kernelFunc->dump_stack(state, stack, 0, stacks, depth);
if (!ok)
return false;
std::stringstream ss;
ss << "[KASAN] {";
ss << "\"ip\": [";
for (unsigned i = 0; i < stacks.size(); i++) {
if (i != 0) {
ss << ", ";
}
ss << std::to_string(stacks[i]);
}
ss << "], ";
if (stacks.size() !=
depth) { // our simple heuristic failed to retrieve backtrace
ss << "\"counter\": " << std::to_string(m_pcMonitor->getCounter())
<< ", ";
}
ss << "\"addr\": " << std::to_string(dstAddr) << ", ";
ss << "\"len\": " << std::to_string(len) << ", ";
ss << "\"reliable\": " << (reliable ? "true" : "false") << ", ";
ss << "\"write\": " << (isWrite ? "true" : "false");
ss << "}\n";
m_reportCounter++;
getDebugStream(state) << ss.str();
return ok;
}
bool KernelAddressSanitizer::reportAccess(S2EExecutionState *state,
uint64_t baseAddr, uint64_t dstAddr,
unsigned len, bool isWrite,
unsigned depth) {
std::vector<target_ulong> stacks;
bool ok = m_kernelFunc->dump_stack(state, 0, 0, stacks, depth);
if (!ok)
return false;
std::stringstream ss;
ss << "[Access] {";
ss << "\"base\": " << std::to_string(baseAddr) << ", ";
ss << "\"offset\": " << std::to_string(dstAddr - baseAddr) << ", ";
ss << "\"len\": " << std::to_string(len) << ", ";
ss << "\"isWrite\": " << (isWrite ? "true" : "false") << ", ";
ss << "\"ip\": [";
for (unsigned i = 0; i < stacks.size(); i++) {
if (i != 0) {
ss << ", ";
}
ss << std::to_string(stacks[i]);
}
ss << "]";
ss << "}\n";
getDebugStream(state) << ss.str();
return ok;
}
bool KernelAddressSanitizer::checkMemory(S2EExecutionState *state,
unsigned size, bool isWrite,
uint64_t ret_ip) {
#ifdef DEBUG_KASAN
getDebugStream() << "Check memory at address " << hexval(ret_ip) << "\n";
#endif
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
uint64_t base_addr;
if (m_allocManager->getBaseAddr(state, dstExpr, base_addr)) {
uint64_t dstAddr = readExpr<uint64_t>(state, dstExpr);
AllocObj obj;
if (!m_allocManager->get(state, base_addr, obj, true)) {
return true;
}
if (m_options->track_access) {
reportAccess(state, base_addr, dstAddr, size, isWrite,
DEFAULT_STACK_DEPTH);
}
if (base_addr + obj.width < dstAddr + size) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state) << "Dst: " << hexval(dstAddr)
<< " with size: " << hexval(size) << "\n";
report(state, dstAddr, size, true, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
return false;
}
ref<Expr> len = E_CONST(size, 64);
// It's time consuming, so we'd better not to check every time we
// encounter a seen pc address.
if (m_visit.find(ret_ip) == m_visit.end() &&
!checkSymMemory(state, dstExpr, len, obj, base_addr)) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state)
<< "Potential Overflow-- Dst: " << hexval(dstAddr)
<< " with size: " << hexval(size) << "\n";
// getDebugStream(state) << dstExpr << "\n";
report(state, dstAddr, size, false, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
m_visit.insert({ret_ip, true});
return false;
}
m_visit.insert({ret_ip, true});
}
return true;
}
bool KernelAddressSanitizer::checkMemoryRegion(S2EExecutionState *state,
ref<Expr> &dstExpr,
ref<Expr> &size, bool isWrite,
uint64_t ret_ip) {
#ifdef DEBUG_KASAN
getDebugStream() << "Check memory region at " << hexval(ret_ip) << "\n";
#endif
uint64_t base_addr;
if (m_allocManager->getBaseAddr(state, dstExpr, base_addr)) {
uint64_t dstAddr = readExpr<uint64_t>(state, dstExpr);
uint64_t len = readExpr<uint64_t>(state, size);
AllocObj obj;
if (!m_allocManager->get(state, base_addr, obj, true)) {
return true;
}
if (m_options->track_access) {
reportAccess(state, base_addr, dstAddr, len, isWrite,
DEFAULT_STACK_DEPTH);
}
if (base_addr + obj.width < dstAddr + len) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state) << "Dst: " << hexval(dstAddr)
<< " with size: " << hexval(len) << "\n";
report(state, dstAddr, len, true, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
return false;
}
if (m_visit.find(ret_ip) != m_visit.end() &&
!checkSymMemory(state, dstExpr, size, obj, base_addr)) {
m_vulAddr = m_vulAddr ? m_vulAddr : base_addr;
getDebugStream(state)
<< "Potential Overflow-- Dst: " << hexval(dstAddr)
<< " with size: " << hexval(len) << "\n";
// getDebugStream(state) << dstExpr << "\n";
// getDebugStream(state) << size << "\n";
report(state, dstAddr, len, false, isWrite, DEFAULT_STACK_DEPTH, state->regs()->getSp());
m_visit.insert({ret_ip, true});
return false;
}
m_visit.insert({ret_ip, true});
}
return true;
}
// check potential overflow
bool KernelAddressSanitizer::checkSymMemory(S2EExecutionState *state,
ref<Expr> &dstExpr, ref<Expr> &size,
AllocObj &obj, uint64_t base_addr) {
if (!m_symbolicoverflow) {
return true;
}
Solver *solver = getSolver(state);
bool ok;
// (ReadLSB w64 0x0 v1_alc_0xffff88000a515900_1)
// Add constraint for this
ref<Expr> condition;
ConstraintManager manager;
for (auto c : m_allocManager->AlloConstraint) {
manager.addConstraint(c);
}
for (auto c : state->constraints()) {
manager.addConstraint(c);
}
if (obj.tag == AllocObj::CONCRETE) {
condition = E_LT(E_CONST(base_addr + obj.width, 64),
AddExpr::create(dstExpr, size));
} else {
ref<Expr> len = alignExpr(obj.sym_width, Expr::Int64);
condition = E_LT(
AddExpr::create(obj.sym_width, E_CONST(base_addr, Expr::Int64)),
AddExpr::create(dstExpr, size));
}
if (!solver->mayBeTrue(Query(manager, condition), ok)) {
getDebugStream() << "Error on constraint solving\n";
exit(1);
}
if (ok) {
getDebugStream(state) << "base: " << hexval(base_addr) << "\n";
getDebugStream(state)
<< "Width: " << obj.sym_width << ", " << hexval(obj.width) << "\n";
}
return !ok;
}
bool KernelAddressSanitizer::handleStore1(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 1, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore2(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 2, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore4(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 4, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore8(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 8, true, ret_ip);
}
bool KernelAddressSanitizer::handleStore16(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 16, true, ret_ip);
}
bool KernelAddressSanitizer::handleStoreN(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
return checkMemoryRegion(state, dstExpr, size, true, ret_ip);
}
bool KernelAddressSanitizer::handleLoad1(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 1, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad2(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 2, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad4(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 4, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad8(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 8, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoad16(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
return checkMemory(state, 16, false, ret_ip);
}
bool KernelAddressSanitizer::handleLoadN(S2EExecutionState *state,
uint64_t pc) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
return checkMemoryRegion(state, dstExpr, size, false, ret_ip);
}
// addr, size, write, ret_ip
bool KernelAddressSanitizer::handleCheckMemoryRegion(S2EExecutionState *state,
uint64_t pc) {
uint64_t isWrite;
m_kernelFunc->readArgument(state, 2, isWrite, false);
if (isWrite || !m_options->write_only) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 0, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 1, false);
return checkMemoryRegion(state, dstExpr, size, isWrite, ret_ip);
}
return true;
}
// rdi: source, rsi: destination, edx: len, ecx: csum, r8: src_err_ptr, r9:
// dst_err_ptr
bool KernelAddressSanitizer::handleCsumPartialCopyGeneric(
S2EExecutionState *state, uint64_t pc) {
KASAN_RET_IP
ref<Expr> dstExpr = m_kernelFunc->readSymArgument(state, 1, false);
ref<Expr> size = m_kernelFunc->readSymArgument(state, 2, false);
bool result = checkMemoryRegion(state, dstExpr, size, true, ret_ip);
if (!m_options->write_only) {
ref<Expr> srcExpr = m_kernelFunc->readSymArgument(state, 0, false);
if (!checkMemoryRegion(state, srcExpr, size, false, ret_ip)) {
result = false;
}
}
return result;
}
void KernelAddressSanitizer::decideAddConstraint(uint64_t pc,
bool *allowConstraint) {
if (m_options->mode != MODE_RESOLVE || !allowConstraint) {
return; // remain the same
}
auto it = m_ranges.lower_bound(pc);
if (it == m_ranges.end()) {
return;
}
if (pc >= it->second) {
*allowConstraint = false;
}
}
} // namespace plugins
} // namespace s2e
| 36.626263 | 102 | 0.575053 | Albocoder |
139f817addd4aa231447b311dea4c8e60114174c | 96,209 | cxx | C++ | windows/core/ntgdi/gre/brushobj.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/core/ntgdi/gre/brushobj.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/core/ntgdi/gre/brushobj.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /******************************Module*Header*******************************\
* Module Name: brushobj.cxx
*
* Support for brmemobj.hxx and brushobj.hxx.
*
* Created: 06-Dec-1990 12:02:24
* Author: Walt Moore [waltm]
*
* Copyright (c) 1990-1999 Microsoft Corporation
\**************************************************************************/
#include "precomp.hxx"
extern "C" BOOL bInitBRUSHOBJ();
extern "C" BOOL bInitBrush(int iBrush, COLORREF cr,
DWORD dwHS, PULONG_PTR pdw, BOOL bEnableDither);
#pragma alloc_text(INIT, bInitBRUSHOBJ)
#pragma alloc_text(INIT, bInitBrush)
// Global pointer to the last RBRUSH freed, if any (for one-deep caching).
PRBRUSH gpCachedDbrush = NULL;
PRBRUSH gpCachedEngbrush = NULL;
#define MAX_STOCKBRUSHES 4*1024
LONG gStockBrushFree = MAX_STOCKBRUSHES;
//#define DBG_STOCKBRUSHES 1
#if DBG_STOCKBRUSHES
#define STOCKWARNING DbgPrint
#define STOCKINFO DbgPrint
#else
#define STOCKWARNING
#define STOCKINFO
#endif
extern "C" HFASTMUTEX ghfmMemory;
#if DBG
LONG bo_inits, bo_realize, bo_notdirty, bo_cachehit;
LONG bo_missnotcached, bo_missfg, bo_missbg, bo_misspaltime, bo_misssurftime;
#endif
/****************************Global*Public*Data******************************\
*
* These are the 5 global brushes and 3 global pens maintained by GDI.
* These are retrieved through GetStockObject.
*
* History:
* 20-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
HBRUSH ghbrText;
HBRUSH ghbrBackground;
HBRUSH ghbrGrayPattern;
PBRUSH gpbrText;
PBRUSH gpbrNull;
PBRUSH gpbrBackground;
PPEN gpPenNull;
HBRUSH ghbrDCBrush;
PBRUSH gpbrDCBrush;
HBRUSH ghbrDCPen;
PBRUSH gpbrDCPen;
// Uniqueness so a logical handle can be reused without having it look like
// the same brush as before. We don't really care where this starts.
ULONG BRUSH::_ulGlobalBrushUnique = 0;
ULONG gCacheHandleEntries[GDI_CACHED_HADNLE_TYPES] = {
CACHE_BRUSH_ENTRIES ,
CACHE_PEN_ENTRIES ,
CACHE_REGION_ENTRIES,
CACHE_LFONT_ENTRIES
};
ULONG gCacheHandleOffsets[GDI_CACHED_HADNLE_TYPES] = {
0,
CACHE_BRUSH_ENTRIES,
(
CACHE_BRUSH_ENTRIES +
CACHE_PEN_ENTRIES
),
(
CACHE_BRUSH_ENTRIES +
CACHE_PEN_ENTRIES +
CACHE_PEN_ENTRIES
)
};
/******************************Public*Routine******************************\
* bPEBCacheHandle
*
* Try to place the object(handle) in a free list on the PEB. The objects
* are removed from this list in user mode.
*
* Arguments:
*
* Handle - handle to cache
* HandleType - type of handle to attempt cache
* pBrushattr - pointer to user-mode object
*
* Return Value:
*
* TRUE if handle is cached, FALSE otherwise
*
* History:
*
* 30-Jan-1996 -by- Mark Enstrom [marke]
*
\**************************************************************************/
BOOL
bPEBCacheHandle(
HANDLE Handle,
HANDLECACHETYPE HandleType,
POBJECTATTR pObjectattr,
PENTRY pentry
)
{
BOOL bRet = FALSE;
PBRUSHATTR pBrushattr = (PBRUSHATTR)pObjectattr;
PW32PROCESS pw32Process = W32GetCurrentProcess();
PPEB Peb;
#if !defined(_GDIPLUS_)
ASSERTGDI(((HandleType == BrushHandle) || (HandleType == PenHandle) ||
(HandleType == RegionHandle) ||(HandleType == LFontHandle)
),"hGetPEBHandle: illegal handle type");
Peb = PsGetProcessPeb(pw32Process->Process);
if (Peb != NULL)
{
PGDIHANDLECACHE pCache = (PGDIHANDLECACHE)(&Peb->GdiHandleBuffer[0]);
BOOL bStatus;
//
// Lock Handle cache on PEB
//
LOCK_HANDLE_CACHE(pCache,PsGetCurrentThread(),bStatus);
if (bStatus)
{
//
// are any free slots still availablle
//
if (pCache->ulNumHandles[HandleType] < gCacheHandleEntries[HandleType])
{
ULONG Index = gCacheHandleOffsets[HandleType];
PHANDLE pHandle,pMaxHandle;
//
// calculate handle offset in PEB array
//
pHandle = &(pCache->Handle[Index]);
pMaxHandle = pHandle + gCacheHandleEntries[HandleType];
//
// search array for a free entry
//
while (pHandle != pMaxHandle)
{
if (*pHandle == NULL)
{
//
// for increased robust behavior, increment handle unique
//
pentry->FullUnique += UNIQUE_INCREMENT;
Handle = (HOBJ)MAKE_HMGR_HANDLE((ULONG)(ULONG_PTR)Handle & INDEX_MASK, pentry->FullUnique);
pentry->einfo.pobj->hHmgr = Handle;
//
// store handle in cache and inc stored count
//
*pHandle = Handle;
pCache->ulNumHandles[HandleType]++;
bRet = TRUE;
//
// clear to be deleted and select flags,
// set cached flag
//
pBrushattr->AttrFlags &= ~(ATTR_TO_BE_DELETED | ATTR_CANT_SELECT);
pBrushattr->AttrFlags |= ATTR_CACHED;
break;
}
pHandle++;
}
ASSERTGDI(bRet,"bPEBCacheHandle: count indicates free handle, but none free\n");
}
UNLOCK_HANDLE_CACHE(pCache);
}
}
#endif
return(bRet);
}
/******************************Public*Routine******************************\
* BRUSHMEMOBJ::pbrAllocBrush(bPen)
*
* Base constructor for brush memory object. This constructor is to be
* called by the various public brush constructors only.
*
* History:
* 29-Oct-1992 -by- Michael Abrash [mikeab]
* changed to allocate but not get a handle or lock (so the brush can be fully
* set up before the handle exists, exposing the data to the outside world).
*
* Wed 19-Jun-1991 -by- Patrick Haluptzok [patrickh]
* 0 out the brush.
*
* Thu 06-Dec-1990 12:02:41 -by- Walt Moore [waltm]
* Wrote it.
\**************************************************************************/
PBRUSH BRUSHMEMOBJ::pbrAllocBrush(BOOL bPen)
{
PBRUSH pbrush;
bKeep = FALSE;
// Allocate a new brush or pen
//
// Note: if anyone decides to try turning off zeroinit for performance,
// make sure to initialize the pen's psytle and cstyle to zero. Of
// course, other dependencies may creep in, so do this very very very
// carefully (if you even dare!).
if ((pbrush = (PBRUSH)ALLOCOBJ(bPen ? sizeof(PEN) : sizeof(BRUSH),
BRUSH_TYPE, TRUE)) != NULL)
{
pbrush->pBrushattr(&pbrush->_Brushattr);
pbrush->pIcmDIBList(NULL); // no ICM translated DIBs
pbrush->iUsage(0);
// Set up as initially not caching any realization
pbrush->vSetNotCached(); // no one's trying to cache a realization
// in this logical brush yet
pbrush->crFore((COLORREF)BO_NOTCACHED);
// no cached realization yet (no need to
// worry about crFore not being set when
// someone tries to check for caching,
// because we don't have a handle yet, and
// we'll lock when we do get the handle,
// forcing writes to flush)
pbrush->ulBrushUnique(pbrush->ulGlobalBrushUnique());
// set the uniqueness so the are-you-
// really-dirty check in vInitBrush will
// know this is not the brush in the DC
}
return(pbrush);
}
/******************************Public*Routine******************************\
* BRUSHMEMOBJ::BRUSHMEMOBJ
*
* Create a pattern brush or a DIB brush.
*
* History:
* 29-Oct-1992 -by- Michael Abrash [mikeab]
* changed to get handle only after fully initialized
*
* 14-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
BRUSHMEMOBJ::BRUSHMEMOBJ(HBITMAP hbmClone, HBITMAP hbmClient,BOOL bMono,
FLONG flDIB, FLONG flType, BOOL bPen)
{
if (flDIB == DIB_PAL_COLORS)
{
flType |= BR_IS_DIBPALCOLORS;
}
else if (flDIB == DIB_PAL_INDICES)
{
flType |= BR_IS_DIBPALINDICES;
}
PBRUSH pbrush;
if ((pbp.pbr = pbrush = pbrAllocBrush(bPen)) != NULL)
{
pbrush->crColor(0);
pbrush->ulStyle(HS_PAT);
pbrush->hbmPattern(hbmClone);
pbrush->hbmClient(hbmClient);
pbrush->AttrFlags(0);
pbrush->flAttrs(flType);
if (bMono)
{
pbrush->flAttrs(pbrush->flAttrs() |
(BR_NEED_BK_CLR | BR_NEED_FG_CLR | BR_IS_MONOCHROME));
}
// Now that everything is set up, create the handle and expose this logical
// brush
if (HmgInsertObject(pbrush, HMGR_ALLOC_ALT_LOCK, BRUSH_TYPE) == 0)
{
FREEOBJ(pbrush, BRUSH_TYPE);
pbp.pbr = NULL;
}
}
else
{
WARNING1("Brush allocation failed\n");
}
}
/******************************Public*Routine******************************\
* GreSetSolidBrush
*
* Chicago API to change the color of a solid color brush.
*
* History:
* 19-Apr-1994 -by- Patrick Haluptzok patrickh
* Made it a function that User can call too.
*
* 03-Dec-1993 -by- Eric Kutter [erick]
* Wrote it - bReset.
\**************************************************************************/
BOOL GreSetSolidBrush(HBRUSH hbr, COLORREF clr)
{
return(GreSetSolidBrushInternal(hbr, clr, FALSE, TRUE));
}
BOOL GreSetSolidBrushInternal(
HBRUSH hbr,
COLORREF clr,
BOOL bPen,
BOOL bUserCalled
)
{
BOOL bReturn = FALSE;
BRUSHSELOBJ ebo(hbr);
PBRUSH pbrush = ebo.pbrush();
if (pbrush != NULL)
{
if ((pbrush->flAttrs() & BR_IS_SOLID) &&
((!pbrush->bIsGlobal()) || bUserCalled) &&
((!!pbrush->bIsPen()) == bPen))
{
#if DBG
if (bPen)
{
ASSERTGDI(((PPEN) pbrush)->pstyle() == NULL ||
(pbrush->flAttrs() & BR_IS_DEFAULTSTYLE),
"GreSetSolidBrush - bad attrs\n");
}
#endif
ASSERTGDI(pbrush->hbmPattern() == NULL,
"ERROR how can solid have pat");
PRBRUSH prbrush = (PRBRUSH) NULL;
RBTYPE rbType;
{
//
// Can't do the delete of the RBRUSH under MLOCK, takes too
// long and it may try and grab it again.
//
MLOCKFAST mlo;
//
// User may call when the brush is selected in a DC, but
// the client side should only ever call on a brush that's
// not in use.
//
if ((pbrush->cShareLockGet() == 1) || bUserCalled)
{
bReturn = TRUE;
pbrush->crColor(clr);
HANDLELOCK HandleLock(PENTRY_FROM_POBJ(pbrush), FALSE);
if (HandleLock.bValid())
{
if (pbrush->cShareLockGet() == 1)
{
//
// Nobody is using it and we have the handle lock
// so noone can select it in till we are done. So
// clean out the old realization now.
//
if ((pbrush->crFore() != BO_NOTCACHED) &&
!pbrush->bCachedIsSolid())
{
prbrush = (PRBRUSH) pbrush->ulRealization();
rbType = pbrush->bIsEngine() ? RB_ENGINE
: RB_DRIVER;
}
// Set up as initially not caching any realization
pbrush->vSetNotCached();
// no one's trying to cache a realization
// in this logical brush yet
pbrush->crFore((COLORREF)BO_NOTCACHED);
// no cached realization yet (no need to
// worry about crFore not being set when
// someone tries to check for caching,
// because we don't have a handle yet, and
// we'll lock when we do get the handle,
// forcing writes to flush)
if (!bUserCalled)
{
//
// If it's not User calling we are resetting the
// attributes / type.
//
pbrush->ulStyle(HS_DITHEREDCLR);
pbrush->flAttrs(BR_IS_SOLID | BR_DITHER_OK);
}
else
{
pbrush->vClearSolidRealization();
}
}
else
{
//ASSERTGDI(bUserCalled,
// "Client side is hosed, shouldn't "
// "call this with it still selected");
ASSERTGDI(pbrush->flAttrs() & BR_IS_SOLID,
"ERROR not solid");
ASSERTGDI(pbrush->ulStyle() == HS_DITHEREDCLR,
"ERROR not HS_DI");
//
// Mark this brushes realization as dirty by setting
// it's cache id's to invalid states. Note that if a
// realization hasn't been cached yet this will cause
// no problem either.
//
pbrush->crBack(0xFFFFFFFF);
pbrush->ulPalTime(0xFFFFFFFF);
pbrush->ulSurfTime(0xFFFFFFFF);
//
// This brush is being used other places, check for
// any DC's that have this brush selected in and mark
// their realizations dirty.
//
// Note there is the theoretical possibility that
// somebody is realizing the brush while we are
// marking them dirty and they won't pick up the new
// color. We set the color first and set the
// uniqueness last so that it is extremely unlikely
// (maybe impossible) that someone gets a realization
// that incorrectly thinks it has the proper
// realization. This is fixable by protecting access
// to the realization and cache fields but we aren't
// going to do it for Daytona.
//
// Mark every DC in the system that has this brush
// selected as a dirty brush.
//
HOBJ hobj = (HOBJ) 0;
DC *pdc;
while ((pdc = (DC *) HmgSafeNextObjt(hobj, DC_TYPE))
!= NULL)
{
if (pdc->peboFill()->pbrush() == pbrush)
{
pdc->flbrushAdd(DIRTY_FILL);
}
hobj = (HOBJ) pdc->hGet();
}
}
HandleLock.vUnlock();
}
//
// Set the uniqueness so the are-you-
// really-dirty check in vInitBrush will
// not think an old realization is still valid.
//
pbrush->ulBrushUnique(pbrush->ulGlobalBrushUnique());
}
else
{
WARNING1("Error, SetSolidBrush with cShare != 1");
}
}
if (prbrush)
{
prbrush->vRemoveRef(rbType);
}
}
#if DBG
else
{
if (bPen)
{
WARNING1("bPen True\n");
}
if (pbrush->bIsPen())
{
WARNING1("bIsPen True\n");
}
if (bUserCalled)
{
WARNING1("bUserCalled\n");
}
if (pbrush->bIsGlobal())
{
WARNING1("bIsGlobal\n");
}
if (pbrush->flAttrs() & BR_IS_SOLID)
{
WARNING1("BR_IS_SOLID is set\n");
}
WARNING1("GreSetSolidBrush not passed a solid color brush\n");
}
#endif
}
#if DBG
else
{
WARNING1("GreSetSolidBrush failed to lock down brush\n");
}
#endif
return(bReturn);
}
/******************************Public*Routine******************************\
* GreSetSolidBrushLight:
*
* Private version of GreSetSolidBrush, user can't call
*
* Arguments:
*
* pbrush - pointer to log brush
* clr - new color
* bPen - Brush is a pen
*
* Return Value:
*
* Status
*
* History:
*
* 2-Nov-1995 -by- Mark Enstrom [marke]
*
\**************************************************************************/
BOOL
GreSetSolidBrushLight(
PBRUSH pbrush,
COLORREF clr,
BOOL bPen
)
{
BOOL bReturn = FALSE;
if (pbrush != NULL)
{
if (
(pbrush->flAttrs() & BR_IS_SOLID) &&
(!pbrush->bIsGlobal())
)
{
//
// make sure bPen flag matches brush type
//
if ((bPen != 0) == (pbrush->bIsPen() != 0))
{
#if DBG
if (bPen)
{
ASSERTGDI(((PPEN) pbrush)->pstyle() == NULL ||
(pbrush->flAttrs() & BR_IS_DEFAULTSTYLE),
"GreSetSolidBrushLight - illegal PEN attrs\n");
}
#endif
ASSERTGDI(pbrush->hbmPattern() == NULL,
"ERROR how can solid have pat");
PRBRUSH prbrush = (PRBRUSH) NULL;
RBTYPE rbType;
{
//
// Grab the handle lock to stabize the lock counts.
// Do not attempt to free the realized brush under
// this lock; it may take to long.
//
ASSERTGDI(pbrush->hGet(),
"ERROR brush obj has no handle\n");
HANDLELOCK HandleLock(PENTRY_FROM_POBJ(pbrush),FALSE);
if (HandleLock.bValid())
{
if (pbrush->cShareLockGet() == 1)
{
bReturn = TRUE;
pbrush->crColor(clr);
//
// Nobody is using it and we have the HANDLELOCK
// so noone can select it in till we are done. So
// clean out the old realization now.
//
if ((pbrush->crFore() != BO_NOTCACHED) &&
!pbrush->bCachedIsSolid())
{
prbrush = (PRBRUSH) pbrush->ulRealization();
rbType = pbrush->bIsEngine() ? RB_ENGINE
: RB_DRIVER;
}
//
// Set up as initially not caching any realization
//
pbrush->vSetNotCached();
// no one's trying to cache a realization
// in this logical brush yet
pbrush->crFore((COLORREF)BO_NOTCACHED);
// no cached realization yet (no need to
// worry about crFore not being set when
// someone tries to check for caching,
// because we don't have a handle yet, and
// we'll lock when we do get the handle,
// forcing writes to flush)
//
// we are resetting the attributes / type.
//
if (bPen)
{
pbrush->ulStyle(HS_DITHEREDCLR);
FLONG flOldAttrs = pbrush->flAttrs() &
(BR_IS_PEN | BR_IS_OLDSTYLEPEN);
pbrush->flAttrs(BR_IS_SOLID | flOldAttrs);
}
else
{
pbrush->ulStyle(HS_DITHEREDCLR);
pbrush->flAttrs(BR_IS_SOLID | BR_DITHER_OK);
}
//
// Set the uniqueness so the are-you-
// really-dirty check in vInitBrush will
// not think an old realization is still valid.
//
pbrush->ulBrushUnique(pbrush->ulGlobalBrushUnique());
}
else
{
WARNING1("Error, SetSolidBrush with cShare != 1");
}
HandleLock.vUnlock();
}
}
if (prbrush)
{
prbrush->vRemoveRef(rbType);
}
}
}
#if DBG
else
{
if (pbrush->bIsGlobal())
{
WARNING1("bIsGlobal\n");
}
if (pbrush->flAttrs() & BR_IS_SOLID)
{
WARNING1("BR_IS_SOLID is set\n");
}
WARNING("GreSetSolidBrush not passed a solid color brush\n");
}
#endif
}
#if DBG
else
{
WARNING1("GreSetSolidBrush failed to lock down brush\n");
}
#endif
return(bReturn);
}
/******************************Public*Routine******************************\
* GreGetBrushColor
*
* Call for User to retrieve the color from any brush owned by any process
* so User can repaint the background correctly in full drag. To make sure
* we don't hose an app we need to hold the mult-lock while we do this so
* any operation by the app (such as a Delete) will wait and not fail
* because we're temporarily locking the brush down to peek inside of it.
*
* History:
* 14-Jun-1994 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
COLORREF GreGetBrushColor(HBRUSH hbr)
{
COLORREF clrRet = 0xFFFFFFFF;
//
// Grab the multi-lock so everyone waits while do our quick hack
// to return the brush color.
//
MLOCKFAST mlo;
//
// Lock it down but don't check ownership because we want to succeed
// no matter what.
//
//
// using try except to make sure we will not crash
// when a bad handle passed in.
//
__try
{
PENTRY pentry = &gpentHmgr[HmgIfromH(hbr)];
PBRUSH pbrush = (PBRUSH)(pentry->einfo.pobj);
if (pbrush)
{
if ((pbrush->ulStyle() == HS_SOLIDCLR) ||
(pbrush->ulStyle() == HS_DITHEREDCLR))
{
clrRet = pbrush->crColor();
}
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
WARNING1("GreGetBrushColor - bad handle passed in\n");
}
return(clrRet);
}
/******************************Public*Routine******************************\
* BRUSHMEMOBJ::BRUSHMEMOBJ
*
* Creates hatched brushes and solid color brushes.
*
* History:
* 29-Oct-1992 -by- Michael Abrash [mikeab]
* changed to get handle only after fully initialized
*
* Wed 26-Feb-1992 -by- Patrick Haluptzok [patrickh]
* rewrote to subsume other constructors, add new hatch styles.
*
* Sun 19-May-1991 -by- Patrick Haluptzok [patrickh]
* Wrote it.
\**************************************************************************/
BRUSHMEMOBJ::BRUSHMEMOBJ(COLORREF cr, ULONG ulStyle_, BOOL bPen, BOOL bSharedMem)
{
if (ulStyle_ > HS_NULL)
{
WARNING1("Invalid style type\n");
pbp.pbr = NULL;
return;
}
PBRUSH pbrush;
if ((pbp.pbr = pbrush = pbrAllocBrush(bPen)) == NULL)
{
WARNING1("Brush allocation failed\n");
return;
}
pbrush->crColor(cr);
pbrush->ulStyle(ulStyle_);
pbrush->hbmPattern(0);
pbrush->AttrFlags(0);
if (ulStyle_ < HS_DDI_MAX)
{
// The old hatch brushes have been extended to include all the default
// patterns passed back by the driver. There are 19 default pattens.
pbrush->flAttrs(BR_IS_HATCH | BR_NEED_BK_CLR | BR_IS_MASKING);
goto CreateHandle;
}
// Handle the other brush types
switch(ulStyle_)
{
case HS_SOLIDCLR:
pbrush->flAttrs(BR_IS_SOLID);
break;
case HS_DITHEREDCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_DITHER_OK);
break;
case HS_SOLIDTEXTCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_FG_CLR);
break;
case HS_DITHEREDTEXTCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_FG_CLR | BR_DITHER_OK);
break;
case HS_SOLIDBKCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_BK_CLR);
break;
case HS_DITHEREDBKCLR:
pbrush->flAttrs(BR_IS_SOLID | BR_NEED_BK_CLR | BR_DITHER_OK);
break;
case HS_NULL:
pbrush->flAttrs(BR_IS_NULL);
break;
default:
RIP("ERROR BRUSHMEMOBJ hatches invalid type");
}
// Now that everything is set up, create the handle and expose this logical
// brush
CreateHandle:
if (HmgInsertObject(pbrush, HMGR_ALLOC_ALT_LOCK, BRUSH_TYPE) == 0)
{
FREEOBJ(pbrush, BRUSH_TYPE);
pbp.pbr = NULL;
}
else
{
if (bSharedMem)
{
//
// Setup the user mode BRUSHATTR
//
PBRUSHATTR pUser = (PBRUSHATTR)HmgAllocateObjectAttr();
if (pUser)
{
HANDLELOCK BrushLock;
BrushLock.bLockHobj((HOBJ)pbrush->hHmgr,BRUSH_TYPE);
if (BrushLock.bValid())
{
PENTRY pent = BrushLock.pentry();
//
// fill up the brushattr
//
*pUser = pbrush->_Brushattr;
pent->pUser = (PVOID)pUser;
pbrush->pBrushattr(pUser);
BrushLock.vUnlock();
}
}
}
}
}
/******************************Public*Routine******************************\
* EBRUSHOBJ::vInitBrush
*
* Initializes the brush user object. If the color can be represented
* without dithering, we set iSolidColor.
*
* History:
* Tue 08-Dec-1992 -by- Michael Abrash [mikeab]
* Rewrote for speed.
*
* Sun 23-Jun-1991 -by- Patrick Haluptzok [patrickh]
* Wrote it.
\**************************************************************************/
VOID
EBRUSHOBJ::vInitBrush(
PDC pdc, // current dc or a fake dc with only back/foreground clr info
PBRUSH pbrushIn, // Current logical brush
XEPALOBJ palDC, // Target's DC palette
XEPALOBJ palSurf, // Target's surface palette
SURFACE *pSurface, // Target surface
BOOL bCanDither // If FALSE then never dither
)
{
// Note: If more members of pdc are accessed in the future, then code must be
// added in drvsup.cxx to initialize the members in each place a fake DC
// object is initialized. There's also a fake DC in bDynamicModeChange in
// opendc.cxx which must be updated.
// If the palSurf isn't valid, then the target is a bitmap for a palette
// managed device; therefore the palette means nothing until we actually blt,
// and only the DC palette is relevant. Likewise, if the target is a palette
// managed surface, the brush is realized as indices into the logical palette,
// and unless the logical palette is changed, the brush doesn't need to be
// rerealized. This causes us effectively to check the logical palette time
// twice, but that's cheaper than checking whether we need to check the surface
// palette time and then possibly checking it.
ULONG ulSurfTime = (palSurf.bValid() && !palSurf.bIsPalManaged()) ?
palSurf.ulTime() : 1;
#if DBG
bo_inits++;
#endif
// If the brush really is dirty, we have to set this anyway; if it's not dirty,
// this takes care of the case where the surface has changed out from under us,
// and then a realization is required and we would otherwise fault trying to
// access the target surface structure in the process of realization.
psoTarg1 = pSurface; // surface for which brush is realized
// The journaling code depends on this
// being set correctly. This has the PDEV
// for the device it's selected into.
COLORREF crTextDC = pdc->crTextClr();
COLORREF crBackDC = pdc->crBackClr();
LONG lIcmModeDC = pdc->lIcmMode();
HANDLE hcmXformDC = pdc->hcmXform();
// See if the brush really isn't dirty and doesn't need to be rerealized
if ( ( pbrushIn->ulBrushUnique() == _ulUnique ) &&
(!bCareAboutFg() || (crCurrentText() == crTextDC) ) &&
(!bCareAboutBg() || (crCurrentBack() == crBackDC) ) &&
(palDC.ulTime() == ulDCPalTime()) &&
(ulSurfTime == ulSurfPalTime()) &&
(pbrushIn != gpbrDCBrush)&&
(pbrushIn != gpbrDCPen) &&
(lIcmMode() == lIcmModeDC) &&
(hcmXform() == hcmXformDC) &&
(bCanDither == _bCanDither))
{
#if DBG
bo_notdirty++;
#endif
return;
}
// Get Cached Values
flAttrs = pbrushIn->flAttrs();
// Remember the characteristics of the brush
_pbrush = pbrushIn;
_ulUnique = pbrushIn->ulBrushUnique(); // brush uniqueness
crCurrentText1 = crTextDC; // text color at realization time
crCurrentBack1 = crBackDC; // background color at realization time
_ulDCPalTime = palDC.ulTime(); // DC palette set time at realization time
_ulSurfPalTime = ulSurfTime; // surface palette set time at realization time
_bCanDither = bCanDither; // dither enabled?
// Initialize ICM stuffs
BOOL bCMYKColorSolid = FALSE;
flColorType = 0; // Initialized with zero.
// Set icm modes
if (IS_ICM_ON(lIcmModeDC))
{
BOOL bIcmBrush = FALSE;
// color translation should happen, check we have nessesary data for ICM.
if (flAttrs & (BR_IS_SOLID|BR_IS_HATCH|BR_IS_MONOCHROME))
{
if (IS_ICM_HOST(lIcmModeDC))
{
// DC attributes should have ICM-ed color.
//
// (or with null-ColorTransform, no color translation happen)
if (flAttrs & (BR_IS_SOLID|BR_IS_MONOCHROME))
{
if ((flAttrs & (BR_NEED_FG_CLR|BR_NEED_BK_CLR)) ||
(pbrushIn == gpbrDCBrush) || (pbrushIn == gpbrDCPen))
{
bIcmBrush = TRUE;
}
}
if (bIcmBrush == FALSE)
{
if (pbrushIn->bIsPen())
{
if ((hcmXformDC == NULL) || pdc->bValidIcmPenColor())
{
bIcmBrush = TRUE;
}
else
{
ICMMSG(("vInitBrush():ERROR: No ICMed pen color for this brush\n"));
}
}
else
{
if ((hcmXformDC == NULL) || pdc->bValidIcmBrushColor())
{
bIcmBrush = TRUE;
}
else
{
ICMMSG(("vInitBrush():ERROR: No ICMed brush color for this brush\n"));
}
}
}
}
else // other ICM modes (Device and Apps)
{
bIcmBrush = TRUE;
}
}
else if (flAttrs & BR_IS_DIB)
{
if (IS_ICM_HOST(lIcmModeDC))
{
// Brush should have ICM-ed DIB
//
// (or with null-ColorTransform, no color translation happen)
if ((hcmXformDC == NULL) || pbrushIn->hFindIcmDIB(hcmXformDC))
{
bIcmBrush = TRUE;
}
else
{
ICMMSG(("vInitBrush():ERROR: No ICMed DIB for this brush\n"));
}
}
else // other ICM modes (Device and Apps)
{
bIcmBrush = TRUE;
}
}
else
{
// Other stlyes, no ICM
}
if (bIcmBrush)
{
lIcmMode(lIcmModeDC); // ICM mode
hcmXform(hcmXformDC); // ICM molor Transform handle
// setup colortype flag.
if (bIsAppsICM() || bIsHostICM())
{
flColorType |= BR_HOST_ICM;
}
else if (bIsDeviceICM())
{
flColorType |= BR_DEVICE_ICM;
}
// If the brush is solid, iSolidColor will have CMKY color. Otherwise,
// iSolidColor will be 0xFFFFFFFF and flColorType does not have BR_CMYKCOLOR.
bCMYKColorSolid = (bIsCMYKColor() && (flAttrs & BR_IS_SOLID));
if (bCMYKColorSolid)
{
flColorType |= BR_CMYKCOLOR; // color type is CMYK color
}
}
else
{
ICMMSG(("vInitBrush():This brush is not ICMed\n"));
lIcmMode(DC_ICM_OFF); // ICM mode
hcmXform(NULL); // ICM molor Transform handle
}
}
else
{
lIcmMode(DC_ICM_OFF); // ICM mode
hcmXform(NULL); // ICM molor Transform handle
}
// Get the target PDEV
PDEVOBJ po(pSurface->hdev());
ASSERTGDI(po.bValid(), "ERROR BRUSHOBJ PDEVOBJ");
// Set palettes
palDC1.ppalSet(palDC.ppalGet());
palSurf1.ppalSet(palSurf.ppalGet());
palMeta1.ppalSet(po.ppalSurfNotDynamic());
_iMetaFormat = po.iDitherFormatNotDynamic();
ASSERTGDI(pSurface != NULL, "ERROR BRUSHOBJ::bInit0");
ASSERTGDI(palDC.bValid(), "ERROR BRUSHOBJ::bInit4");
// Clean up what was already here
// If this brush object had an engine brush realization, get rid of it
if (pengbrush1 != (PENGBRUSH) NULL)
{
PRBRUSH prbrush = pengbrush1; // point to engine brush realization
prbrush->vRemoveRef(RB_ENGINE); // decrement the reference count on the
// realization and free the brush if
// this is the last reference
pengbrush1 = NULL; // mark that there's no realization
}
// If this brush object had a device brush realization, get rid of it
if (pvRbrush != (PVOID) NULL)
{
PRBRUSH prbrush = (PDBRUSH)DBRUSHSTART(pvRbrush);
// point to DBRUSH (pvRbrush points to
// realization, which is at the end of DBRUSH)
prbrush->vRemoveRef(RB_DRIVER);
// decrement the reference count on the
// realization and free the brush if
// this is the last reference
pvRbrush = NULL; // mark that there's no realization
}
// Remember the color so we do the realization code correctly later
// if it's a dithered brush. We may need this even if we have
// a hit in the cache since we have driver/engine distinction.
if (flAttrs & BR_IS_SOLID)
{
if (flAttrs & BR_NEED_FG_CLR)
{
crRealize = crCurrentText(); // use text brush
if (bIsHostICM())
crRealizeOrignal = pdc->ulTextClr();
}
else if (flAttrs & BR_NEED_BK_CLR)
{
crRealize = crCurrentBack(); // use back brush
if (bIsHostICM())
crRealizeOrignal = pdc->ulBackClr();
}
else if (pbrushIn == gpbrDCBrush)
{
crRealize = pdc->crDCBrushClr(); // use DC brush
if (bIsHostICM())
crRealizeOrignal = pdc->ulDCBrushClr();
}
else if (pbrushIn == gpbrDCPen)
{
crRealize = pdc->crDCPenClr(); // use DC pen
if (bIsHostICM())
crRealizeOrignal = pdc->ulDCPenClr();
}
else
{
crRealize = pbrushIn->crColor();
if (bIsHostICM())
{
crRealizeOrignal = crRealize;
if (pbrushIn->bIsPen())
{
if (pdc->bValidIcmPenColor())
{
crRealize = pdc->crIcmPenColor(); // use ICM translated pen
}
}
else
{
if (pdc->bValidIcmBrushColor())
{
crRealize = pdc->crIcmBrushColor(); // use ICM translated brush
}
}
}
}
}
else if (flAttrs & BR_IS_HATCH)
{
crRealize = pbrushIn->crColor();
if (bIsHostICM())
{
crRealizeOrignal = crRealize;
if (pbrushIn->bIsPen())
{
if (pdc->bValidIcmPenColor())
{
crRealize = pdc->crIcmPenColor();
}
}
else
{
if (pdc->bValidIcmBrushColor())
{
crRealize = pdc->crIcmBrushColor();
}
}
}
}
// See if there's a cached realization that we can use
// Note that the check for crFore MUST come first, because if and only if
// that field is not BO_NOTCACHED is there a valid cached realization.
#if DBG
bo_realize++;
if ( (pbrushIn->crFore() == BO_NOTCACHED) )
{
bo_missnotcached++;
}
else if ( pbrushIn->bCareAboutFg() &&
(pbrushIn->crFore() != crTextDC) )
{
bo_missfg++;
}
else if (pbrushIn->bCareAboutBg() &&
(pbrushIn->crBack() != crBackDC) )
{
bo_missbg++;
}
else if ( pbrushIn->ulPalTime() != ulDCPalTime() )
{
bo_misspaltime++;
}
else if ( pbrushIn->ulSurfTime() != ulSurfPalTime() )
{
bo_misssurftime++;
}
else
{
bo_cachehit++;
}
#endif
if (
(pbrushIn->crFore() != BO_NOTCACHED) &&
(
(!pbrushIn->bCareAboutFg()) ||
(pbrushIn->crFore() == crTextDC)
) &&
(
(!pbrushIn->bCareAboutBg()) ||
(pbrushIn->crBack() == crBackDC)
) &&
(pbrushIn->ulPalTime() == ulDCPalTime()) &&
(pbrushIn->ulSurfTime() == ulSurfPalTime()) &&
(pbrushIn->hdevRealization() == po.hdev()) &&
(pbrushIn != gpbrDCBrush) &&
(pbrushIn != gpbrDCPen)
)
{
// Uncache the realization according to the realization type (solid,
// driver realization, or engine realization)
if (pbrushIn->bCachedIsSolid())
{
// Retrieve the cached solid color and done
iSolidColor = (ULONG)pbrushIn->ulRealization();
crPaletteColor = pbrushIn->crPalColor();
}
else
{
// See whether this is an engine or driver realization
PRBRUSH prbrush = (PRBRUSH)pbrushIn->ulRealization();
if (pbrushIn->bIsEngine())
{
pengbrush1 = (PENGBRUSH)prbrush;
}
else
{
// Skip over the RBRUSH at the start of the DBRUSH, so that the
// driver doesn't see that
pvRbrush = (PVOID)(((PDBRUSH)prbrush)->aj);
}
// Whether this was an engine or driver realization, now we've got
// it selected into another DC, so increment the reference count
// so it won't get deleted until it's no longer selected into any
// DC and the logical brush no longer exists
prbrush->vAddRef();
// Indicate that this is a pattern brush
iSolidColor = 0xffffffff;
crPaletteColor = pbrushIn->crPalColor();
}
// Nothing more to do once we've found that the realization is cached;
// this tells us all we hoped to find out in this call, either the
// solid color for the realization or else that the realization isn't
// solid (in which case we probably found the realization too, although
// if the cached realization is driver and this time the engine will do
// the drawing, or vice-versa, the cached realization won't help us)
return;
}
// If brush isn't based on color (if it is a bitmap or hatch), we're done
// here, because all we want to do is set iSolidColor if possible
if (!(flAttrs & BR_IS_SOLID))
{
iSolidColor = crPaletteColor = 0xffffffff;
return;
}
// See if we can find exactly the color we want
if (bCMYKColorSolid)
{
// crRealize is CMKY color just set it to iSolidColor
iSolidColor = crPaletteColor = crRealize;
}
else if (po.bCapsForceDither() && bCanDither)
{
// printer drivers may set the FORCEDITHER flag. In this case, we always
// want to dither brushes, even if they map to a color in the drivers palette.
iSolidColor = 0xffffffff;
crPaletteColor = crRealize;
}
else
{
iSolidColor =
ulGetMatchingIndexFromColorref(
palSurf,
palDC,
crRealize
);
crPaletteColor = rgbFromColorref(palSurf,
palDC,
crRealize
);
}
// Under CMYK color context, there is no dither.
if ((iSolidColor == 0xFFFFFFFF) && (!bCMYKColorSolid))
{
// Not an exact match. If we can dither, then we're done for now; we'll
// realize the brush when the driver wants it, so if all conditions are
// met for dithering this brush, then we're done
// we dither the brush if the caller says we can and if either the brush
// says it is ditherable or the driver has requested dithering.
if (((flAttrs & BR_DITHER_OK) || (po.bCapsForceDither())) &&
bCanDither)
{
// ...and the PDEV allows color dithering and either the bitmap is
// for a palette managed device, or if the surface and device
// palettes are the same palette, or if the destination surface is
// monochrome and the pdev has hooked mono dithering.
//
// Note: There is a dynamic mode change synchronization hole here
// between the time we check GCAPS_COLOR_DITHER/MONO_DITHER
// and the time that we go to actually realize the brush --
// the driver's capabilities may have changed in the mean
// time. Note that this will happen only when drawing to
// DIB based compatible bitmaps. Since it will be rare, and
// since we won't fall over, I'm letting it through...
if (
(
(
(!palSurf.bValid()) ||
(palSurf.ppalGet() == po.ppalSurfNotDynamic())
) &&
(po.flGraphicsCapsNotDynamic() & GCAPS_COLOR_DITHER)
) ||
(palSurf.bIsMonochrome() &&
(po.flGraphicsCapsNotDynamic() & GCAPS_MONO_DITHER)
)
)
{
// ...then we can dither this brush, so we can't set iSolidColor
// and we're done. Dithering will be done when the driver
// requests realization
//
crPaletteColor = crRealize;
return;
}
}
// We can't dither and there's no exact match, so find the nearest
// color and that'll have to do
if (pSurface->iFormat() == BMF_1BPP)
{
// For monochrome surface, we'll have background mapped to
// background and everything else mapped to foreground.
iSolidColor = ulGetNearestIndexFromColorref(
palSurf,
palDC,
crBackDC,
SE_DONT_SEARCH_EXACT_FIRST
);
crPaletteColor = rgbFromColorref(palSurf,
palDC,
crBackDC);
if (crBackDC != crRealize)
{
iSolidColor = 1 - iSolidColor;
// Obtain corresponding color from index.
PAL_ULONG ulPalTemp;
ulPalTemp.pal = palSurf.palentryGet(iSolidColor);
crPaletteColor = ulPalTemp.ul;
}
}
else
{
iSolidColor = ulGetNearestIndexFromColorref(
palSurf,
palDC,
crRealize,
SE_DONT_SEARCH_EXACT_FIRST
);
crPaletteColor = rgbFromColorref(palSurf,
palDC,
crRealize);
}
}
// See if we can cache this brush color in the logical brush; we can't if
// another realization has already been cached in the logical brush
// See vTryToCacheRealization, in BRUSHDDI.CXX, for a detailed explanation
// of caching in the logical brush
if ( !pbrushIn->bCacheGrabbed() )
{
// Try to grab the "can cache" flag; if we don't get it, someone just
// sneaked in and got it ahead of us, so we're out of luck and can't
// cache
if ( pbrushIn->bGrabCache() )
{
// We got the "can cache" flag, so now we can cache this realization
// in the logical brush
// These cache ID fields must be set before crFore, because crFore
// is the key that indicates when the cached realization is valid.
// If crFore is -1 when the logical brush is being realized, we
// just go realize the brush; if it's not -1, we check the cache ID
// fields to see if we can use the cached fields.
// InterlockedExchange() is used below to set crFore to make sure
// the cache ID fields are set before crFore
pbrushIn->crBack(crCurrentBack1);
pbrushIn->ulPalTime(ulDCPalTime());
pbrushIn->ulSurfTime(ulSurfPalTime());
pbrushIn->ulRealization(iSolidColor);
pbrushIn->crPalColor(crPaletteColor);
pbrushIn->SetSolidRealization();
// This must be set last, because once it's set, other selections
// of this logical brush will attempt to use the cached brush. The
// use of InterlockedExchange in this method enforces this
pbrushIn->crForeLocked(crCurrentText1);
// The realization is now cached in the logical brush
}
}
return;
}
/******************************Public*Routine******************************\
* EBRUSHOBJ::vNuke()
*
* Clean up framed EBRUSHOBJ
*
* History:
* 20-Mar-1992 -by- Donald Sidoroff [donalds]
* Wrote it.
\**************************************************************************/
VOID EBRUSHOBJ::vNuke()
{
if (pengbrush1 != (PENGBRUSH) NULL)
{
PRBRUSH prbrush = pengbrush1; // point to engine brush realization
prbrush->vRemoveRef(RB_ENGINE); // decrement the reference count on the
// realization and free the brush if
// this is the last reference
}
if (pvRbrush != (PVOID) NULL)
{
PRBRUSH prbrush = (PDBRUSH)DBRUSHSTART(pvRbrush);
// point to DBRUSH (pvRbrush points to
// realization, which is at the end of DBRUSH)
prbrush->vRemoveRef(RB_DRIVER);
// decrement the reference count on the
// realization and free the brush if
// this is the last reference
}
}
// This is the brusheng.cxx section
/******************************Public*Routine******************************\
* bInitBRUSHOBJ
*
* Initializes the default brushes and and the dclevel default values for
* brushes and pens.
*
* Explanation of the NULL brush (alias Hollow Brush)
* The Null brush is special. Only 1 is ever created
* (at initialization time in hbrNull). The only API's for
* getting a Null brush are CreateBrushIndirect and GetStockObject which
* both return "the 1 and only 1" Null brush. A Null brush is never
* realized by a driver or the engine. No output call should ever occur
* that requires a brush if the brush is NULL, the engine should stop
* these before they get to the driver.
*
* History:
* 20-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
extern "C" BOOL bInitBrush(
int iBrush,
COLORREF cr,
DWORD dwHS,
PULONG_PTR pdw,
BOOL bEnableDither
)
{
BOOL bSuccess = FALSE;
BRUSHMEMOBJ brmo(cr,dwHS,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
if (bEnableDither)
brmo.vEnableDither();
if (pdw)
*pdw = (ULONG_PTR)brmo.pbrush();
bSetStockObject(brmo.hbrush(),iBrush);
// init DcAttrDefault brush
if (iBrush == WHITE_BRUSH)
{
DcAttrDefault.hbrush = brmo.hbrush();
}
bSuccess = TRUE;
}
else
{
#if DBG
DbgPrint("couldn't create default brush %lx, %lx\n",cr,iBrush);
#endif
return(FALSE);
}
return(bSuccess);
}
BOOL bInitBRUSHOBJ()
{
if (!bInitBrush(WHITE_BRUSH,(COLORREF)RGB(0xFF,0xFF,0xFF),
HS_DITHEREDCLR,(PULONG_PTR)&dclevelDefault.pbrFill,FALSE) ||
!bInitBrush(BLACK_BRUSH, (COLORREF)RGB(0x0, 0x0, 0x0), HS_DITHEREDCLR,NULL,FALSE) ||
!bInitBrush(GRAY_BRUSH, (COLORREF)RGB(0x80,0x80,0x80),HS_DITHEREDCLR,NULL,TRUE) ||
!bInitBrush(DKGRAY_BRUSH,(COLORREF)RGB(0x40,0x40,0x40),HS_DITHEREDCLR,NULL,TRUE) ||
!bInitBrush(LTGRAY_BRUSH,(COLORREF)RGB(0xc0,0xc0,0xc0),HS_DITHEREDCLR,NULL,TRUE) ||
!bInitBrush(NULL_BRUSH, (COLORREF)0,HS_NULL,(PULONG_PTR)&gpbrNull,FALSE))
{
return(FALSE);
}
// Init default Null Pen
{
BRUSHMEMOBJ brmo((COLORREF) 0, HS_NULL, TRUE, FALSE); // TRUE signifies a pen
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_NULL);
brmo.lWidthPen(1);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),NULL_PEN);
gpPenNull = (PPEN)brmo.pbrush();
}
else
{
WARNING("Failed Null Pen");
return(FALSE);
}
}
// Init default Black Pen
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0,0,0)), HS_DITHEREDCLR, TRUE, FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_SOLID);
brmo.lWidthPen(0);
brmo.l_eWidthPen(IEEE_0_0F);
brmo.iJoin(JOIN_ROUND);
brmo.iEndCap(ENDCAP_ROUND);
brmo.pstyle((PFLOAT_LONG) NULL);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),BLACK_PEN);
DcAttrDefault.hpen = (HPEN)brmo.hbrush();
dclevelDefault.pbrLine = brmo.pbrush();
}
else
{
WARNING("failed black pen");
return(FALSE);
}
}
// Init default White Pen
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0xFF,0xFF,0xFF)), HS_DITHEREDCLR, TRUE, FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_SOLID);
brmo.lWidthPen(0);
brmo.l_eWidthPen(IEEE_0_0F);
brmo.iJoin(JOIN_ROUND);
brmo.iEndCap(ENDCAP_ROUND);
brmo.pstyle((PFLOAT_LONG) NULL);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),WHITE_PEN);
}
else
{
WARNING("Failed white pen");
return(FALSE);
}
}
// Init the stock DC Pen
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0,0,0)), HS_DITHEREDCLR, TRUE, FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
brmo.vSetOldStylePen();
brmo.flStylePen(PS_SOLID);
brmo.lWidthPen(0);
brmo.l_eWidthPen(IEEE_0_0F);
brmo.iJoin(JOIN_ROUND);
brmo.iEndCap(ENDCAP_ROUND);
brmo.pstyle((PFLOAT_LONG) NULL);
HmgModifyHandleType((HOBJ)MODIFY_HMGR_TYPE(brmo.hbrush(),LO_PEN_TYPE));
bSetStockObject(brmo.hbrush(),DC_PEN);
ghbrDCPen = brmo.hbrush();
gpbrDCPen = brmo.pbrush();
}
else
{
WARNING("Failed DC pen");
return(FALSE);
}
}
// init the text brush
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0,0,0)),HS_DITHEREDTEXTCLR,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
ghbrText = brmo.hbrush();
gpbrText = brmo.pbrush();
}
else
{
WARNING("Could not create default text brush");
return(FALSE);
}
}
// init the background brush
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0xff,0xff,0xff)),HS_DITHEREDBKCLR,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
ghbrBackground = brmo.hbrush();
gpbrBackground = brmo.pbrush();
}
else
{
WARNING("Could not create default background brush");
return(FALSE);
}
}
// init the global pattern gray brush
{
static WORD patGray[8] = { 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa };
HBITMAP hbmGray;
hbmGray = GreCreateBitmap(8, 8, 1, 1, (LPBYTE)patGray);
if (hbmGray == (HBITMAP) 0)
{
WARNING1("bInitBRUSHOBJ failed GreCreateBitmap\n");
return(FALSE);
}
ghbrGrayPattern = GreCreatePatternBrush(hbmGray);
if (ghbrGrayPattern == (HBRUSH) 0)
{
WARNING1("bInitBRUSHOBJ failed GreCreatePatternBrush\n");
return(FALSE);
}
GreDeleteObject(hbmGray);
GreSetBrushOwnerPublic((HBRUSH)ghbrGrayPattern);
}
// init the stock DC brush
{
BRUSHMEMOBJ brmo((COLORREF) (RGB(0xff,0xff,0xff)),HS_DITHEREDCLR,FALSE,FALSE);
if (brmo.bValid())
{
brmo.vKeepIt();
brmo.vGlobal();
bSetStockObject(brmo.hbrush(), DC_BRUSH);
ghbrDCBrush = brmo.hbrush();
gpbrDCBrush = brmo.pbrush();
}
else
{
WARNING("Could not create direct dc brush");
return(FALSE);
}
}
return(TRUE);
}
/******************************Public*Routine******************************\
* GreSelectBrush
*
* Selects the given brush into the given DC. Fast SelectObject
*
* History:
* Thu 21-Oct-1993 -by- Patrick Haluptzok [patrickh]
* wrote it.
\**************************************************************************/
HBRUSH GreSelectBrush(HDC hdc, HBRUSH hbrush)
{
HBRUSH hbrReturn = (HBRUSH) 0;
//
// Try to lock the DC. If we fail, we just return failure.
//
XDCOBJ dco(hdc);
if (dco.bValid())
{
//
// call DC locked version
//
hbrReturn = GreDCSelectBrush(dco.pdc,hbrush);
dco.vUnlockFast();
}
return(hbrReturn);
}
/******************************Public*Routine******************************\
* GreDCSelectBrush
*
* Select brush with dc already locked
*
* Arguments:
*
* pdc - locked DC pointer
* hbrush - brush to select
*
* Return Value:
*
* Old hbrush or NULL
*
* History:
*
* 19-May-1995 : copied from GreSelectBrush
*
\**************************************************************************/
HBRUSH
GreDCSelectBrush(
PDC pdc,
HBRUSH hbrush
)
{
HBRUSH hbrReturn = (HBRUSH) 0;
PBRUSH pbrush = NULL;
XDCOBJ dco;
dco.pdc = pdc;
if (dco.bValid())
{
HBRUSH hbrOld;
//
// The DC is locked. Set the return value to the old brush in the DC.
//
hbrOld = (HBRUSH) (dco.pdc->pbrushFill())->hGet();
//
// the return value should be the one cached in the dc
//
hbrReturn = dco.pdc->hbrush();
//
// If the new brush is the same as the old brush, nothing to do.
//
if (DIFFHANDLE(hbrush,hbrOld))
{
//
// Try to lock down the logical brush so we can get the pointer out.
//
pbrush = (BRUSH *)HmgShareCheckLock((HOBJ)hbrush, BRUSH_TYPE);
if (pbrush)
{
//
// Undo the lock from when the brush was selected.
//
DEC_SHARE_REF_CNT_LAZY0(dco.pdc->pbrushFill());
//
// Changing pbrushfill, set flag to force re-realization
//
dco.ulDirtyAdd(DIRTY_FILL);
//
// Save the pointer to the logical brush in the DC. We don't
// unlock the logical brush, because the alt lock count in the
// logical brush is the reference count for DCs in which the brush
// is currently selected; this protects us from having the actual
// logical brush deleted while it's selected into a DC, and allows
// us to reference the brush with a pointer rather than having to
// lock down the logical brush every time.
//
dco.pdc->pbrushFill(pbrush);
}
else
{
WARNING1("SelectBrush got invalid brush handle\n");
hbrReturn = NULL;
}
}
else
{
pbrush = dco.pdc->pbrushFill();
}
if (pbrush != NULL)
{
if (hbrReturn != NULL)
{
//
// must still check brush for new color
//
PBRUSHATTR pUser = pbrush->_pBrushattr;
//
// if the brush handle is a cached solid brush,
// call GreSetSolidBrushInternal to change the color
//
if (pUser != &pbrush->_Brushattr)
{
if (pUser->AttrFlags & ATTR_NEW_COLOR)
{
//
// force re-realization in case handle was same
//
dco.ulDirtyAdd(DIRTY_FILL);
//
// set the new color for the cached brush.
// Note: since pbrush is pulled straight
// from the DC, it's reference count will
// be 1, which is needed by SetSolidBrush
//
if (!GreSetSolidBrushLight(pbrush,pUser->lbColor,FALSE))
{
WARNING1("GreSyncbrush failed to setsolidbrushiternal\n");
}
pUser->AttrFlags &= ~ATTR_NEW_COLOR;
}
}
}
dco.pdc->hbrush(hbrush);
dco.pdc->ulDirtySub(DC_BRUSH_DIRTY);
}
}
return(hbrReturn);
}
/******************************Public*Routine******************************\
* GreDCSelectPen
* Selects a hpen into the given pdc
*
* Arguments:
*
* pdc - locked dc
* hpen - hpen to select
*
* Return Value:
*
* old hpen
*
* History:
*
* 29-Jan-1996 -by- Mark Enstrom [marke]
*
\**************************************************************************/
HPEN GreDCSelectPen(
PDC pdc,
HPEN hpen
)
{
HPEN hpReturn = (HPEN) NULL;
PPEN ppen = NULL;
//
// Try to lock the DC. If we fail, we just return failure.
//
XDCOBJ dco;
dco.pdc = pdc;
if (dco.bValid())
{
HPEN hpOld;
BOOL bRealize = FALSE;
//
// hpOld is the pen (LINE BRUSH) currently realized in the DC
//
hpOld = (HPEN) (dco.pdc->pbrushLine())->hGet();
//
// Set the return value to the old pen in the DCATTR.
// This is the last hpen the user selected
//
hpReturn = (HPEN)dco.pdc->hpen();
//
// If the new pen is the same as the old pen, nothing to do.
//
if (DIFFHANDLE(hpen, hpOld))
{
//
// Try to lock down the logical brush so we can get the pointer out.
//
ppen = (PEN *)HmgShareCheckLock((HOBJ)hpen, BRUSH_TYPE);
if (ppen && ppen->bIsPen())
{
//
// Undo the lock from when the pen was selected.
//
DEC_SHARE_REF_CNT_LAZY0(dco.pdc->pbrushLine());
//
// Mark line relization is invalid.
//
dco.ulDirtyAdd(DIRTY_LINE);
//
// Save the pointer to the logical brush in the DC. We don't
// unlock the logical brush, because the alt lock count in the
// logical brush is the reference count for DCs in which the brush
// is currently selected; this protects us from having the actual
// logical brush deleted while it's selected into a DC, and allows
// us to reference the brush with a pointer rather than having to
// lock down the logical brush every time.
//
dco.pdc->pbrushLine(ppen);
//
// The pen changed, so realize the new LINEATTRS, based on
// the current world transform.
//
bRealize = TRUE;
}
else
{
WARNING1("SelectPen got invalid pen handle\n");
//
// If this is not pen, can't select it as pen.
//
if (ppen)
{
DEC_SHARE_REF_CNT(ppen);
ppen = NULL;
}
hpReturn = NULL;
}
}
else
{
ppen = (PPEN)dco.pdc->pbrushLine();
}
//
// In case the handle stays the same, but the pen is new
// due to re-use of a user hpen, so re-realize it.
//
if (ppen != (PPEN) NULL)
{
if (hpReturn != NULL)
{
PBRUSHATTR pUser = ppen->_pBrushattr;
//
// if the brush handle is a cached solid brush,
// call GreSetSolidBrushInternal to change the color
//
if (pUser != &ppen->_Brushattr)
{
if (pUser->AttrFlags & ATTR_NEW_COLOR)
{
//
// set the new color for the cached brush.
// Note: since pbrush is pulled straight
// from the DC, it's reference count will
// be 1, which is needed by SetSolidBrush
//
if (!GreSetSolidBrushLight(ppen,pUser->lbColor,TRUE))
{
WARNING ("GreDCSelectPen failed to setsolidbrushiternal\n");
}
dco.ulDirtyAdd(DIRTY_LINE);
pUser->AttrFlags &= ~ATTR_NEW_COLOR;
bRealize = TRUE;
}
}
if (bRealize)
{
//
// The pen changed, so realize the new LINEATTRS, based on
// the current world transform.
//
EXFORMOBJ exo(dco, WORLD_TO_DEVICE);
dco.pdc->vRealizeLineAttrs(exo);
LINEATTRS *pla = dco.plaRealized();
}
}
dco.pdc->hpen(hpen);
dco.pdc->ulDirtySub(DC_PEN_DIRTY);
}
}
return(hpReturn);
}
/******************************Public*Routine******************************\
* GreSelectPen
*
* Selects the given brush into the given DC. Fast SelectObject
*
* History:
* Thu 21-Oct-1993 -by- Patrick Haluptzok [patrickh]
* wrote it.
\**************************************************************************/
HPEN GreSelectPen(HDC hdc, HPEN hpen)
{
HPEN hpenReturn = (HPEN) 0;
//
// Try to lock the DC. If we fail, we just return failure.
//
XDCOBJ dco(hdc);
if (dco.bValid())
{
//
// call DC locked version
//
hpenReturn = GreDCSelectPen(dco.pdc,hpen);
dco.vUnlockFast();
}
return(hpenReturn);
}
/******************************Public*Routine******************************\
* bDeleteBrush
*
* This will delete the brush. The brush can only be deleted if it's not
* global and not being used by anyone else.
*
* History:
*
* 7-Feb-1996 -by- Mark Enstrom [marke]
* Add PEB caching for brush and pen objects
* 23-May-1991 -by- Patrick Haluptzok patrickh
* Wrote it.
\**************************************************************************/
BOOL bDeleteBrush(HBRUSH hbrush, BOOL bCleanup)
{
PBRUSHPEN pbp;
BOOL bReturn = TRUE;
HBRUSH hbrushNew;
BOOL bDelete = TRUE;
PBRUSHATTR pUser = NULL;
PENTRY pentTmp;
BOOL bMakeNonStock = FALSE;
//
// check handle for user-mode brush
//
if (!bCleanup)
{
HANDLELOCK BrushLock;
BrushLock.bLockHobj((HOBJ)hbrush,BRUSH_TYPE);
if (BrushLock.bValid())
{
POBJ pobj = BrushLock.pObj();
pUser = (PBRUSHATTR)BrushLock.pUser();
ASSERTGDI(pobj->cExclusiveLock == 0, "deletebrush - exclusive lock not 0\n");
//
// If Brush is still in use, mark for lazy deletion and return true
//
if (BrushLock.ShareCount() > 0)
{
((PBRUSH)pobj)->AttrFlags(ATTR_TO_BE_DELETED);
bDelete = FALSE;
}
else if (pUser != (PBRUSHATTR)NULL)
{
if (!(pUser->AttrFlags & ATTR_CACHED))
{
BOOL bPen = ((PPEN)pobj)->bIsPen();
INT iType = LO_TYPE(hbrush);
#if DBG
//
// make sure handle type agrees with bPen
//
if (bPen)
{
ASSERTGDI(((iType == LO_PEN_TYPE) || (iType == LO_EXTPEN_TYPE)),
"bDeleteBrush Error: PEN TYPE NOT LO_PEN OR LO_EXTPEN");
}
else
{
ASSERTGDI((iType == LO_BRUSH_TYPE),
"bDeleteBrush error: BRUSH type not LO_BRUSH_TYPE");
}
#endif
//
// try to cache the solid brush
// don't cache LO_EXTPEN_TYPE
//
if ((((PBRUSH)pobj)->flAttrs() & BR_IS_SOLID) &&
(!bPen || iType != LO_EXTPEN_TYPE))
{
BOOL bStatus;
bStatus = bPEBCacheHandle(hbrush,bPen?PenHandle:BrushHandle,(POBJECTATTR)pUser,(PENTRY)BrushLock.pentry());
if (bStatus)
{
bDelete = FALSE;
}
}
}
else
{
//
// brush is already cached
//
WARNING1("Trying to delete brush marked as cached\n");
bDelete = FALSE;
}
}
if (bDelete)
{
if (bMakeNonStock = ((PBRUSH)pobj)->bIsMakeNonStock())
{
((PBRUSH)pobj)->vClearMakeNonStock();
}
}
BrushLock.vUnlock();
}
}
if (bDelete)
{
if (bMakeNonStock)
{
STOCKINFO("Brush(%p) is marked MakeNonStock. Doing it\n", hbrush);
if(!GreMakeBrushNonStock(hbrush))
STOCKWARNING("GreMakeBrushNonStock (%p) failed\n", hbrush);
}
//
// Try and remove handle from Hmgr. This will fail if the brush
// is locked down on any threads or if it has been marked global
// or undeletable.
//
pbp.pbr = (PBRUSH) HmgRemoveObject((HOBJ)hbrush, 0, 0, FALSE, BRUSH_TYPE);
if (pbp.pbr!= NULL)
{
//
// Free the style array memory if there is some and it's
// not pointing to our stock default styles:
//
if (pbp.pbr->bIsPen())
{
if ((pbp.ppen->pstyle() != (PFLOAT_LONG) NULL) &&
!pbp.ppen->bIsDefaultStyle())
{
//
// We don't set the field to NULL since this brush
// is on it's way out.
//
VFREEMEM(pbp.ppen->pstyle());
}
}
//
// Free the bitmap pattern in the brush.
//
if (pbp.pbr->hbmPattern())
{
//
// We don't set the field to NULL since this brush
// is on it's way out.
//
BOOL bTemp = bDeleteSurface((HSURF)pbp.pbr->hbmPattern());
ASSERTGDI(bTemp, "ERROR How could pattern brush failed deletion?");
}
//
// Un-reference count the realization cached in the logical brush,
// if any. We don't have to worry about anyone else being in the
// middle of trying to cache a realization for this brush because
// we have removed it from Hmgr and noone else has it locked down.
// We only have to do this if there is a cached realization and the
// brush is non-solid.
//
if ((pbp.pbr->crFore() != BO_NOTCACHED) &&
!pbp.pbr->bCachedIsSolid())
{
ASSERTGDI(pbp.pbr->ulRealization() != NULL,
"ERROR ulRealization() is NULL");
((PRBRUSH)pbp.pbr->ulRealization())->vRemoveRef(
pbp.pbr->bIsEngine() ? RB_ENGINE : RB_DRIVER);
}
//
// Brush is DIB pattern ? if so we may need to free ICM DIBs
//
if (pbp.pbr->flAttrs() & BR_IS_DIB)
{
//
// Free cached color translated ICM DIBs.
//
pbp.pbr->vDeleteIcmDIBs();
}
FREEOBJ(pbp.pbr, BRUSH_TYPE);
//
// free pUser
//
if (!bCleanup && (pUser != (PBRUSHATTR)NULL))
{
HmgFreeObjectAttr((POBJECTATTR)pUser);
}
}
else
{
//
// Under Win31 deleting stock objects returns True.
//
BRUSHSELOBJ bo(hbrush);
if (!bo.bValid() || !bo.bIsGlobal())
bReturn = FALSE;
}
}
return(bReturn);
}
/******************************Public*Routine******************************\
* GreSetBrushGlobal
*
* Sets the brush to be a global one.
*
\**************************************************************************/
void
GreSetBrushGlobal(HBRUSH hbr)
{
BRUSHSELOBJ ebo(hbr);
if (ebo.bValid())
{
ebo.vGlobal();
}
}
/******************************Public*Routine******************************\
* GreMakeBrushStock
*
* Make the brush a stock brush.
*
\**************************************************************************/
HBRUSH
GreMakeBrushStock(HBRUSH hbr)
{
BRUSHSELOBJAPI ebo(hbr);
HANDLE bRet = 0;
BOOL bHandleModified = TRUE;
// Can make the brush a stock brush only when:
// (1) It is valid
// (2) Its not global already (i.e already stock)
// (3) Its not a DIBSection based brush.
// (4) Its not selected into any DC already.
if (!ebo.bValid() || ebo.bIsGlobal() || ebo.pbrush()->cShareLockGet() > 0)
{
STOCKWARNING("GreMakeBrushStock (%p) invalid/global/selected\n",hbr);
return (HBRUSH)0;
}
bRet = (HANDLE)((ULONG_PTR)hbr | GDISTOCKOBJ);
if (InterlockedDecrement(&gStockBrushFree) >= 0 &&
GreSetBrushOwner((HBRUSH)hbr,OBJECT_OWNER_PUBLIC) &&
(bHandleModified = HmgLockAndModifyHandleType((HOBJ)bRet)))
{
ebo.pbrush()->flAttrs(ebo.pbrush()->flAttrs() | BR_IS_GLOBAL);
return (HBRUSH)bRet;
}
else
{
if (!bHandleModified)
GreSetBrushOwner((HBRUSH)hbr,OBJECT_OWNER_CURRENT);
STOCKWARNING("GreMakeBrushStock (%p) Count/GreSetBrushOwner/ModifyH failed\n",bRet);
InterlockedIncrement(&gStockBrushFree);
bRet = 0;
}
return (HBRUSH)bRet;
}
/******************************Public*Routine******************************\
* GreMakeBrushNonStock
*
* Makes the brush a non stock brush
*
\**************************************************************************/
HBRUSH
GreMakeBrushNonStock(HBRUSH hbr)
{
HANDLE bRet = 0;
BRUSHSELOBJAPI ebo(hbr);
// Can make a stock brush non stock only when
// (1) It is valid
// (2) It is a global brush
// (3) It is not a Fixed stock brush
if (ebo.bValid() && ebo.bIsGlobal() && !ebo.pbrush()->bIsFixedStock())
{
bRet = (HANDLE)((ULONG_PTR)hbr & ~GDISTOCKOBJ);
if (ebo.pbrush()->cShareLockGet() > 0)
{
// The brush has more than one share lock. This means it will need
// to be lazy deleted.
ebo.pbrush()->vSetMakeNonStock();
STOCKINFO("GreMakeBrushNonStock (%p) is selected. Delay it\n", hbr);
}
else if(HmgLockAndModifyHandleType((HOBJ)bRet))
{
ebo.pbrush()->flAttrs(ebo.pbrush()->flAttrs() & ~BR_IS_GLOBAL);
if(!GreSetBrushOwner((HBRUSH)bRet,OBJECT_OWNER_CURRENT))
{
bRet = 0;
STOCKWARNING("GreMakeBrushNonStock (%p) GreSetBrushOwner failed\n", bRet);
}
else
{
InterlockedIncrement(&gStockBrushFree);
}
}
else
{
bRet = 0;
}
}
return (HBRUSH)bRet;
}
/******************************Public*Routine******************************\
* GreSetBrushOwner
*
* Sets the brush owner.
*
\**************************************************************************/
BOOL
GreSetBrushOwner(
HBRUSH hbr,
W32PID lPid
)
{
// If it is a global brush which by design are public we dont need to
// do anything.
{
BRUSHSELOBJ ebo(hbr);
if (ebo.bValid())
{
if (ebo.bIsGlobal())
return TRUE;
}
}
BOOL bStatus = FALSE;
PBRUSHATTR pBrushattr = NULL;
PENTRY pentry;
UINT uiIndex = (UINT) HmgIfromH(hbr);
if (uiIndex < gcMaxHmgr)
{
pentry = &gpentHmgr[uiIndex];
if (lPid == OBJECT_OWNER_CURRENT)
{
pBrushattr = (PBRUSHATTR)HmgAllocateObjectAttr();
}
//
// Accquire handle lock. Don't check PID here because owner could
// be NONE, not PUBLIC
//
HANDLELOCK HandleLock(pentry, FALSE);
if (HandleLock.bValid())
{
POBJ pobj = pentry->einfo.pobj;
if ((pentry->Objt == BRUSH_TYPE) && (pentry->FullUnique== HmgUfromH(hbr)))
{
PBRUSH pBrush = (PBRUSH)pobj;
if ((pobj->cExclusiveLock == 0) ||
(pobj->Tid == (PW32THREAD)PsGetCurrentThread()))
{
//
// Handle is locked. It is illegal to accquire the hmgr
// resource when a handle is locked.
//
if ((lPid == OBJECT_OWNER_NONE) ||
(lPid == OBJECT_OWNER_PUBLIC))
{
//
// free PBRUSHATTR if PID matches current process
// transfer brushattributes to kernel mode.
if (HandleLock.Pid() == W32GetCurrentPID())
{
//
// If user mode BRUSHATTR is allocated for this
// brush
//
if (pBrush->pBrushattr() != &pBrush->_Brushattr)
{
// Copy pBrushattr() to _BrushAttr
pBrush->_Brushattr = *(pBrush->pBrushattr());
// Free BRUSHATTR at bottom of function
pBrushattr = pBrush->pBrushattr();
// Set pBrushAttr to point to internal
pBrush->pBrushattr(&pBrush->_Brushattr);
// Clear entry
pentry->pUser = NULL;
}
// Set Brush owner to NONE or PUBLIC
HandleLock.Pid(lPid);
// dec process handle count
HmgDecProcessHandleCount(W32GetCurrentPID());
bStatus = TRUE;
}
else if (HandleLock.Pid() == OBJECT_OWNER_NONE)
{
// Allow to set from NONE to PUBLIC or NONE
HandleLock.Pid(lPid);
bStatus = TRUE;
}
//
// Move bitmap owner if needed. No need to do this if
// we are doing OBJECT_OWNER_NONE.
//
if (bStatus && lPid == OBJECT_OWNER_PUBLIC)
{
if (pBrush->hbmPattern() != (HBITMAP)NULL)
{
GreSetBitmapOwner(pBrush->hbmPattern(), OBJECT_OWNER_PUBLIC);
}
}
}
else if (lPid == OBJECT_OWNER_CURRENT)
{
//
// can only set to OBJECT_OWNER_CURRENT if Brush is
// not owned, or already owned by current pid.
//
lPid = W32GetCurrentPID();
if (HandleLock.Pid() == lPid ||
HandleLock.Pid() == OBJECT_OWNER_NONE ||
HandleLock.Pid() == OBJECT_OWNER_PUBLIC)
{
BOOL bIncHandleCount = FALSE;
bStatus = TRUE;
// only inc handle count if assigning new pid
if (HandleLock.Pid() != lPid)
{
// dont check quota for Brushes. ???
if (HmgIncProcessHandleCount(lPid,BRUSH_TYPE))
bIncHandleCount = TRUE;
}
//
// Check if user object already allocated for this
// handle
//
if (pentry->pUser == NULL)
{
if (pBrushattr != NULL)
{
// Set BrushAttr pointer
pBrush->pBrushattr(pBrushattr);
// Set pUser in ENTRY
pentry->pUser = pBrushattr;
// copy clean brush attrs
*pBrushattr = pBrush->_Brushattr;
// Set pBrushattr to NULL so it is not freed
pBrushattr = NULL;
}
else
{
WARNING("GreSetBrushOwner failed - No BRUSHATTR available");
bStatus = FALSE;
// reduce handle quota count
if (bIncHandleCount)
HmgDecProcessHandleCount(lPid);
}
}
if (bStatus)
{
// Set new owner
HandleLock.Pid(lPid);
//
// Move bitmap owner if needed.
//
if (pBrush->hbmPattern() != (HBITMAP)NULL)
{
GreSetBitmapOwner(pBrush->hbmPattern(), OBJECT_OWNER_CURRENT);
}
}
}
else
{
WARNING("GreSetBrushOwner failed, trying to set directly from one PID to another");
}
}
else
{
WARNING("GreSetBrushOwner failed, bad lPid");
}
}
else
{
WARNING("GreSetBrushOwner failed - Handle is exclusivly locked");
}
}
else
{
WARNING("GreSetBrushOwner failed - bad unique or object type");
}
HandleLock.vUnlock();
}
}
else
{
WARNING("GtreSetBrushOwner failed - invalid handle index\n");
}
// free pBrushattr if needed
if (pBrushattr)
{
HmgFreeObjectAttr((POBJECTATTR)pBrushattr);
}
return(bStatus);
}
/******************************Public*Routine******************************\
* vFreeOrCacheRbrush
*
* Either frees the current RBRUSH (the one pointed to by the this pointer) or
* puts it in the 1-deep RBRUSH cache, if the cache is empty.
*
* History:
*
* 30-Sep-1996 -by- Tom Zakrajsek [tomzak]
* Fixed it for multi brushes (DDML).
*
* 14-Dec-1993 -by- Michael Abrash [mikeab]
* Wrote it.
\**************************************************************************/
VOID MulDestroyBrushInternal(VOID*);
VOID RBRUSH::vFreeOrCacheRBrush(RBTYPE rbtype)
{
//
// If RBRUSH is for UMPD, just free it
//
if (!IS_SYSTEM_ADDRESS(this))
{
ASSERTGDI(bUMPDRBrush(),"RBRUSH::vFreeOrCacheRBrush UserMode brush does not have bUMPDBrush() bit on\n");
EngFreeUserMem(this);
return;
}
PRBRUSH *pprbrush;
// The bMultiBrush check is only valid for DRIVER realizations.
// Otherwise, it is assumed false.
BOOL bMulti = FALSE;
if (rbtype == RB_DRIVER)
{
pprbrush = &gpCachedDbrush;
bMulti = bMultiBrush();
if (bMulti)
{
PVOID pvRbrush = (PVOID)(((PDBRUSH)this)->aj);
MulDestroyBrushInternal(pvRbrush);
}
}
else
{
pprbrush = &gpCachedEngbrush;
}
// If there's already a cached RBRUSH, or this is a DDML brush
// just free this.
if ((*pprbrush != NULL) || (bMulti == TRUE))
{
VFREEMEM(this);
}
else
{
PRBRUSH pOldRbrush;
// There's no cached RBRUSH, and it's not a DDML brush,
// so cache this one.
if ((pOldRbrush = (PRBRUSH)
InterlockedExchangePointer((PVOID *)pprbrush, this))
!= NULL)
{
// Before we could cache this one, someone else cached another one,
// which we just acquired responsibility for, so free it.
VFREEMEM(pOldRbrush);
}
}
}
/******************************Public*Routine******************************\
* BRUSH::hFindIcmDIB
*
* Search ICM DIBs associated with brush until a match is found
*
* Arguments:
*
* Return Value:
*
* History:
*
* 9/25/1996 Mark Enstrom [marke]
*
\**************************************************************************/
HBITMAP BRUSH::hFindIcmDIB(HANDLE hcmXform)
{
ICMMSG(("hFindIcmDIB: FIND ICM DIB \n"));
if (hcmXform == NULL)
{
return _hbmPattern;
}
else
{
GreAcquireFastMutex(ghfmMemory);
PICM_DIB_LIST pDIBList = pIcmDIBList();
while (pDIBList != NULL)
{
if (pDIBList->hcmXform == hcmXform)
{
GreReleaseFastMutex(ghfmMemory);
return(pDIBList->hDIB);
}
pDIBList = pDIBList->pNext;
}
GreReleaseFastMutex(ghfmMemory);
return(NULL);
}
}
BOOL BRUSH::bAddIcmDIB(HANDLE hcmXform,HBITMAP hDIB)
{
ICMMSG(("bAddIcmDIB: ADD ICM DIB \n"));
BOOL bRet = FALSE;
//
// Check current hcmform is not on the list.
//
if (hFindIcmDIB(hcmXform))
{
ICMMSG(("bAddIcmDIB(): The DIB for hcmXform is exist\n"));
//
// hcmXform is exist,
//
// Do we need to do delete existing one and insert new one ??
//
return (FALSE);
}
SURFREF SurfDIB((HSURF) hDIB);
if (SurfDIB.bValid())
{
PICM_DIB_LIST pDIBList = (PICM_DIB_LIST)PALLOCNOZ(sizeof(ICM_DIB_LIST),'ldbG');
if (pDIBList)
{
//
// Inc. ref. count
//
{
SURFACE *ps = SurfDIB.ps;
ps->vInc_cRef();
}
//
// Fill DIBList cell.
//
pDIBList->hcmXform = hcmXform;
pDIBList->hDIB = hDIB;
pDIBList->pNext = pIcmDIBList();
//
// Updates list.
//
GreAcquireFastMutex(ghfmMemory);
pIcmDIBList(pDIBList);
GreReleaseFastMutex(ghfmMemory);
bRet = TRUE;
}
else
{
bRet = FALSE;
}
}
return(bRet);
}
VOID BRUSH::vDeleteIcmDIBs(VOID)
{
ICMMSG(("vDeleteIcmDIBs: Free ICM DIB \n"));
PICM_DIB_LIST pDIBList = pIcmDIBList();
GreAcquireFastMutex(ghfmMemory);
while (pDIBList != NULL)
{
PICM_DIB_LIST pNext = pDIBList->pNext;
HSURF hSurf = (HSURF) pDIBList->hDIB;
BOOL bValidSurface = FALSE;
//
// Dec. ref count, before deleting
//
{
SURFREF SurfDIB(hSurf);
if (SurfDIB.bValid())
{
SURFACE *ps = SurfDIB.ps;
ps->vDec_cRef();
bValidSurface = TRUE;
}
}
if (bValidSurface)
{
//
// Delete ICM-ed DIB surface.
//
if (!bDeleteSurface((HSURF)pDIBList->hDIB))
{
ICMMSG(("vDeleteICMDIBs(): bDeleteSurface is failed\n"));
}
}
else
{
ICMMSG(("vDeleteICMDIBs(): Invalid surface\n"));
}
//
// free the cell.
//
VFREEMEM(pDIBList);
pDIBList = pNext;
}
GreReleaseFastMutex(ghfmMemory);
}
| 31.135599 | 128 | 0.450207 | npocmaka |
13a06540b3f76de1734cf13b99186543812fea99 | 9,994 | cpp | C++ | windows/richedit/re30/olsole.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/richedit/re30/olsole.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/richedit/re30/olsole.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*
* @doc INTERNAL
*
* @module OLSOLE.CPP -- OlsOle LineServices object class
*
* Author:
* Murray Sargent (with lots of help from RickSa's ols code)
*
* Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved.
*/
#include "_common.h"
#include "_font.h"
#include "_edit.h"
#include "_disp.h"
#include "_ols.h"
#include "_render.h"
extern "C" {
#include "objdim.h"
#include "pobjdim.h"
#include "plsdnode.h"
#include "dispi.h"
#include "pdispi.h"
#include "fmti.h"
#include "lsdnset.h"
#include "lsdnfin.h"
#include "brko.h"
#include "pbrko.h"
#include "locchnk.h"
#include "lsqout.h"
#include "lsqin.h"
#include "lsimeth.h"
}
#ifdef LINESERVICES
/*
* OlsOleCreateILSObj(pols, plsc, pclscbk, dword, ppilsobj)
*
* @func
* Create LS Ole object handler. We don't have any need for
* this, so just set it to 0.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleCreateILSObj(
POLS pols, //[IN]: COls *
PLSC plsc, //[IN]: LineServices context
PCLSCBK,
DWORD,
PILSOBJ *ppilsobj) //[OUT]: ptr to ilsobj
{
*ppilsobj = 0;
return lserrNone;
}
/*
* OlsOleDestroyILSObj(pilsobj)
*
* @func
* Destroy LS Ole handler object. Nothing to do, since we don't
* use the ILSObj.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDestroyILSObj(
PILSOBJ pilsobj)
{
return lserrNone;
}
/*
* OlsOleSetDoc(pilsobj, pclsdocinf)
*
* @func
* Set doc info. Nothing to do for Ole objects
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleSetDoc(
PILSOBJ,
PCLSDOCINF)
{
// Ole objects don't care about this
return lserrNone;
}
/*
* OlsOleCreateLNObj(pilsobj, pplnobj)
*
* @func
* Create the line object. Nothing needed in addition to the ped,
* so just return the ped as the LN object.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleCreateLNObj(
PCILSOBJ pilsobj,
PLNOBJ * pplnobj)
{
*pplnobj = (PLNOBJ)g_pols->_pme->GetPed(); // Just the ped
return lserrNone;
}
/*
* OlsOleDestroyLNObj(plnobj)
*
* @func
* Destroy LN object. Nothing to do, since ped is destroyed
* elsewhere
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDestroyLNObj(
PLNOBJ plnobj)
{
return lserrNone;
}
/*
* OlsOleFmt(plnobj, pcfmtin, pfmres)
*
* @func
* Compute dimensions of a particular Ole object
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleFmt(
PLNOBJ plnobj,
PCFMTIN pcfmtin,
FMTRES *pfmres)
{
const LONG cp = pcfmtin->lsfrun.plsrun->_cp; //Cannot trust LS cps
LONG dup = 0;
LSERR lserr;
OBJDIM objdim;
CTxtEdit * ped = (CTxtEdit *)plnobj;
COleObject * pobj = ped->GetObjectMgr()->GetObjectFromCp(cp);
Assert(pobj);
ZeroMemory(&objdim, sizeof(objdim));
pobj->MeasureObj(g_pols->_pme->GetDyrInch(), g_pols->_pme->GetDxrInch(),
objdim.dur, objdim.heightsRef.dvAscent,
objdim.heightsRef.dvDescent, pcfmtin->lstxmRef.dvDescent);
pobj->MeasureObj(g_pols->_pme->GetDypInch(), g_pols->_pme->GetDxpInch(),
dup, objdim.heightsPres.dvAscent,
objdim.heightsPres.dvDescent, pcfmtin->lstxmPres.dvDescent);
pobj->_plsdnTop = pcfmtin->plsdnTop;
lserr = g_plsc->dnFinishRegular(1, pcfmtin->lsfrun.plsrun, pcfmtin->lsfrun.plschp, (PDOBJ)pobj, &objdim);
if(lserrNone == lserr)
{
lserr = g_plsc->dnSetRigidDup(pcfmtin->plsdnTop, dup);
if(lserrNone == lserr)
{
*pfmres = fmtrCompletedRun;
if (pcfmtin->lsfgi.urPen + objdim.dur > pcfmtin->lsfgi.urColumnMax
&& !pcfmtin->lsfgi.fFirstOnLine)
{
*pfmres = fmtrExceededMargin;
}
}
}
return lserr;
}
/*
* OlsOleTruncateChunk(plocchnk, posichnk)
*
* @func
* Truncate chunk plocchnk at the point posichnk
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleTruncateChunk(
PCLOCCHNK plocchnk, // (IN): locchnk to truncate
PPOSICHNK posichnk) // (OUT): truncation point
{
LSERR lserr;
OBJDIM objdim;
PLSCHNK plschnk = plocchnk->plschnk;
COleObject * pobj;
long ur = plocchnk->lsfgi.urPen;
long urColumnMax = plocchnk->lsfgi.urColumnMax;
for(DWORD i = 0; ur <= urColumnMax; i++)
{
AssertSz(i < plocchnk->clschnk, "OlsOleTruncateChunk: exceeded group of chunks");
pobj = (COleObject *)plschnk[i].pdobj;
Assert(pobj);
lserr = g_plsc->dnQueryObjDimRange(pobj->_plsdnTop, pobj->_plsdnTop, &objdim);
if(lserr != lserrNone)
return lserr;
ur += objdim.dur;
}
posichnk->ichnk = i - 1;
posichnk->dcp = 1;
return lserrNone;
}
/*
* OlsOleFindPrevBreakChunk(plocchnk, pposichnk, brkcond, pbrkout)
*
* @func
* Find previous break in chunk
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleFindPrevBreakChunk(
PCLOCCHNK plocchnk,
PCPOSICHNK pposichnk,
BRKCOND brkcond, //(IN): recommendation about break after chunk
PBRKOUT pbrkout)
{
ZeroMemory(pbrkout, sizeof(*pbrkout));
if (pposichnk->ichnk == ichnkOutside && (brkcond == brkcondPlease || brkcond == brkcondCan))
{
pbrkout->fSuccessful = fTrue;
pbrkout->posichnk.ichnk = plocchnk->clschnk - 1;
pbrkout->posichnk.dcp = plocchnk->plschnk[plocchnk->clschnk - 1].dcp;
COleObject *pobj = (COleObject *)plocchnk->plschnk[plocchnk->clschnk - 1].pdobj;
Assert(pobj);
g_plsc->dnQueryObjDimRange(pobj->_plsdnTop, pobj->_plsdnTop, &pbrkout->objdim);
}
else
pbrkout->brkcond = brkcondPlease;
return lserrNone;
}
/*
* OlsOleForceBreakChunk(plocchnk, pposichnk, pbrkout)
*
* @func
* Called when forced to break a line.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleForceBreakChunk(
PCLOCCHNK plocchnk,
PCPOSICHNK pposichnk,
PBRKOUT pbrkout)
{
ZeroMemory(pbrkout, sizeof(*pbrkout));
pbrkout->fSuccessful = fTrue;
if (plocchnk->lsfgi.fFirstOnLine && pposichnk->ichnk == 0 || pposichnk->ichnk == ichnkOutside)
{
pbrkout->posichnk.dcp = 1;
COleObject *pobj = (COleObject *)plocchnk->plschnk[0].pdobj;
Assert(pobj);
g_plsc->dnQueryObjDimRange(pobj->_plsdnTop, pobj->_plsdnTop, &pbrkout->objdim);
}
else
{
pbrkout->posichnk.ichnk = pposichnk->ichnk;
pbrkout->posichnk.dcp = 0;
}
return lserrNone;
}
/*
* OlsOleSetBreak(pdobj, brkkind, nBreakRecord, rgBreakRecord, nActualBreakRecord)
*
* @func
* Set break
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleSetBreak(
PDOBJ pdobj, // (IN): dobj which is broken
BRKKIND brkkind, // (IN): Previous/Next/Force/Imposed was chosen
DWORD nBreakRecord, // (IN): size of array
BREAKREC* rgBreakRecord, // (OUT): array of break records
DWORD* nActualBreakRecord) // (OUT): actual number of used elements in array
{
return lserrNone;
}
LSERR WINAPI OlsOleGetSpecialEffectsInside(
PDOBJ pdobj, // (IN): dobj
UINT *pEffectsFlags) // (OUT): Special effects for this object
{
*pEffectsFlags = 0;
return lserrNone;
}
LSERR WINAPI OlsOleCalcPresentation(
PDOBJ, // (IN): dobj
long, // (IN): dup of dobj
LSKJUST, // (IN): LSKJUST
BOOL fLastVisibleOnLine)// (IN): this object is last visible object on line
{
return lserrNone;
}
/*
* OlsOleQueryPointPcp(pdobj, ppointuvQuery, plsqin, plsqout)
*
* @func
* Query Ole object PointFromCp.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleQueryPointPcp(
PDOBJ pdobj, //(IN): dobj to query
PCPOINTUV ppointuvQuery, //(IN): query point (uQuery,vQuery)
PCLSQIN plsqin, //(IN): query input
PLSQOUT plsqout) //(OUT): query output
{
ZeroMemory(plsqout, sizeof(LSQOUT));
plsqout->heightsPresObj = plsqin->heightsPresRun;
plsqout->dupObj = plsqin->dupRun;
return lserrNone;
}
/*
* OlsOleQueryCpPpoint(pdobj, dcp, plsqin, plsqout)
*
* @func
* Query Ole object CpFromPoint.
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleQueryCpPpoint(
PDOBJ pdobj, //(IN): dobj to query
LSDCP dcp, //(IN): dcp for query
PCLSQIN plsqin, //(IN): query input
PLSQOUT plsqout) //(OUT): query output
{
ZeroMemory(plsqout, sizeof(LSQOUT));
plsqout->heightsPresObj = plsqin->heightsPresRun;
plsqout->dupObj = plsqin->dupRun;
return lserrNone;
}
/*
* OlsOleDisplay(pdobj, pcdispin)
*
* @func
* Display object
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDisplay(
PDOBJ pdobj, //(IN): dobj to query
PCDISPIN pcdispin) //(IN): display info
{
POINT pt, ptCur;
COleObject *pobj = (COleObject *)pdobj;
Assert(pobj);
CRenderer *pre = g_pols->GetRenderer();
const CDisplay *pdp = pre->GetPdp();
ptCur = pre->GetCurPoint();
pt.x = pcdispin->ptPen.x;
pt.y = ptCur.y;
if (pcdispin->lstflow == lstflowWS)
pt.x -= pcdispin->dup - 1;
pre->SetCurPoint(pt);
pre->SetClipLeftRight(pcdispin->dup);
RECT rc = pre->GetClipRect();
pre->SetSelected(pcdispin->plsrun->IsSelected());
pre->Check_pccs();
pre->SetFontAndColor(pcdispin->plsrun->_pCF);
// Draw it!
HDC hdc = pre->GetDC();
pobj->DrawObj(pdp, pre->GetDypInch(), pre->GetDxpInch(), hdc, pdp->IsMetafile(), &pt, &rc, pcdispin->ptPen.y - pt.y, pre->GetLine()._yDescent);
return lserrNone;
}
/*
* OlsOleDistroyDObj(pdobj)
*
* @func
* Destroy object: nothing to do since object is destroyed elsewhere
*
* @rdesc
* LSERR
*/
LSERR WINAPI OlsOleDestroyDObj(
PDOBJ pdobj)
{
return lserrNone;
}
extern const LSIMETHODS vlsimethodsOle =
{
OlsOleCreateILSObj,
OlsOleDestroyILSObj,
OlsOleSetDoc,
OlsOleCreateLNObj,
OlsOleDestroyLNObj,
OlsOleFmt,
0,//OlsOleFmtResume
0,//OlsOleGetModWidthPrecedingChar
0,//OlsOleGetModWidthFollowingChar
OlsOleTruncateChunk,
OlsOleFindPrevBreakChunk,
0,//OlsOleFindNextBreakChunk
OlsOleForceBreakChunk,
OlsOleSetBreak,
OlsOleGetSpecialEffectsInside,
0,//OlsOleFExpandWithPrecedingChar
0,//OlsOleFExpandWithFollowingChar
OlsOleCalcPresentation,
OlsOleQueryPointPcp,
OlsOleQueryCpPpoint,
0,//pfnEnum
OlsOleDisplay,
OlsOleDestroyDObj
};
#endif // LINESERVICES
| 22.258352 | 145 | 0.658295 | npocmaka |
13a6621ab669a6c6ce79469cdba6a9e2d49e17c6 | 5,031 | cpp | C++ | uppsrc/CtrlCore/Frame.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppsrc/CtrlCore/Frame.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppsrc/CtrlCore/Frame.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include "CtrlCore.h"
NAMESPACE_UPP
#ifdef flagSO
CtrlFrame::CtrlFrame() {}
CtrlFrame::~CtrlFrame() {}
#endif
void CtrlFrame::FramePaint(Draw& draw, const Rect& r) {}
void CtrlFrame::FrameAdd(Ctrl& ctrl) {}
void CtrlFrame::FrameRemove() {}
int CtrlFrame::OverPaint() const { return 0; }
void NullFrameClass::FrameLayout(Rect& r) {}
void NullFrameClass::FramePaint(Draw& draw, const Rect& r) {}
void NullFrameClass::FrameAddSize(Size& sz) {}
CtrlFrame& GLOBAL_V(NullFrameClass, NullFrame);
#ifdef flagSO
BorderFrame::BorderFrame(const ColorF *border) : border(border) {}
BorderFrame::~BorderFrame() {}
#endif
void BorderFrame::FrameLayout(Rect& r)
{
Size sz = r.GetSize();
int n = (int)(intptr_t)*border;
if(sz.cx >= 2 * n && sz.cy >= 2 * n)
r.Deflate(n);
}
void BorderFrame::FrameAddSize(Size& sz)
{
sz += 2 * (int)(intptr_t)*border;
}
void BorderFrame::FramePaint(Draw& draw, const Rect& r)
{
Size sz = r.GetSize();
int n = (int)(intptr_t)*border;
if(sz.cx >= 2 * n && sz.cy >= 2 * n)
DrawBorder(draw, r.left, r.top, r.Width(), r.Height(), border);
}
CtrlFrame& GLOBAL_VP(BorderFrame, InsetFrame, (InsetBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, ThinInsetFrame, (ThinInsetBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, ButtonFrame, (ButtonBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, BlackFrame, (BlackBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, WhiteFrame, (WhiteBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, OutsetFrame, (OutsetBorder()));
CtrlFrame& GLOBAL_VP(BorderFrame, ThinOutsetFrame, (ThinOutsetBorder()));
CH_COLOR(FieldFrameColor, Blend(SColorHighlight, SColorShadow));
class XPFieldFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.Deflate(2); }
virtual void FramePaint(Draw& w, const Rect& r) {
DrawFrame(w, r, FieldFrameColor());
DrawFrame(w, r.Deflated(1), SColorPaper);
}
virtual void FrameAddSize(Size& sz) { sz += 4; }
};
class XPEditFieldFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.Deflate(1); }
virtual void FramePaint(Draw& w, const Rect& r) {
DrawFrame(w, r, FieldFrameColor());
}
virtual void FrameAddSize(Size& sz) { sz += 2; }
};
CtrlFrame& XPFieldFrame() { return Single<XPFieldFrameCls>(); }
CtrlFrame& XPEditFieldFrame() { return Single<XPEditFieldFrameCls>(); }
CH_INT(EditFieldIsThin, 0);
CtrlFrame& FieldFrame() { return GUI_GlobalStyle() >= GUISTYLE_XP ? XPFieldFrame() : InsetFrame(); }
CH_VALUE(TopSeparator1, SColorShadow());
CH_VALUE(TopSeparator2, SColorLight());
class TopSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.top += 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
ChPaint(w, r.left, r.top, r.Width(), 1, TopSeparator1());
ChPaint(w, r.left, r.top + 1, r.Width(), 1, TopSeparator2());
}
virtual void FrameAddSize(Size& sz) { sz.cy += 2; }
};
class BottomSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.bottom -= 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
w.DrawRect(r.left, r.bottom - 2, r.Width(), 1, SColorShadow);
w.DrawRect(r.left, r.bottom - 1, r.Width(), 1, SColorLight);
}
virtual void FrameAddSize(Size& sz) { sz.cy += 2; }
};
class LeftSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.left += 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
w.DrawRect(r.left, r.top, 1, r.Height(), SColorShadow);
w.DrawRect(r.left + 1, r.top, 1, r.Height(), SColorLight);
}
virtual void FrameAddSize(Size& sz) { sz.cx += 2; }
};
class RightSeparatorFrameCls : public CtrlFrame {
virtual void FrameLayout(Rect& r) { r.right -= 2; }
virtual void FramePaint(Draw& w, const Rect& r) {
w.DrawRect(r.right - 2, r.top, 1, r.Height(), SColorShadow);
w.DrawRect(r.right - 1, r.top, 1, r.Height(), SColorLight);
}
virtual void FrameAddSize(Size& sz) { sz.cx += 2; }
};
CtrlFrame& BottomSeparatorFrame() { return Single<BottomSeparatorFrameCls>(); }
CtrlFrame& TopSeparatorFrame() { return Single<TopSeparatorFrameCls>(); }
CtrlFrame& RightSeparatorFrame() { return Single<RightSeparatorFrameCls>(); }
CtrlFrame& LeftSeparatorFrame() { return Single<LeftSeparatorFrameCls>(); }
CH_INT(FrameButtonWidth, 17);
CH_INT(ScrollBarArrowSize, FrameButtonWidth());
void LayoutFrameLeft(Rect& r, Ctrl *ctrl, int cx)
{
if(ctrl) {
cx *= ctrl->IsShown();
ctrl->SetFrameRect(r.left, r.top, cx, r.Height());
r.left += cx;
}
}
void LayoutFrameRight(Rect& r, Ctrl *ctrl, int cx)
{
if(ctrl) {
cx *= ctrl->IsShown();
ctrl->SetFrameRect(r.right - cx, r.top, cx, r.Height());
r.right -= cx;
}
}
void LayoutFrameTop(Rect& r, Ctrl *ctrl, int cy)
{
if(ctrl) {
cy *= ctrl->IsShown();
ctrl->SetFrameRect(r.left, r.top, r.Width(), cy);
r.top += cy;
}
}
void LayoutFrameBottom(Rect& r, Ctrl *ctrl, int cy)
{
if(ctrl) {
cy *= ctrl->IsShown();
ctrl->SetFrameRect(r.left, r.bottom - cy, r.Width(), cy);
r.bottom -= cy;
}
}
END_UPP_NAMESPACE
| 30.490909 | 100 | 0.675611 | dreamsxin |
13aabc60c62c64011af9b6c0d731c9297b7fcc27 | 4,483 | hpp | C++ | cpp/include/xtt/group_public_key_context.hpp | xaptum/xtt-cpp | d82f4c33e6c67e343da70f3b73dea67c0a8bf6f1 | [
"Apache-2.0"
] | null | null | null | cpp/include/xtt/group_public_key_context.hpp | xaptum/xtt-cpp | d82f4c33e6c67e343da70f3b73dea67c0a8bf6f1 | [
"Apache-2.0"
] | 7 | 2018-05-14T15:29:57.000Z | 2019-11-19T22:04:40.000Z | cpp/include/xtt/group_public_key_context.hpp | xaptum/xtt-cpp | d82f4c33e6c67e343da70f3b73dea67c0a8bf6f1 | [
"Apache-2.0"
] | 3 | 2018-05-07T14:27:00.000Z | 2018-07-20T18:29:43.000Z | /******************************************************************************
*
* Copyright 2018 Xaptum, 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
*
*****************************************************************************/
#ifndef XTT_CPP_GROUPPUBLICKEYCONTEXT_HPP
#define XTT_CPP_GROUPPUBLICKEYCONTEXT_HPP
#pragma once
#include <xtt/context.h>
#include <xtt/group_identity.hpp>
#include <xtt/config.hpp>
#include <vector>
#include <memory>
namespace xtt { class group_public_key_context; }
namespace xtt {
class group_public_key_context {
public:
virtual ~group_public_key_context() = default;
virtual std::unique_ptr<group_public_key_context> clone() const = 0;
/*
* Serialize to byte stream,
* as (GPK | basename_length(1 byte) | basename).
*/
virtual std::vector<unsigned char> serialize() const = 0;
/*
* Get GPK as byte string.
*/
virtual std::vector<unsigned char> get_gpk() const = 0;
/*
* Get basename as byte string.
*/
virtual std::vector<unsigned char> get_basename() const = 0;
/*
* Get GPK as ASCII-encoded hexadecimal string
*/
virtual std::string get_gpk_as_text() const = 0;
/*
* Get basename as ASCII-encoded hexadecimal string
*/
virtual std::string get_basename_as_text() const = 0;
virtual struct xtt_group_public_key_context* get() = 0;
virtual const struct xtt_group_public_key_context* get() const = 0;
};
class group_public_key_context_lrsw : public group_public_key_context {
public:
/*
* Build a group_public_key_context_lrsw from
* a single byte string,
* in the form (GPK | basename_length (1 byte) | basename).
*/
static
std::unique_ptr<group_public_key_context>
deserialize(const unsigned char* serialized, std::size_t serialized_length);
static
std::unique_ptr<group_public_key_context>
deserialize(const std::vector<unsigned char>& serialized);
/*
* Build a group_public_key_context_lrsw from
* two separate byte strings,
* one for the basename and the other for the GPK.
*/
static
std::unique_ptr<group_public_key_context>
from_gpk_and_basename(const unsigned char* gpk,
std::size_t gpk_length,
const unsigned char* basename,
std::size_t basename_length);
static
std::unique_ptr<group_public_key_context>
from_gpk_and_basename(const std::vector<unsigned char>& gpk,
const std::vector<unsigned char>& basename);
/*
* Build a group_public_key_context_lrsw from
* two separate ASCII-encoded hexadecimal strings,
* one for the basename and the other for the GPK.
*/
static
std::unique_ptr<group_public_key_context>
from_gpk_and_basename(const std::string& gpk,
const std::string& basename);
public:
group_public_key_context_lrsw();
std::vector<unsigned char> serialize() const final;
std::vector<unsigned char> get_gpk() const final;
std::vector<unsigned char> get_basename() const final;
std::string get_gpk_as_text() const final;
std::string get_basename_as_text() const final;
std::unique_ptr<group_public_key_context> clone() const final;
struct xtt_group_public_key_context* get() final;
const struct xtt_group_public_key_context* get() const final;
private:
xtt_group_public_key_context gpk_ctx_;
};
std::ostream& operator<<(std::ostream& stream, const xtt::group_public_key_context& gpk_ctx);
} // namespace xtt
#endif
| 32.021429 | 97 | 0.612982 | xaptum |
13aaf417fadb0c18e7f25b6d2c877f161850ba14 | 1,032 | cpp | C++ | Dev/asd_cpp/core/Graphics/3D/Resource/Animation/asd.KeyframeAnimation_Imp.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 37 | 2015-07-12T14:21:03.000Z | 2020-10-17T03:08:17.000Z | Dev/asd_cpp/core/Graphics/3D/Resource/Animation/asd.KeyframeAnimation_Imp.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 91 | 2015-06-14T10:47:22.000Z | 2020-06-29T18:05:21.000Z | Dev/asd_cpp/core/Graphics/3D/Resource/Animation/asd.KeyframeAnimation_Imp.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 14 | 2015-07-13T04:15:20.000Z | 2021-09-30T01:34:51.000Z |
#include "asd.KeyframeAnimation_Imp.h"
#include <cmath>
namespace asd
{
KeyframeAnimation_Imp::KeyframeAnimation_Imp()
: m_targetType(AnimationCurveTargetType::NoneTarget)
, m_targetAxis(AnimationCurveTargetAxis::NoneTarget)
{
}
KeyframeAnimation_Imp::~KeyframeAnimation_Imp()
{
}
const achar* KeyframeAnimation_Imp::GetName()
{
return m_name.c_str();
}
void KeyframeAnimation_Imp::SetName(const achar* name)
{
m_name = name;
ModelUtils::GetAnimationTarget(m_targetName, m_targetType, m_targetAxis, name);
}
astring& KeyframeAnimation_Imp::GetTargetName()
{
return m_targetName;
}
AnimationCurveTargetType KeyframeAnimation_Imp::GetTargetType()
{
return m_targetType;
}
AnimationCurveTargetAxis KeyframeAnimation_Imp::GetTargetAxis()
{
return m_targetAxis;
}
void KeyframeAnimation_Imp::AddKeyframe(const FCurveKeyframe& kf)
{
m_keyframes.push_back(kf);
}
float KeyframeAnimation_Imp::GetValue(float time)
{
return ModelUtils::GetKeyframeValue(time, m_keyframes);
}
}
| 18.105263 | 81 | 0.766473 | GCLemon |
13ab558e15de8ba4df61d5a5966e5b25d1beace2 | 17,635 | cpp | C++ | lib/SimpleHttpClient/SslClientConnection.cpp | LLcat1217/arangodb | 67c51272915699e0a489e1f8d9da786f4226221a | [
"Apache-2.0"
] | null | null | null | lib/SimpleHttpClient/SslClientConnection.cpp | LLcat1217/arangodb | 67c51272915699e0a489e1f8d9da786f4226221a | [
"Apache-2.0"
] | null | null | null | lib/SimpleHttpClient/SslClientConnection.cpp | LLcat1217/arangodb | 67c51272915699e0a489e1f8d9da786f4226221a | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include <errno.h>
#include <string.h>
#include <string>
#include "Basics/Common.h"
#include "Basics/operating-system.h"
#ifdef TRI_HAVE_WINSOCK2_H
#include <WS2tcpip.h>
#include <WinSock2.h>
#endif
#include <openssl/opensslv.h>
#include <openssl/ssl.h>
#ifndef OPENSSL_VERSION_NUMBER
#error expecting OPENSSL_VERSION_NUMBER to be defined
#endif
#include <openssl/err.h>
#include <openssl/opensslconf.h>
#include <openssl/ssl3.h>
#include <openssl/x509.h>
#include "SslClientConnection.h"
#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/debugging.h"
#include "Basics/error.h"
#include "Basics/socket-utils.h"
#include "Basics/voc-errors.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include "Ssl/ssl-helper.h"
#undef TRACE_SSL_CONNECTIONS
#ifdef _WIN32
#define STR_ERROR() \
windowsErrorBuf; \
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, \
windowsErrorBuf, sizeof(windowsErrorBuf), NULL); \
errno = GetLastError();
#else
#define STR_ERROR() strerror(errno)
#endif
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::httpclient;
namespace {
#ifdef TRACE_SSL_CONNECTIONS
static char const* tlsTypeName(int type) {
switch (type) {
#ifdef SSL3_RT_HEADER
case SSL3_RT_HEADER:
return "TLS header";
#endif
case SSL3_RT_CHANGE_CIPHER_SPEC:
return "TLS change cipher";
case SSL3_RT_ALERT:
return "TLS alert";
case SSL3_RT_HANDSHAKE:
return "TLS handshake";
case SSL3_RT_APPLICATION_DATA:
return "TLS app data";
default:
return "TLS Unknown";
}
}
static char const* sslMessageType(int sslVersion, int msg) {
#ifdef SSL2_VERSION_MAJOR
if (sslVersion == SSL2_VERSION_MAJOR) {
switch (msg) {
case SSL2_MT_ERROR:
return "Error";
case SSL2_MT_CLIENT_HELLO:
return "Client hello";
case SSL2_MT_CLIENT_MASTER_KEY:
return "Client key";
case SSL2_MT_CLIENT_FINISHED:
return "Client finished";
case SSL2_MT_SERVER_HELLO:
return "Server hello";
case SSL2_MT_SERVER_VERIFY:
return "Server verify";
case SSL2_MT_SERVER_FINISHED:
return "Server finished";
case SSL2_MT_REQUEST_CERTIFICATE:
return "Request CERT";
case SSL2_MT_CLIENT_CERTIFICATE:
return "Client CERT";
}
} else
#endif
if (sslVersion == SSL3_VERSION_MAJOR) {
switch (msg) {
case SSL3_MT_HELLO_REQUEST:
return "Hello request";
case SSL3_MT_CLIENT_HELLO:
return "Client hello";
case SSL3_MT_SERVER_HELLO:
return "Server hello";
#ifdef SSL3_MT_NEWSESSION_TICKET
case SSL3_MT_NEWSESSION_TICKET:
return "Newsession Ticket";
#endif
case SSL3_MT_CERTIFICATE:
return "Certificate";
case SSL3_MT_SERVER_KEY_EXCHANGE:
return "Server key exchange";
case SSL3_MT_CLIENT_KEY_EXCHANGE:
return "Client key exchange";
case SSL3_MT_CERTIFICATE_REQUEST:
return "Request CERT";
case SSL3_MT_SERVER_DONE:
return "Server finished";
case SSL3_MT_CERTIFICATE_VERIFY:
return "CERT verify";
case SSL3_MT_FINISHED:
return "Finished";
#ifdef SSL3_MT_CERTIFICATE_STATUS
case SSL3_MT_CERTIFICATE_STATUS:
return "Certificate Status";
#endif
}
}
return "Unknown";
}
static void sslTlsTrace(int direction, int sslVersion, int contentType,
void const* buf, size_t, SSL*, void*) {
// enable this for tracing SSL connections
if (sslVersion) {
sslVersion >>= 8; /* check the upper 8 bits only below */
char const* tlsRtName;
if (sslVersion == SSL3_VERSION_MAJOR && contentType)
tlsRtName = tlsTypeName(contentType);
else
tlsRtName = "";
LOG_TOPIC("5e087", TRACE, arangodb::Logger::FIXME)
<< "SSL connection trace: " << (direction ? "out" : "in") << ", "
<< tlsRtName << ", "
<< sslMessageType(sslVersion, *static_cast<char const*>(buf));
}
}
#endif
} // namespace
////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new client connection
////////////////////////////////////////////////////////////////////////////////
SslClientConnection::SslClientConnection(
application_features::CommunicationFeaturePhase& comm, Endpoint* endpoint,
double requestTimeout, double connectTimeout, size_t connectRetries,
uint64_t sslProtocol)
: GeneralClientConnection(comm, endpoint, requestTimeout, connectTimeout,
connectRetries),
_ssl(nullptr),
_ctx(nullptr),
_sslProtocol(sslProtocol) {
init(sslProtocol);
}
SslClientConnection::SslClientConnection(
application_features::CommunicationFeaturePhase& comm,
std::unique_ptr<Endpoint>& endpoint, double requestTimeout,
double connectTimeout, size_t connectRetries, uint64_t sslProtocol)
: GeneralClientConnection(comm, endpoint, requestTimeout, connectTimeout,
connectRetries),
_ssl(nullptr),
_ctx(nullptr),
_sslProtocol(sslProtocol) {
init(sslProtocol);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys a client connection
////////////////////////////////////////////////////////////////////////////////
SslClientConnection::~SslClientConnection() {
disconnect();
if (_ssl != nullptr) {
SSL_free(_ssl);
}
if (_ctx != nullptr) {
SSL_CTX_free(_ctx);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief internal initialization method, called from ctor
////////////////////////////////////////////////////////////////////////////////
void SslClientConnection::init(uint64_t sslProtocol) {
TRI_invalidatesocket(&_socket);
SSL_METHOD SSL_CONST* meth = nullptr;
switch (SslProtocol(sslProtocol)) {
case SSL_V2:
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_NOT_IMPLEMENTED,
"support for SSLv2 has been dropped");
#ifndef OPENSSL_NO_SSL3_METHOD
case SSL_V3:
meth = SSLv3_method();
break;
#endif
case SSL_V23:
meth = SSLv23_method();
break;
case TLS_V1:
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
meth = TLS_client_method();
#else
meth = TLSv1_method();
#endif
break;
case TLS_V12:
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
meth = TLS_client_method();
#else
meth = TLSv1_2_method();
#endif
break;
// TLS 1.3, only supported from OpenSSL 1.1.1 onwards
// openssl version number format is
// MNNFFPPS: major minor fix patch status
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
case TLS_V13:
meth = TLS_client_method();
break;
#endif
case TLS_GENERIC:
meth = TLS_client_method();
break;
case SSL_UNKNOWN:
default:
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
// The actual protocol version used will be negotiated to the highest
// version mutually supported by the client and the server. The supported
// protocols are SSLv3, TLSv1, TLSv1.1 and TLSv1.2. Applications should
// use these methods, and avoid the version-specific methods described
// below.
meth = TLS_method();
#else
// default to TLS 1.2
meth = TLSv1_2_method();
#endif
break;
}
_ctx = SSL_CTX_new(meth);
if (_ctx != nullptr) {
#ifdef TRACE_SSL_CONNECTIONS
SSL_CTX_set_msg_callback(_ctx, sslTlsTrace);
#endif
SSL_CTX_set_cipher_list(_ctx, "ALL");
// TODO: better use the following ciphers...
// SSL_CTX_set_cipher_list(_ctx,
// "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH");
bool sslCache = true;
SSL_CTX_set_session_cache_mode(
_ctx, sslCache ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_OFF);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief connect
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::connectSocket() {
TRI_ASSERT(_endpoint != nullptr);
if (_endpoint->isConnected()) {
disconnectSocket();
_isConnected = false;
}
_errorDetails.clear();
_socket = _endpoint->connect(_connectTimeout, _requestTimeout);
if (!TRI_isvalidsocket(_socket) || _ctx == nullptr) {
_errorDetails = _endpoint->_errorMessage;
_isConnected = false;
return false;
}
_isConnected = true;
_ssl = SSL_new(_ctx);
if (_ssl == nullptr) {
_errorDetails = std::string("failed to create ssl context");
disconnectSocket();
_isConnected = false;
return false;
}
switch (SslProtocol(_sslProtocol)) {
case TLS_V1:
case TLS_V12:
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
case TLS_V13:
#endif
case TLS_GENERIC:
default:
SSL_set_tlsext_host_name(_ssl, _endpoint->host().c_str());
}
SSL_set_connect_state(_ssl);
if (SSL_set_fd(_ssl, (int)TRI_get_fd_or_handle_of_socket(_socket)) != 1) {
_errorDetails = std::string("SSL: failed to create context ") +
ERR_error_string(ERR_get_error(), nullptr);
disconnectSocket();
_isConnected = false;
return false;
}
SSL_set_verify(_ssl, SSL_VERIFY_NONE, nullptr);
ERR_clear_error();
int ret = SSL_connect(_ssl);
if (ret != 1) {
_errorDetails.append("SSL: during SSL_connect: ");
int errorDetail;
long certError;
errorDetail = SSL_get_error(_ssl, ret);
if ((errorDetail == SSL_ERROR_WANT_READ) ||
(errorDetail == SSL_ERROR_WANT_WRITE)) {
return true;
}
/* Gets the earliest error code from the
thread's error queue and removes the entry. */
unsigned long lastError = ERR_get_error();
if (errorDetail == SSL_ERROR_SYSCALL && lastError == 0) {
if (ret == 0) {
_errorDetails +=
"an EOF was observed that violates the protocol. this may happen "
"when the other side has closed the connection";
} else if (ret == -1) {
_errorDetails += "I/O reported by BIO";
}
}
switch (errorDetail) {
case 0x1407E086:
/* 1407E086:
SSL routines:
SSL2_SET_CERTIFICATE:
certificate verify failed */
/* fall-through */
case 0x14090086:
/* 14090086:
SSL routines:
SSL3_GET_SERVER_CERTIFICATE:
certificate verify failed */
certError = SSL_get_verify_result(_ssl);
if (certError != X509_V_OK) {
_errorDetails += std::string("certificate problem: ") +
X509_verify_cert_error_string(certError);
} else {
_errorDetails =
std::string("certificate problem, verify that the CA cert is OK");
}
break;
default:
char errorBuffer[256];
ERR_error_string_n(errorDetail, errorBuffer, sizeof(errorBuffer));
_errorDetails += std::string(" - details: ") + errorBuffer;
break;
}
disconnectSocket();
_isConnected = false;
return false;
}
LOG_TOPIC("b3d52", TRACE, arangodb::Logger::FIXME)
<< "SSL connection opened: " << SSL_get_cipher(_ssl) << ", "
<< SSL_get_cipher_version(_ssl) << " ("
<< SSL_get_cipher_bits(_ssl, nullptr) << " bits)";
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief disconnect
////////////////////////////////////////////////////////////////////////////////
void SslClientConnection::disconnectSocket() {
_endpoint->disconnect();
TRI_invalidatesocket(&_socket);
if (_ssl != nullptr) {
SSL_free(_ssl);
_ssl = nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief write data to the connection
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::writeClientConnection(void const* buffer,
size_t length,
size_t* bytesWritten) {
TRI_ASSERT(bytesWritten != nullptr);
#ifdef _WIN32
char windowsErrorBuf[256];
#endif
*bytesWritten = 0;
if (_ssl == nullptr) {
return false;
}
int written = SSL_write(_ssl, buffer, (int)length);
int err = SSL_get_error(_ssl, written);
switch (err) {
case SSL_ERROR_NONE:
*bytesWritten = written;
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
_written += written;
#endif
return true;
case SSL_ERROR_ZERO_RETURN:
SSL_shutdown(_ssl);
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
break;
case SSL_ERROR_SYSCALL: {
char const* pErr = STR_ERROR();
_errorDetails =
std::string("SSL: while writing: SYSCALL returned errno = ") +
std::to_string(errno) + std::string(" - ") + pErr;
break;
}
case SSL_ERROR_SSL: {
/* A failure in the SSL library occurred, usually a protocol error.
The OpenSSL error queue contains more information on the error. */
unsigned long errorDetail = ERR_get_error();
char errorBuffer[256];
ERR_error_string_n(errorDetail, errorBuffer, sizeof(errorBuffer));
_errorDetails = std::string("SSL: while writing: ") + errorBuffer;
break;
}
default:
/* a true error */
_errorDetails =
std::string("SSL: while writing: error ") + std::to_string(err);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief read data from the connection
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::readClientConnection(StringBuffer& stringBuffer,
bool& connectionClosed) {
#ifdef _WIN32
char windowsErrorBuf[256];
#endif
connectionClosed = true;
if (_ssl == nullptr) {
return false;
}
if (!_isConnected) {
return true;
}
connectionClosed = false;
do {
again:
// reserve some memory for reading
if (stringBuffer.reserve(READBUFFER_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {
// out of memory
TRI_set_errno(TRI_ERROR_OUT_OF_MEMORY);
return false;
}
ERR_clear_error();
int lenRead = SSL_read(_ssl, stringBuffer.end(), READBUFFER_SIZE - 1);
switch (SSL_get_error(_ssl, lenRead)) {
case SSL_ERROR_NONE:
stringBuffer.increaseLength(lenRead);
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
_read += lenRead;
#endif
break;
case SSL_ERROR_ZERO_RETURN:
connectionClosed = true;
SSL_shutdown(_ssl);
_isConnected = false;
return true;
case SSL_ERROR_WANT_READ:
goto again;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_SYSCALL:
default: {
char const* pErr = STR_ERROR();
unsigned long errorDetail = ERR_get_error();
char errorBuffer[256];
ERR_error_string_n(errorDetail, errorBuffer, sizeof(errorBuffer));
_errorDetails = std::string("SSL: while reading: error '") +
std::to_string(errno) + std::string("' - ") +
errorBuffer + std::string("' - ") + pErr;
/* unexpected */
connectionClosed = true;
return false;
}
}
} while (readable());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return whether the connection is readable
////////////////////////////////////////////////////////////////////////////////
bool SslClientConnection::readable() {
// must use SSL_pending() and not select() as SSL_read() might read more
// bytes from the socket into the _ssl structure than we actually requested
// via SSL_read().
// if we used select() to check whether there is more data available, select()
// might return 0 already but we might not have consumed all bytes yet
// ...........................................................................
// SSL_pending(...) is an OpenSSL function which returns the number of bytes
// which are available inside ssl for reading.
// ...........................................................................
if (SSL_pending(_ssl) > 0) {
return true;
}
if (prepare(_socket, 0.0, false)) {
return checkSocket();
}
return false;
}
| 28.674797 | 80 | 0.593365 | LLcat1217 |
13ae8f62cb5077fa011fd21193a50167a84754a1 | 18,471 | cc | C++ | chromium/chrome/browser/android/data_usage/data_use_ui_tab_model_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/android/data_usage/data_use_ui_tab_model_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/android/data_usage/data_use_ui_tab_model_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/data_usage/data_use_ui_tab_model.h"
#include <stddef.h>
#include <stdint.h>
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "chrome/browser/android/data_usage/data_use_tab_model.h"
#include "chrome/browser/android/data_usage/data_use_ui_tab_model_factory.h"
#include "chrome/browser/android/data_usage/external_data_use_observer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "components/data_usage/core/data_use_aggregator.h"
#include "components/data_usage/core/data_use_amortizer.h"
#include "components/data_usage/core/data_use_annotator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
namespace chrome {
namespace android {
namespace {
const char kFooLabel[] = "foo_label";
const char kFooPackage[] = "com.foo";
class TestDataUseTabModel : public DataUseTabModel {
public:
TestDataUseTabModel() {}
~TestDataUseTabModel() override {}
using DataUseTabModel::NotifyObserversOfTrackingStarting;
using DataUseTabModel::NotifyObserversOfTrackingEnding;
};
class DataUseUITabModelTest : public testing::Test {
public:
DataUseUITabModelTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
DataUseUITabModel* data_use_ui_tab_model() { return &data_use_ui_tab_model_; }
ExternalDataUseObserver* external_data_use_observer() const {
return external_data_use_observer_.get();
}
TestDataUseTabModel* data_use_tab_model() const {
return data_use_tab_model_.get();
}
void RegisterURLRegexes(const std::vector<std::string>& app_package_name,
const std::vector<std::string>& domain_path_regex,
const std::vector<std::string>& label) {
data_use_tab_model_->RegisterURLRegexes(app_package_name, domain_path_regex,
label);
}
protected:
void SetUp() override {
io_task_runner_ = content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::IO);
ui_task_runner_ = content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::UI);
data_use_aggregator_.reset(
new data_usage::DataUseAggregator(nullptr, nullptr));
external_data_use_observer_.reset(new ExternalDataUseObserver(
data_use_aggregator_.get(), io_task_runner_, ui_task_runner_));
// Wait for |external_data_use_observer_| to create the Java object.
base::RunLoop().RunUntilIdle();
data_use_tab_model_.reset(new TestDataUseTabModel());
data_use_tab_model_->InitOnUIThread(
io_task_runner_, external_data_use_observer_->GetWeakPtr());
data_use_ui_tab_model_.SetDataUseTabModel(data_use_tab_model_.get());
data_use_tab_model_->OnControlAppInstallStateChange(true);
}
private:
content::TestBrowserThreadBundle thread_bundle_;
DataUseUITabModel data_use_ui_tab_model_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
scoped_ptr<data_usage::DataUseAggregator> data_use_aggregator_;
scoped_ptr<ExternalDataUseObserver> external_data_use_observer_;
scoped_ptr<TestDataUseTabModel> data_use_tab_model_;
};
} // namespace
// Tests that DataUseTabModel is notified of tab closure and navigation events,
// and DataUseTabModel notifies DataUseUITabModel.
TEST_F(DataUseUITabModelTest, ReportTabEventsTest) {
std::vector<std::string> url_regexes;
url_regexes.push_back(
"http://www[.]foo[.]com/#q=.*|https://www[.]foo[.]com/#q=.*");
RegisterURLRegexes(std::vector<std::string>(url_regexes.size(), kFooPackage),
url_regexes,
std::vector<std::string>(url_regexes.size(), kFooLabel));
const struct {
ui::PageTransition transition_type;
std::string expected_label;
} tests[] = {
{ui::PageTransitionFromInt(ui::PageTransition::PAGE_TRANSITION_LINK |
ui::PAGE_TRANSITION_FROM_API),
kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_LINK, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_TYPED, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()},
{ui::PageTransition::PAGE_TRANSITION_GENERATED, kFooLabel},
{ui::PageTransition::PAGE_TRANSITION_RELOAD, kFooLabel},
};
SessionID::id_type foo_tab_id = 100;
for (size_t i = 0; i < arraysize(tests); ++i) {
// Start a new tab.
++foo_tab_id;
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.foo.com/#q=abc"), tests[i].transition_type,
foo_tab_id);
// |data_use_ui_tab_model| should receive callback about starting of
// tracking of data usage for |foo_tab_id|.
EXPECT_EQ(!tests[i].expected_label.empty(),
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
std::string got_label;
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now(), &got_label);
EXPECT_EQ(tests[i].expected_label, got_label) << i;
// Report closure of tab.
data_use_ui_tab_model()->ReportTabClosure(foo_tab_id);
// DataUse object should not be labeled.
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id));
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now() + base::TimeDelta::FromMinutes(10),
&got_label);
EXPECT_EQ(std::string(), got_label) << i;
}
// Start a custom tab with matching package name and verify if tracking
// started is not being set.
const SessionID::id_type bar_tab_id = foo_tab_id + 1;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(bar_tab_id));
data_use_ui_tab_model()->ReportCustomTabInitialNavigation(
bar_tab_id, kFooPackage, std::string());
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(bar_tab_id));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(bar_tab_id));
data_use_ui_tab_model()->ReportTabClosure(bar_tab_id);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(bar_tab_id));
}
// Tests if the Entrance/Exit UI state is tracked correctly.
TEST_F(DataUseUITabModelTest, EntranceExitState) {
const SessionID::id_type kFooTabId = 1;
const SessionID::id_type kBarTabId = 2;
const SessionID::id_type kBazTabId = 3;
// CheckAndResetDataUseTrackingStarted should return true only once.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBarTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBarTabId));
// CheckAndResetDataUseTrackingEnded should return true only once.
data_use_tab_model()->NotifyObserversOfTrackingEnding(kFooTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// The tab enters the tracking state again.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// The tab exits the tracking state.
data_use_tab_model()->NotifyObserversOfTrackingEnding(kFooTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// The tab enters the tracking state again.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
data_use_tab_model()->NotifyObserversOfTrackingStarting(kFooTabId);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kFooTabId));
// ShowExit should return true only once.
data_use_tab_model()->NotifyObserversOfTrackingEnding(kBarTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBarTabId));
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBarTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBarTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBarTabId));
data_use_ui_tab_model()->ReportTabClosure(kFooTabId);
data_use_ui_tab_model()->ReportTabClosure(kBarTabId);
// CheckAndResetDataUseTrackingStarted/Ended should return false for closed
// tabs.
data_use_tab_model()->NotifyObserversOfTrackingStarting(kBazTabId);
data_use_ui_tab_model()->ReportTabClosure(kBazTabId);
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(kBazTabId));
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(kBazTabId));
}
// Tests if the Entrance/Exit UI state is tracked correctly.
TEST_F(DataUseUITabModelTest, EntranceExitStateForDialog) {
const SessionID::id_type kFooTabId = 1;
std::vector<std::string> url_regexes;
url_regexes.push_back(
"http://www[.]foo[.]com/#q=.*|https://www[.]foo[.]com/#q=.*");
RegisterURLRegexes(std::vector<std::string>(url_regexes.size(), kFooPackage),
url_regexes,
std::vector<std::string>(url_regexes.size(), kFooLabel));
SessionID::id_type foo_tab_id = kFooTabId;
const struct {
// True if a dialog box was shown to the user. It may not be shown if the
// user has previously selected the option to opt out.
bool continue_dialog_box_shown;
bool user_proceeded_with_navigation;
} tests[] = {
{false, false}, {true, true}, {true, false},
};
for (size_t i = 0; i < arraysize(tests); ++i) {
// Start a new tab.
++foo_tab_id;
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.foo.com/#q=abc"), ui::PAGE_TRANSITION_GENERATED,
foo_tab_id);
// |data_use_ui_tab_model| should receive callback about starting of
// tracking of data usage for |foo_tab_id|.
EXPECT_TRUE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
std::string got_label;
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now(), &got_label);
EXPECT_EQ(kFooLabel, got_label) << i;
// Tab enters non-tracking state.
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.bar.com/#q=abc"),
ui::PageTransition::PAGE_TRANSITION_TYPED, foo_tab_id);
EXPECT_TRUE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
EXPECT_FALSE(
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(foo_tab_id))
<< i;
// Tab enters tracking state.
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.foo.com/#q=abc"), ui::PAGE_TRANSITION_GENERATED,
foo_tab_id);
EXPECT_TRUE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingStarted(
foo_tab_id))
<< i;
// Tab may enter non-tracking state.
EXPECT_TRUE(data_use_ui_tab_model()->WouldDataUseTrackingEnd(
"https://www.bar.com/#q=abc", ui::PageTransition::PAGE_TRANSITION_TYPED,
foo_tab_id));
if (tests[i].continue_dialog_box_shown &&
tests[i].user_proceeded_with_navigation) {
data_use_ui_tab_model()->UserClickedContinueOnDialogBox(foo_tab_id);
}
if (tests[i].user_proceeded_with_navigation) {
data_use_ui_tab_model()->ReportBrowserNavigation(
GURL("https://www.bar.com/#q=abc"),
ui::PageTransition::PAGE_TRANSITION_TYPED, foo_tab_id);
}
const std::string expected_label =
tests[i].user_proceeded_with_navigation ? "" : kFooLabel;
data_use_tab_model()->GetLabelForTabAtTime(
foo_tab_id, base::TimeTicks::Now(), &got_label);
EXPECT_EQ(expected_label, got_label) << i;
if (tests[i].user_proceeded_with_navigation) {
// No UI element should be shown afterwards if the dialog box was shown
// before.
EXPECT_NE(tests[i].continue_dialog_box_shown,
data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(
foo_tab_id))
<< i;
} else {
EXPECT_FALSE(data_use_ui_tab_model()->CheckAndResetDataUseTrackingEnded(
foo_tab_id))
<< i;
}
}
}
// Checks if page transition type is converted correctly.
TEST_F(DataUseUITabModelTest, ConvertTransitionType) {
DataUseTabModel::TransitionType transition_type;
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_TYPED | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_NAVIGATION, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_BOOKMARK | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_BOOKMARK, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_GENERATED | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_OMNIBOX_SEARCH, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD), &transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD | 0xFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD | 0xFFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
EXPECT_TRUE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD | 0x12FFFF00),
&transition_type));
EXPECT_EQ(DataUseTabModel::TRANSITION_RELOAD, transition_type);
// Navigating back or forward.
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_RELOAD |
ui::PAGE_TRANSITION_FORWARD_BACK),
&transition_type));
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_AUTO_SUBFRAME), &transition_type));
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_MANUAL_SUBFRAME),
&transition_type));
EXPECT_FALSE(data_use_ui_tab_model()->ConvertTransitionType(
ui::PageTransition(ui::PAGE_TRANSITION_FORM_SUBMIT), &transition_type));
}
} // namespace android
} // namespace chrome
| 41.507865 | 80 | 0.747929 | wedataintelligence |
13afe562cb97b33f540a1e8e585c0a7f50de2a24 | 51 | cpp | C++ | CompileUnits/example/src/bin/cli/src/main.cpp | yyunon/cmake-modules | 141e793b42c0702e7b73570960bf7f6e23501496 | [
"Apache-2.0"
] | 1 | 2019-06-06T06:28:50.000Z | 2019-06-06T06:28:50.000Z | CompileUnits/example/src/bin/cli/src/main.cpp | yyunon/cmake-modules | 141e793b42c0702e7b73570960bf7f6e23501496 | [
"Apache-2.0"
] | 7 | 2019-06-03T12:17:03.000Z | 2022-01-13T15:54:21.000Z | CompileUnits/example/src/bin/cli/src/main.cpp | yyunon/cmake-modules | 141e793b42c0702e7b73570960bf7f6e23501496 | [
"Apache-2.0"
] | 1 | 2021-05-31T06:27:47.000Z | 2021-05-31T06:27:47.000Z | #include <example/lib/c.hpp>
int main() {
c();
}
| 8.5 | 28 | 0.568627 | yyunon |
13b07629f927f12728ba1c9eeda44a572d8aa5da | 356 | hpp | C++ | src/TypeTraits.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/TypeTraits.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/TypeTraits.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | // Copyright 2013, James Mitchell, All rights reserved.
#pragma once
#include "typetraits/EnableIf.hpp"
#include "typetraits/CallTraits.hpp"
#include "typetraits/HasOstreamOut.hpp"
#include "typetraits/HasMemberFunction.hpp"
#include "typetraits/IsArithmetic.hpp"
#include "typetraits/IsPointer.hpp"
#include "typetraits/IsSame.hpp"
namespace util
{
}
| 20.941176 | 55 | 0.789326 | jmitchell24 |
13b0a0104b85e1f4b72acdabf300ee0e2be3023b | 383 | cpp | C++ | chapter_4_computation/exercise/square_rice.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | chapter_4_computation/exercise/square_rice.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | chapter_4_computation/exercise/square_rice.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | #include "../../std_lib_facilities.h"
int square(int x)
{
return x * x;
}
int main(void)
{
//constexpr int first {1000};
//constexpr int second {1000000};
constexpr int third {1000000000};
bool is_overflow{false};
for (int i{0}, temp{0}; is_overflow || temp < third; ++i)
{
temp = square(i);
cout << i << " : " << temp << "\n";
}
} | 18.238095 | 61 | 0.537859 | jamie-prog |
13b5c3fb34fecf57c52a99f9100cfde6b29d2d1c | 2,372 | cpp | C++ | ares/ngp/system/system.cpp | kirwinia/ares-emu-v121 | 722aa227caf943a4a64f1678c1bdd07b38b15caa | [
"0BSD"
] | 2 | 2021-06-28T06:04:56.000Z | 2021-06-28T11:30:20.000Z | ares/ngp/system/system.cpp | kirwinia/ares-emu-v121 | 722aa227caf943a4a64f1678c1bdd07b38b15caa | [
"0BSD"
] | null | null | null | ares/ngp/system/system.cpp | kirwinia/ares-emu-v121 | 722aa227caf943a4a64f1678c1bdd07b38b15caa | [
"0BSD"
] | 1 | 2021-06-28T06:05:04.000Z | 2021-06-28T06:05:04.000Z | #include <ngp/ngp.hpp>
namespace ares::NeoGeoPocket {
auto enumerate() -> vector<string> {
return {
"[SNK] Neo Geo Pocket",
"[SNK] Neo Geo Pocket Color",
};
}
auto load(Node::System& node, string name) -> bool {
if(!enumerate().find(name)) return false;
return system.load(node, name);
}
Scheduler scheduler;
System system;
#include "controls.cpp"
#include "debugger.cpp"
#include "serialization.cpp"
auto System::game() -> string {
if(cartridge.node) {
return cartridge.title();
}
return "(no cartridge connected)";
}
auto System::run() -> void {
scheduler.enter();
}
auto System::load(Node::System& root, string name) -> bool {
if(node) unload();
information = {};
if(name.find("Neo Geo Pocket")) {
information.name = "Neo Geo Pocket";
information.model = Model::NeoGeoPocket;
}
if(name.find("Neo Geo Pocket Color")) {
information.name = "Neo Geo Pocket Color";
information.model = Model::NeoGeoPocketColor;
}
node = Node::System::create(information.name);
node->setGame({&System::game, this});
node->setRun({&System::run, this});
node->setPower({&System::power, this});
node->setSave({&System::save, this});
node->setUnload({&System::unload, this});
node->setSerialize({&System::serialize, this});
node->setUnserialize({&System::unserialize, this});
root = node;
if(!node->setPak(pak = platform->pak(node))) return false;
fastBoot = node->append<Node::Setting::Boolean>("Fast Boot", false);
bios.allocate(64_KiB);
if(auto fp = pak->read("bios.rom")) {
bios.load(fp);
}
scheduler.reset();
controls.load(node);
cpu.load(node);
apu.load(node);
kge.load(node);
psg.load(node);
cartridgeSlot.load(node);
debugger.load(node);
return true;
}
auto System::save() -> void {
if(!node) return;
cpu.save();
apu.save();
cartridge.save();
}
auto System::unload() -> void {
if(!node) return;
debugger.unload(node);
bios.reset();
cpu.unload();
apu.unload();
kge.unload();
psg.unload();
cartridgeSlot.unload();
pak.reset();
node.reset();
}
auto System::power(bool reset) -> void {
for(auto& setting : node->find<Node::Setting::Setting>()) setting->setLatch();
cartridge.power();
cpu.power();
apu.power();
kge.power();
psg.power();
scheduler.power(cpu);
if(fastBoot->latch() && cartridge.flash[0]) cpu.fastBoot();
}
}
| 21.369369 | 80 | 0.642496 | kirwinia |
13b71c408f3bce3cfa75daab08f07ca2b81945c8 | 1,058 | cpp | C++ | Q12/Q12.cpp | d9vya/Operating-Systems-Practical | 01ff599d94e955035e8d433037e23262abda2a97 | [
"MIT"
] | null | null | null | Q12/Q12.cpp | d9vya/Operating-Systems-Practical | 01ff599d94e955035e8d433037e23262abda2a97 | [
"MIT"
] | null | null | null | Q12/Q12.cpp | d9vya/Operating-Systems-Practical | 01ff599d94e955035e8d433037e23262abda2a97 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum = 0;
void *summer(void *); //function to run inside thread
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_attr_t attr;
if (argc != 2) // if 2 arguments are not passed on commandline, show error
{
fprintf(stderr, "usage: %s <integer value>\n", argv[0]);
exit(1);
}
else if (atoi(argv[1]) < 0) // if a negative value is passed as an argument, show error
{
fprintf(stderr, "integer value must be > 0\n");
exit(1);
}
pthread_attr_init(&attr); // initializing attributes of the thread
pthread_create(&tid, &attr, summer, argv[1]); // creating thread
pthread_join(tid,NULL); // wating for thread to exit
printf("SUM: %d\n",sum);
return 0;
}
void *summer(void *param)
{
int n = atoi((char*)param);
for(int i=0;i<=n;i++)
sum+=i;
pthread_exit(0);
}
| 28.594595 | 111 | 0.528355 | d9vya |
13b7a78535c5570233c5d97bdad43f941eac46d1 | 259 | cpp | C++ | SPOJ/Week 1/next/next.cpp | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | SPOJ/Week 1/next/next.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | SPOJ/Week 1/next/next.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<iostream>
using namespace std;
int main(){
unsigned long a,b,c;
cin>>a>>b>>c;
while(a != 0, b != 0, c != 0){
if(c-b == b-a){
cout<<"AP "<< c + c - b<<endl;
}
else{
cout<<"GP "<< c * (c/b) <<endl;
}
cin>>a>>b>>c;
}
return 0;
}
| 14.388889 | 34 | 0.46332 | VastoLorde95 |
13b9b6f361d58a27c59637e7abe9c8078bfeddb9 | 23,451 | cpp | C++ | win32/src/win32profilemodule.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | 3 | 2020-06-18T16:57:44.000Z | 2020-07-21T17:52:06.000Z | win32/src/win32profilemodule.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | win32/src/win32profilemodule.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | // @doc
#include "PyWinTypes.h"
#include "PyWinObjects.h"
#include "malloc.h"
#include "Userenv.h"
#define CHECK_PFN(fname) \
if (pfn##fname == NULL) \
return PyErr_Format(PyExc_NotImplementedError, "%s is not available on this platform", #fname);
typedef BOOL(WINAPI *DeleteProfilefunc)(WCHAR *, WCHAR *, WCHAR *);
static DeleteProfilefunc pfnDeleteProfile = NULL;
typedef BOOL(WINAPI *GetAllUsersProfileDirectoryfunc)(WCHAR *, DWORD *);
static GetAllUsersProfileDirectoryfunc pfnGetAllUsersProfileDirectory = NULL;
typedef BOOL(WINAPI *GetDefaultUserProfileDirectoryfunc)(WCHAR *, DWORD *);
static GetDefaultUserProfileDirectoryfunc pfnGetDefaultUserProfileDirectory = NULL;
typedef BOOL(WINAPI *GetProfilesDirectoryfunc)(WCHAR *, DWORD *);
static GetProfilesDirectoryfunc pfnGetProfilesDirectory = NULL;
typedef BOOL(WINAPI *GetProfileTypefunc)(DWORD *);
static GetProfileTypefunc pfnGetProfileType = NULL;
typedef BOOL(WINAPI *GetUserProfileDirectoryfunc)(HANDLE, WCHAR *, DWORD *);
static GetUserProfileDirectoryfunc pfnGetUserProfileDirectory = NULL;
typedef BOOL(WINAPI *LoadUserProfilefunc)(HANDLE, LPPROFILEINFOW);
static LoadUserProfilefunc pfnLoadUserProfile = NULL;
typedef BOOL(WINAPI *UnloadUserProfilefunc)(HANDLE, HANDLE);
static UnloadUserProfilefunc pfnUnloadUserProfile = NULL;
typedef BOOL(WINAPI *ExpandEnvironmentStringsForUserfunc)(HANDLE, LPWSTR, LPWSTR, DWORD);
static ExpandEnvironmentStringsForUserfunc pfnExpandEnvironmentStringsForUser = NULL;
/* Takes an environment block and returns a dict suitable for passing to CreateProcess
or CreateProcessAsUser. Length is not known, so you have to depend on the block being correctly formatted.
There are also several other pieces of code handling these types of strings:
win32process(building an environment block from a dict), win32service (service dependencies),
win32print(list of driver files), win32api(REG_MULTI_SZ values)
Should probably consolidate into one place
*/
PyObject *PyWinObject_FromEnvironmentBlock(WCHAR *multistring)
{
PyObject *key, *val, *ret = NULL;
WCHAR *eq;
size_t keylen, vallen, totallen;
if (multistring == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
ret = PyDict_New();
if (ret == NULL)
return NULL;
totallen = wcslen(multistring);
while (totallen) {
/* Use *last* equal sign as separator, since per-drive working dirs are stored in the environment in the form
"=C:=C:\\somedir","=D:=D:\\someotherdir". These are retrievable by win32api.GetEnvironmentVariable('=C:'),
but don't appear in os.environ and are apparently undocumented
*/
eq = wcsrchr(multistring, '=');
if (eq == NULL) {
// Use blank string for value if no equal sign present. ???? Maybe throw an error instead ????
vallen = 0;
val = PyWinObject_FromWCHAR(L"");
}
else {
vallen = wcslen(++eq);
val = PyUnicode_FromWideChar(eq, vallen);
}
keylen = totallen - (vallen + 1);
key = PyUnicode_FromWideChar(multistring, keylen);
if ((key == NULL) || (val == NULL) || (PyDict_SetItem(ret, key, val) == -1)) {
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(ret);
return NULL;
}
Py_DECREF(key);
Py_DECREF(val);
multistring += (totallen + 1);
totallen = wcslen(multistring);
}
return ret;
}
void PyWinObject_FreePROFILEINFO(LPPROFILEINFO pi)
{
PyWinObject_FreeWCHAR(pi->lpUserName);
PyWinObject_FreeWCHAR(pi->lpProfilePath);
PyWinObject_FreeWCHAR(pi->lpDefaultPath);
PyWinObject_FreeWCHAR(pi->lpServerName);
PyWinObject_FreeWCHAR(pi->lpPolicyPath);
ZeroMemory(pi, sizeof(PROFILEINFO));
}
// @object PyPROFILEINFO|Dictionary containing data to fill a PROFILEINFO struct, to be passed to <om
// win32profile.LoadUserProfile>. UserName is only required member.
// @pyseeapi PROFILEINFO
// @prop <o PyUnicode>|UserName|Name of user for which to load profile
// @prop int|Flags|Combination of PI_* flags
// @prop <o PyUnicode>|ProfilePath|Path to roaming profile, can be None. Use <om win32net.NetUserGetInfo> to retrieve
// user's profile path
// @prop <o PyUnicode>|DefaultPath|Path to Default user profile, can be None
// @prop <o PyUnicode>|ServerName|Domain controller, can be None
// @prop <o PyUnicode>|PolicyPath|Location of policy file, can be None
// @prop <o PyHKEY>|Profile|Handle to root of user's registry key. This member is output.
BOOL PyWinObject_AsPROFILEINFO(PyObject *ob, LPPROFILEINFO pi)
{
BOOL ret;
static char *elements[] = {"UserName", "Flags", "ProfilePath", "DefaultPath",
"ServerName", "PolicyPath", "Profile", NULL};
PyObject *obUserName = Py_None, *obProfilePath = Py_None, *obDefaultPath = Py_None, *obServerName = Py_None,
*obPolicyPath = Py_None, *obhProfile = Py_None;
PyObject *dummy_args = NULL;
ZeroMemory(pi, sizeof(PROFILEINFOW));
pi->dwSize = sizeof(PROFILEINFOW);
if (!PyDict_Check(ob)) {
PyErr_SetString(PyExc_TypeError, "PROFILEINFO must be a dictionary");
return FALSE;
}
dummy_args = PyTuple_New(0);
if (dummy_args == NULL)
return FALSE;
ret = PyArg_ParseTupleAndKeywords(dummy_args, ob, "O|kOOOOO:LoadUserProfile", elements, &obUserName, &pi->dwFlags,
&obProfilePath, &obDefaultPath, &obServerName, &obPolicyPath, &obhProfile) &&
PyWinObject_AsWCHAR(obUserName, &pi->lpUserName, FALSE) &&
PyWinObject_AsWCHAR(obProfilePath, &pi->lpProfilePath, TRUE) &&
PyWinObject_AsWCHAR(obDefaultPath, &pi->lpDefaultPath, TRUE) &&
PyWinObject_AsWCHAR(obServerName, &pi->lpServerName, TRUE) &&
PyWinObject_AsWCHAR(obPolicyPath, &pi->lpPolicyPath, TRUE) && PyWinObject_AsHANDLE(obhProfile, &pi->hProfile);
Py_DECREF(dummy_args);
if (!ret)
PyWinObject_FreePROFILEINFO(pi);
return ret;
}
// @pymethod <o PyHKEY>|win32profile|LoadUserProfile|Loads user settings into registry
// @comm SE_BACKUP_NAME and SE_RESTORE_NAME privs are required, but do not have to be enabled
// @rdesc Returns a handle to user's registry key.
PyObject *PyLoadUserProfile(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "ProfileInfo", NULL};
CHECK_PFN(LoadUserProfile)
PyObject *obhToken, *obPROFILEINFO, *ret = NULL;
HANDLE hToken;
DWORD dwFlags = 0;
BOOL success = TRUE;
PROFILEINFOW profileinfo = {NULL};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "OO:LoadUserProfile", keywords,
&obhToken, // @pyparm <o PyHANDLE>|hToken||Logon token as returned by <om win32security.LogonUser>, <om
// win32security.OpenThreadToken>, etc
&obPROFILEINFO)) // @pyparm <o PyPROFILEINFO>|ProfileInfo||Dictionary representing a PROFILEINFO structure
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
if (!PyWinObject_AsPROFILEINFO(obPROFILEINFO, &profileinfo))
return NULL;
if (!(*pfnLoadUserProfile)(hToken, &profileinfo))
PyWin_SetAPIError("LoadUserProfile");
else
ret = new PyHKEY(profileinfo.hProfile);
PyWinObject_FreePROFILEINFO(&profileinfo);
return ret;
}
// @pymethod |win32profile|UnloadUserProfile|Unloads user profile loaded by <om win32profile.LoadUserProfile>
PyObject *PyUnloadUserProfile(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "Profile", NULL};
CHECK_PFN(UnloadUserProfile);
PyObject *obhToken = NULL, *obhProfile = NULL;
HANDLE hToken, hProfile;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO:UnloadUserProfile", keywords,
&obhToken, // @pyparm <o PyHANDLE>|Token||Logon token as returned by <om
// win32security.LogonUser>, <om win32security.OpenProcessToken>, etc
&obhProfile)) // @pyparm <o PyHKEY>|Profile||Registry handle as returned by <om
// win32profile.LoadUserProfile>
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
if (!PyWinObject_AsHANDLE(obhProfile, &hProfile))
return NULL;
if (!(*pfnUnloadUserProfile)(hToken, hProfile)) {
PyWin_SetAPIError("UnloadUserProfile");
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyUnicode>|win32profile|GetProfilesDirectory|Retrieves directory where user profiles are stored
static PyObject *PyGetProfilesDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetProfilesDirectory);
WCHAR *profile_path = NULL;
DWORD bufsize = 0, err = 0;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetProfilesDirectory", keywords))
return (NULL);
(*pfnGetProfilesDirectory)(profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetProfilesDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d characters", bufsize);
return NULL;
}
if (!(*pfnGetProfilesDirectory)(profile_path, &bufsize))
PyWin_SetAPIError("GetProfilesDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
// @pymethod <o PyUnicode>|win32profile|GetAllUsersProfileDirectory|Retrieve All Users profile path
static PyObject *PyGetAllUsersProfileDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetAllUsersProfileDirectory);
WCHAR *profile_path = NULL;
DWORD bufsize = 0, err = 0;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetAllUsersProfileDirectory", keywords))
return (NULL);
(*pfnGetAllUsersProfileDirectory)(profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetAllUsersProfileDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d characters", bufsize);
return NULL;
}
if (!(*pfnGetAllUsersProfileDirectory)(profile_path, &bufsize))
PyWin_SetAPIError("GetAllUsersProfileDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
// @pymethod <o PyUnicode>|win32profile|GetDefaultUserProfileDirectory|Retrieve Default user profile
static PyObject *PyGetDefaultUserProfileDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetDefaultUserProfileDirectory);
WCHAR *profile_path = NULL;
DWORD bufsize = 0, err = 0;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetDefaultUserProfileDirectory", keywords))
return (NULL);
(*pfnGetDefaultUserProfileDirectory)(profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetDefaultUserProfileDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_SetString(PyExc_MemoryError, "GetDefaultUserProfileDirectory unable to allocate unicode buffer");
return NULL;
}
if (!(*pfnGetDefaultUserProfileDirectory)(profile_path, &bufsize))
PyWin_SetAPIError("GetDefaultUserProfileDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
// @pymethod <o PyUnicode>|win32profile|GetUserProfileDirectory|Returns profile directory for a logon token
PyObject *PyGetUserProfileDirectory(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", NULL};
CHECK_PFN(GetUserProfileDirectory);
HANDLE hToken;
WCHAR *profile_path = NULL;
DWORD bufsize = 0;
PyObject *obhToken = NULL, *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "O:GetUserProfileDirectory", keywords,
&obhToken)) // @pyparm <o PyHANDLE>|Token||User token as returned by <om win32security.LogonUser>
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
(*pfnGetUserProfileDirectory)(hToken, profile_path, &bufsize);
if (bufsize == 0)
return PyWin_SetAPIError("GetUserProfileDirectory");
profile_path = (WCHAR *)malloc(bufsize * sizeof(WCHAR));
if (profile_path == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d characters", bufsize);
return NULL;
}
if (!(*pfnGetUserProfileDirectory)(hToken, profile_path, &bufsize))
PyWin_SetAPIError("GetUserProfileDirectory");
else
ret = PyWinObject_FromWCHAR(profile_path);
free(profile_path);
return ret;
}
//@pymethod |win32profile|DeleteProfile|Remove profile for a user identified by string SID from specified machine.
PyObject *PyDeleteProfile(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"SidString", "ProfilePath", "ComputerName", NULL};
CHECK_PFN(DeleteProfile);
PyObject *obstrsid = Py_None, *obprofile_path = Py_None, *obmachine = Py_None, *ret = NULL;
WCHAR *strsid = NULL, *profile_path = NULL, *machine = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OO:DeleteProfile", keywords,
&obstrsid, // @pyparm <o PyUnicode>|SidString||String representation of user's
// Sid. See <om win32security.ConvertSidToStringSid>.
&obprofile_path, // @pyparm <o PyUnicode>|ProfilePath|None|Profile directory,
// value queried from registry if not specified
&obmachine)) // @pyparm <o PyUnicode>|ComputerName|None|Name of computer from
// which to delete profile, local machine assumed if not specified
return NULL;
if (PyWinObject_AsWCHAR(obstrsid, &strsid, FALSE) && PyWinObject_AsWCHAR(obprofile_path, &profile_path, TRUE) &&
PyWinObject_AsWCHAR(obmachine, &machine, TRUE)) {
if ((*pfnDeleteProfile)(strsid, profile_path, machine)) {
Py_INCREF(Py_None);
ret = Py_None;
}
else
PyWin_SetAPIError("DeleteProfile");
}
PyWinObject_FreeWCHAR(strsid);
PyWinObject_FreeWCHAR(profile_path);
PyWinObject_FreeWCHAR(machine);
return ret;
}
// @pymethod int|win32profile|GetProfileType|Returns type of current user's profile
// @rdesc Returns a combination of PT_* flags
PyObject *PyGetProfileType(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
CHECK_PFN(GetProfileType);
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetProfileType", keywords))
return NULL;
DWORD ptype = 0;
if (!(*pfnGetProfileType)(&ptype)) {
PyWin_SetAPIError("GetProfileType");
return NULL;
}
return PyLong_FromUnsignedLong(ptype);
}
// @pymethod dict|win32profile|CreateEnvironmentBlock|Retrieves environment variables for a user
PyObject *PyCreateEnvironmentBlock(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "Inherit", NULL};
HANDLE hToken;
BOOL inherit;
LPVOID env;
PyObject *obhToken = NULL, *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "Ol:CreateEnvironmentBlock", keywords,
&obhToken, // @pyparm <o PyHANDLE>|Token||User token as returned by <om win32security.LogonUser>, use None
// to retrieve system variables only
&inherit)) // @pyparm boolean|Inherit||Indicates if environment of current process should be inherited
return NULL;
if (!PyWinObject_AsHANDLE(obhToken, &hToken))
return NULL;
if (!CreateEnvironmentBlock(&env, hToken, inherit))
PyWin_SetAPIError("CreateEnvironmentBlock");
else {
ret = PyWinObject_FromEnvironmentBlock((WCHAR *)env);
DestroyEnvironmentBlock(env);
}
return ret;
}
// @pymethod dict|win32profile|GetEnvironmentStrings|Retrieves environment variables for current process
PyObject *PyGetEnvironmentStrings(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {NULL};
WCHAR *env;
PyObject *ret = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":GetEnvironmentStrings", keywords))
return NULL;
env = GetEnvironmentStrings();
if (env == NULL)
PyWin_SetAPIError("GetEnvironmentStrings");
else {
ret = PyWinObject_FromEnvironmentBlock((WCHAR *)env);
FreeEnvironmentStrings(env);
}
return ret;
}
//@pymethod <o PyUnicode>|win32profile|ExpandEnvironmentStringsForUser|Replaces environment variables in a string with
// per-user values
PyObject *PyExpandEnvironmentStringsForUser(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"Token", "Src", NULL};
CHECK_PFN(ExpandEnvironmentStringsForUser);
PyObject *obtoken, *obsrc, *ret = NULL;
HANDLE htoken;
WCHAR *src = NULL, *dst = NULL;
DWORD bufsize;
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "OO:ExpandEnvironmentStringsForUser", keywords,
&obtoken, // @pyparm <o PyHANDLE>|Token||The logon token for a user. Use None for system variables.
&obsrc)) // @pyparm <o PyUnicode>|Src||String containing environment variables enclosed in % signs
return NULL;
if (!PyWinObject_AsHANDLE(obtoken, &htoken) || !PyWinObject_AsWCHAR(obsrc, &src, FALSE, &bufsize))
return NULL;
// Increase initial allocation to reduce reallocation
// MSDN says the Size param is in TCHARS, but it acts as if it's in bytes
bufsize *= 4;
while (TRUE) {
if (dst != NULL)
free(dst);
bufsize *= 2;
dst = (WCHAR *)malloc(bufsize);
if (dst == NULL) {
PyErr_Format(PyExc_MemoryError, "Unable to allocate %d bytes", bufsize);
break;
}
if ((*pfnExpandEnvironmentStringsForUser)(htoken, src, dst, bufsize)) {
ret = PyWinObject_FromWCHAR(dst);
break;
}
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
PyWin_SetAPIError("ExpandEnvironmentStringsForUser");
break;
}
}
PyWinObject_FreeWCHAR(src);
if (dst != NULL)
free(dst);
return ret;
}
// @module win32profile|Wraps functions for dealing with user profiles
static struct PyMethodDef win32profile_functions[] = {
//@pymeth CreateEnvironmentBlock|Retrieves environment variables for a user
{"CreateEnvironmentBlock", (PyCFunction)PyCreateEnvironmentBlock, METH_VARARGS | METH_KEYWORDS,
"Retrieves environment variables for a user"},
// @pymeth DeleteProfile|Removes a user's profile
{"DeleteProfile", (PyCFunction)PyDeleteProfile, METH_VARARGS | METH_KEYWORDS, "Remove a user's profile"},
// @pymeth ExpandEnvironmentStringsForUser|Replaces environment variables in a string with per-user values
{"ExpandEnvironmentStringsForUser", (PyCFunction)PyExpandEnvironmentStringsForUser, METH_VARARGS | METH_KEYWORDS,
"Replaces environment variables in a string with per-user values"},
//@pymeth GetAllUsersProfileDirectory|Retrieve All Users profile directory
{"GetAllUsersProfileDirectory", (PyCFunction)PyGetAllUsersProfileDirectory, METH_VARARGS | METH_KEYWORDS,
"Retrieve All Users profile directory"},
//@pymeth GetDefaultUserProfileDirectory|Retrieve profile path for Default user
{"GetDefaultUserProfileDirectory", (PyCFunction)PyGetDefaultUserProfileDirectory, METH_VARARGS | METH_KEYWORDS,
"Retrieve profile path for Default user"},
//@pymeth GetEnvironmentStrings|Retrieves environment variables for current process
{"GetEnvironmentStrings", (PyCFunction)PyGetEnvironmentStrings, METH_VARARGS | METH_KEYWORDS,
"Retrieves environment variables for current process"},
//@pymeth GetProfilesDirectory|Retrieves directory where user profiles are stored
{"GetProfilesDirectory", (PyCFunction)PyGetProfilesDirectory, METH_VARARGS | METH_KEYWORDS,
"Retrieves directory where user profiles are stored"},
//@pymeth GetProfileType|Returns type of current user's profile
{"GetProfileType", (PyCFunction)PyGetProfileType, METH_VARARGS | METH_KEYWORDS,
"Returns type of current user's profile"},
// @pymeth GetUserProfileDirectory|Returns profile directory for a logon token
{"GetUserProfileDirectory", (PyCFunction)PyGetUserProfileDirectory, METH_VARARGS | METH_KEYWORDS,
"Returns profile directory for a logon token"},
//@pymeth LoadUserProfile|Load user settings for a login token
{"LoadUserProfile", (PyCFunction)PyLoadUserProfile, METH_VARARGS | METH_KEYWORDS,
"Load user settings for a login token"},
//@pymeth UnloadUserProfile|Unload profile loaded by LoadUserProfile
{"UnloadUserProfile", (PyCFunction)PyUnloadUserProfile, METH_VARARGS | METH_KEYWORDS,
"Unload profile loaded by LoadUserProfile"},
{NULL, NULL}};
PYWIN_MODULE_INIT_FUNC(win32profile)
{
PYWIN_MODULE_INIT_PREPARE(win32profile, win32profile_functions, "Interface to the User Profile Api.");
// PROFILEINFO flags
PyModule_AddIntConstant(module, "PI_NOUI", PI_NOUI);
PyModule_AddIntConstant(module, "PI_APPLYPOLICY", PI_APPLYPOLICY);
// profile types
PyModule_AddIntConstant(module, "PT_MANDATORY", PT_MANDATORY);
PyModule_AddIntConstant(module, "PT_ROAMING", PT_ROAMING);
PyModule_AddIntConstant(module, "PT_TEMPORARY", PT_TEMPORARY);
HMODULE hmodule;
hmodule = GetModuleHandle(L"Userenv.dll");
if (hmodule == NULL)
hmodule = LoadLibrary(L"Userenv.dll");
if (hmodule != NULL) {
pfnDeleteProfile = (DeleteProfilefunc)GetProcAddress(hmodule, "DeleteProfileW");
pfnExpandEnvironmentStringsForUser =
(ExpandEnvironmentStringsForUserfunc)GetProcAddress(hmodule, "ExpandEnvironmentStringsForUserW");
pfnGetAllUsersProfileDirectory =
(GetAllUsersProfileDirectoryfunc)GetProcAddress(hmodule, "GetAllUsersProfileDirectoryW");
pfnGetDefaultUserProfileDirectory =
(GetDefaultUserProfileDirectoryfunc)GetProcAddress(hmodule, "GetDefaultUserProfileDirectoryW");
pfnGetProfilesDirectory = (GetProfilesDirectoryfunc)GetProcAddress(hmodule, "GetProfilesDirectoryW");
pfnGetProfileType = (GetProfileTypefunc)GetProcAddress(hmodule, "GetProfileType");
pfnGetUserProfileDirectory = (GetUserProfileDirectoryfunc)GetProcAddress(hmodule, "GetUserProfileDirectoryW");
pfnLoadUserProfile = (LoadUserProfilefunc)GetProcAddress(hmodule, "LoadUserProfileW");
pfnUnloadUserProfile = (UnloadUserProfilefunc)GetProcAddress(hmodule, "UnloadUserProfile");
}
PYWIN_MODULE_INIT_RETURN_SUCCESS;
}
| 45.982353 | 120 | 0.695024 | huanyin88 |
13b9ea5b16da3fe9a715186421b1e1bc8706c7ba | 3,657 | cc | C++ | codebook/datastructures/Splay_Implicit.cc | jeffrey-xiao/acm-notebook | b8588429f2cb727f35e346e649e544bb1e67badd | [
"Apache-2.0",
"MIT"
] | 1 | 2020-02-19T14:02:54.000Z | 2020-02-19T14:02:54.000Z | codebook/datastructures/Splay_Implicit.cc | jeffrey-xiao/acm-notebook | b8588429f2cb727f35e346e649e544bb1e67badd | [
"Apache-2.0",
"MIT"
] | null | null | null | codebook/datastructures/Splay_Implicit.cc | jeffrey-xiao/acm-notebook | b8588429f2cb727f35e346e649e544bb1e67badd | [
"Apache-2.0",
"MIT"
] | 3 | 2017-11-28T07:23:27.000Z | 2020-03-01T07:46:23.000Z | /* The key of each element is the array index of the element.
* Time: O(log N)
* Memory: O(N)
*/
#include <bits/stdc++.h>
using namespace std;
struct Splay {
struct Node {
int val, sz;
Node *child[2], *par;
Node() {}
Node(int val, int sz = 1) : val(val), sz(sz) {
child[0] = child[1] = par = this;
}
};
Node *root;
static Node *null;
Splay() {
null = new Node();
null->child[0] = null->child[1] = null->par = null;
null->sz = 0;
root = null;
}
static void connect(Node *u, Node *v, int dir) {
u->child[dir] = v;
v->par = u;
}
static void update(Node *u) {
if (u != null)
u->sz = 1 + u->child[0]->sz + u->child[1]->sz;
}
// 0 = left, 1 = right;
static Node *rotate(Node *u, int dir) {
Node *c = u->child[dir ^ 1], *p = u->par, *pp = p->par;
connect(p, c, dir);
connect(u, p, dir ^ 1);
connect(pp, u, getDir(p, pp));
update(p);
update(u);
update(pp);
return u;
}
static int getDir(Node *u, Node *p) {
return p->child[0] == u ? 0 : 1;
}
static Node *splay(Node *u) {
while (u->par != null) {
Node *p = u->par, *pp = p->par;
int dp = getDir(u, p), dpp = getDir(p, pp);
if (pp == null)
rotate(u, dp);
else if (dp == dpp)
rotate(p, dpp), rotate(u, dp);
else
rotate(u, dp), rotate(u, dpp);
}
return u;
}
static Node *nodeAt(Node *u, int index) {
if (u == null)
return u;
Node *ret = u;
while (u != null) {
ret = u;
if (u->child[0]->sz + 1 < index)
index -= u->child[0]->sz + 1, u = u->child[1];
else if (u->child[0]->sz + 1 > index)
u = u->child[0];
else
return u;
}
return ret;
}
// precondition: all values of u are smaller than all values of v
static Node *join(Node *u, Node *v) {
if (u == null)
return v;
while (u->child[1] != null)
u = u->child[1];
splay(u);
u->child[1] = v;
update(u);
if (v != null)
v->par = u;
return u;
}
static pair<Node *, Node *> split(Node *u, int index) {
if (u == null)
return {null, null};
splay(u = nodeAt(u, index));
if (u->child[0]->sz + 1 <= index) {
Node *ret = u->child[1];
u->child[1] = (u->child[1]->par = null);
update(u);
update(ret);
return {u, ret};
} else {
Node *ret = u->child[0];
u->child[0] = (u->child[0]->par = null);
update(u);
update(ret);
return {ret, u};
}
}
void modify(int index, int val) {
Node *curr = root;
while (curr != null) {
if (curr->child[0]->sz + 1 < index)
index -= curr->child[0]->sz + 1, curr = curr->child[1];
else if (curr->child[0]->sz + 1 > index)
curr = curr->child[0];
else {
curr->val = val;
return;
}
}
}
void push_back(int val) {
Node *u = new Node(val);
u->child[0] = u->child[1] = u->par = null;
root = join(root, u);
}
void insert(int index, int val) {
auto res = split(root, index);
root = new Node(val);
root->par = null;
root->child[0] = res.first, root->child[1] = res.second;
update(root);
if (root->child[0] != null)
root->child[0]->par = root;
if (root->child[1] != null)
root->child[1]->par = root;
}
void remove(int index) {
Node *curr = nodeAt(root, index);
splay(curr);
curr->child[0]->par = curr->child[1]->par = null;
root = join(curr->child[0], curr->child[1]);
}
int get(int index) {
return nodeAt(root, index)->val;
}
};
Splay::Node *Splay::null = new Node(0, 0);
| 22.163636 | 67 | 0.493574 | jeffrey-xiao |
13ba2eb77ab63146ca1404944e10dd3993d8c034 | 694 | cpp | C++ | CodeForces/InsomniaCure.cpp | roshan11160/Competitive-Programming-Solutions | 2d9cfe901c23a2b7344c410b7368eb02f7fa6e7e | [
"MIT"
] | 40 | 2020-07-25T19:35:37.000Z | 2022-01-28T02:57:02.000Z | CodeForces/InsomniaCure.cpp | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 160 | 2021-04-26T19:04:15.000Z | 2022-03-26T20:18:37.000Z | CodeForces/InsomniaCure.cpp | afrozchakure/Hackerrank-Problem-Solutions | 014155d841e08cb1f7609c23335576dc9b29cef3 | [
"MIT"
] | 24 | 2020-05-03T08:11:53.000Z | 2021-10-04T03:23:20.000Z | #include <iostream>
using namespace std;
int main()
{
int k, l, m, n, d;
cin >> k >> l >> m >> n >> d;
// kth got punched in the face with frying pan
// lth got shut in the balcony door
// mmeth got his paws trampled
// nth to call her mom
int count = d;
if (l == 1 || k == 1 || m == 1 || n == 1)
cout << count << endl;
else
{
for (int i = 1; i <= d; i++)
{
// we are subtracting the ones where all are not divisible by
// any of k, l, m and n
if (i % k != 0 && i % l != 0 && i % m != 0 && i % n != 0)
count--;
}
cout << count << endl;
}
return 0;
} | 22.387097 | 73 | 0.432277 | roshan11160 |
13beb24b3f7fbd391cf301b7ef293b8015f702b5 | 3,140 | cpp | C++ | ad_map_access/impl/tests/access/GeometryStoreTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/tests/access/GeometryStoreTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/tests/access/GeometryStoreTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | 1 | 2020-10-27T11:09:30.000Z | 2020-10-27T11:09:30.000Z | // ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// Copyright (C) 2018-2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
//
// ----------------- END LICENSE BLOCK -----------------------------------
#include <ad/map/access/Factory.hpp>
#include <ad/map/access/Operation.hpp>
#include <ad/map/lane/LaneOperation.hpp>
#include <ad/map/point/Operation.hpp>
#include <ad/map/serialize/SerializerFileCRC32.hpp>
#include <gtest/gtest.h>
#include "../src/access/GeometryStore.hpp"
using namespace ::ad;
using namespace ::ad::map;
using namespace ::ad::map::point;
using namespace ::ad::map::lane;
struct GeometryStoreTest : ::testing::Test
{
GeometryStoreTest()
{
}
virtual void SetUp()
{
}
virtual void TearDown()
{
access::cleanup();
}
};
TEST_F(GeometryStoreTest, GeometryStore)
{
ASSERT_TRUE(access::init("test_files/Town01.txt"));
access::GeometryStore geoStore;
EXPECT_THROW(geoStore.store(NULL), std::runtime_error);
EXPECT_THROW(geoStore.restore(NULL), std::runtime_error);
EXPECT_THROW(geoStore.check(NULL), std::runtime_error);
auto lanes = lane::getLanes();
ASSERT_GT(lanes.size(), 0u);
auto lanePtr = lane::getLanePtr(lanes[0]);
ASSERT_TRUE(geoStore.store(lanePtr));
ASSERT_TRUE(geoStore.check(lanePtr));
lane::Lane::Ptr oneLane;
oneLane.reset(new lane::Lane());
oneLane->id = lanes[0];
ASSERT_TRUE(geoStore.restore(oneLane));
ASSERT_EQ(oneLane->edgeLeft.ecefEdge, lanePtr->edgeLeft.ecefEdge);
ASSERT_EQ(oneLane->edgeRight.ecefEdge, lanePtr->edgeRight.ecefEdge);
}
TEST_F(GeometryStoreTest, StoreSerialization)
{
ASSERT_TRUE(access::init("test_files/Town01.txt"));
access::Store &store = access::getStore();
size_t versionMajor = ::ad::map::serialize::SerializerFileCRC32::VERSION_MAJOR;
size_t versionMinor = ::ad::map::serialize::SerializerFileCRC32::VERSION_MINOR;
serialize::SerializerFileCRC32 serializer_w(true);
ASSERT_TRUE(serializer_w.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
ASSERT_TRUE(store.save(serializer_w, false, false, true));
ASSERT_TRUE(serializer_w.close());
serialize::SerializerFileCRC32 serializer_r(false);
ASSERT_EQ(serializer_r.getStorageType(), "File");
ASSERT_EQ(serializer_r.getChecksumType(), "CRC-32");
ASSERT_TRUE(serializer_r.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
access::Store::Ptr storeRead;
storeRead.reset(new access::Store());
ASSERT_TRUE(storeRead->load(serializer_r));
ASSERT_TRUE(serializer_r.close());
serialize::SerializerFileCRC32 serializer_w2(true);
ASSERT_TRUE(serializer_w2.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
ASSERT_TRUE(store.save(serializer_w2, false, true, true));
ASSERT_TRUE(serializer_w2.close());
serialize::SerializerFileCRC32 serializer_r2(false);
ASSERT_TRUE(serializer_r2.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
access::Store::Ptr storeRead2;
storeRead2.reset(new access::Store());
ASSERT_TRUE(storeRead2->load(serializer_r2));
ASSERT_TRUE(serializer_r2.close());
}
| 33.763441 | 104 | 0.729618 | seowwj |
13bfa37048e98d16dcf3768baccdd5b51d6b3e14 | 54 | cpp | C++ | src/victoryconnect/cpp/logger.cpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | src/victoryconnect/cpp/logger.cpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | src/victoryconnect/cpp/logger.cpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | #include "logger.hpp"
using namespace VictoryConnect;
| 18 | 31 | 0.814815 | victoryforphil |
13c47789b56d27a1375a573dd1e14827fd83f584 | 5,653 | cpp | C++ | src/cgp/minicgp_blindwatchmaker.cpp | dubkois/ReusWorld | 15ccf4dbde20d6b600b6e5dc706435d6dd4eb620 | [
"MIT"
] | null | null | null | src/cgp/minicgp_blindwatchmaker.cpp | dubkois/ReusWorld | 15ccf4dbde20d6b600b6e5dc706435d6dd4eb620 | [
"MIT"
] | null | null | null | src/cgp/minicgp_blindwatchmaker.cpp | dubkois/ReusWorld | 15ccf4dbde20d6b600b6e5dc706435d6dd4eb620 | [
"MIT"
] | null | null | null | #include <QApplication>
#include <QMainWindow>
#include <QGridLayout>
#include <QPushButton>
#include <QMouseEvent>
#include <QPainter>
#include <QTimer>
#include "kgd/external/cxxopts.hpp"
#include "kgd/utils/indentingostream.h"
#include "minicgp.h"
DEFINE_NAMESPACE_PRETTY_ENUMERATION(watchmaker, VideoInputs, X, Y, T, R, G, B)
DEFINE_NAMESPACE_PRETTY_ENUMERATION(watchmaker, RGBOutputs, R_, G_, B_)
using CGP = cgp::CGP<watchmaker::VideoInputs, 10, watchmaker::RGBOutputs>;
namespace watchmaker {
using Callback = std::function<void(const CGP&)>;
static constexpr int STEPS = 50;
static constexpr int LOOP_DURATION = 2; // seconds
struct CGPViewer : public QPushButton {
static constexpr int SIDE = 50;
static constexpr int MARGIN = 10;
static constexpr QSize SIZE = QSize(SIDE + 2 * MARGIN, SIDE + 2 * MARGIN);
CGP &cgp;
Callback callback;
QImage img;
int step;
bool up = true;
CGPViewer(CGP &cgp, Callback c)
: QPushButton(nullptr), cgp(cgp), callback(c),
img(SIDE, SIDE, QImage::Format_RGB32) {
img.fill(Qt::gray);
setFocusPolicy(Qt::NoFocus);
setAutoExclusive(true);
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
step = 0;
}
void cgpUpdated (void) {
setToolTip(QString::fromStdString(cgp.toTex()));
img.fill(Qt::gray);
}
void nextFrame (void) {
QRgb *pixels = reinterpret_cast<QRgb*>(img.scanLine(0));
CGP::Inputs inputs;
inputs[T] = 2. * step / (STEPS - 1) - 1;
for (int i=0; i<SIDE; i++) {
for (int j=0; j<SIDE; j++) {
inputs[X] = double(2) * i / (SIDE-1) - 1;
inputs[Y] = double(2) * j / (SIDE-1) - 1;
QRgb &pixel = pixels[i*SIDE+j];
inputs[R] = 2 * qRed(pixel) / 255. - 1;
inputs[G] = 2 * qGreen(pixel) / 255. - 1;
inputs[B] = 2 * qBlue(pixel) / 255. - 1;
CGP::Outputs outputs;
cgp.evaluate(inputs, outputs);
pixel = qRgb(255 * (outputs[R_] * .5 + .5),
255 * (outputs[G_] * .5 + .5),
255 * (outputs[B_] * .5 + .5));
}
}
if (up) {
step++;
up = (step < STEPS);
} else {
step--;
up = (step <= 0);
}
update();
}
QSize sizeHint (void) const {
return SIZE;
}
void paintEvent(QPaintEvent *event) {
QPushButton::paintEvent(event);
QPainter painter (this);
painter.drawImage(rect().adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN), img);
}
void mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton)
callback(cgp);
else if (event->button() == Qt::RightButton) {
static int i = 0;
std::ostringstream oss;
oss << "cgp_bw_test_" << i++ << ".pdf";
stdfs::path path = oss.str();
cgp.toDot(path, CGP::FULL | CGP::NO_ARITY);
oss.str("");
oss << "xdg-open " << path;
std::string cmd = oss.str();
system(cmd.c_str());
}
}
};
} // end of namespace watchmaker
int main (int argc, char *argv[]) {
// ===========================================================================
// == Command line arguments parsing
using Verbosity = config::Verbosity;
std::string configFile = "auto"; // Default to auto-config
Verbosity verbosity = Verbosity::SHOW;
cxxopts::Options options("MiniCGP-blindwatchmaker",
"Exhibit MiniCGP capabilities through a blind"
" watchmaker algorithm");
options.add_options()
("h,help", "Display help")
("a,auto-config", "Load configuration data from default location")
("c,config", "File containing configuration data",
cxxopts::value(configFile))
("v,verbosity", "Verbosity level. " + config::verbosityValues(),
cxxopts::value(verbosity))
;
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help()
<< std::endl;
return 0;
}
if (result.count("auto-config") && result["auto-config"].as<bool>())
configFile = "auto";
config::CGP::setupConfig(configFile, verbosity);
if (configFile.empty()) config::CGP::printConfig("");
rng::FastDice dice;
auto cgps = utils::make_array<CGP, 9>([&dice] (auto) {
return CGP::null(dice);
});
std::cout << "Generated with seed " << dice.getSeed() << std::endl;
QApplication app (argc, argv);
QMainWindow w;
QWidget *widget = new QWidget;
QGridLayout *layout = new QGridLayout;
w.setCentralWidget(widget);
widget->setLayout(layout);
std::array<watchmaker::CGPViewer*, 9> viewers;
auto updateCGPs = [&dice, &viewers, &cgps]
(const CGP &newParent) {
cgps[4] = newParent;
for (uint i=0; i<3; i++) {
for (uint j=0; j<3; j++) {
uint ix = i*3+j;
if (ix != 4) {
CGP child = newParent;
// std::cerr << "Mutating IX=" << ix << ", i=" << i << ", j=" << j
// << ":\n";
// utils::IndentingOStreambuf indent (std::cerr);
child.mutate(dice);
cgps[ix] = child;
// std::cerr << std::endl;
}
viewers[ix]->cgpUpdated();
}
}
};
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
uint ix = i*3+j;
auto viewer = new watchmaker::CGPViewer(cgps[ix], updateCGPs);
viewers[ix] = viewer;
layout->addWidget(viewer, i, j);
}
}
updateCGPs(cgps[4]);
w.show();
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&viewers] {
for (watchmaker::CGPViewer *v: viewers) v->nextFrame();
});
timer.start(watchmaker::LOOP_DURATION * 1000.f / watchmaker::STEPS);
return app.exec();
}
| 25.931193 | 80 | 0.576685 | dubkois |
13c64d792041bdde2c84df21cdcf831ad42c9002 | 15,723 | cpp | C++ | src/main.cpp | QE-Lab/dqcsim-qx | b9a95663233dbff43c0dd7f14bd964abe5422ffc | [
"Apache-2.0"
] | null | null | null | src/main.cpp | QE-Lab/dqcsim-qx | b9a95663233dbff43c0dd7f14bd964abe5422ffc | [
"Apache-2.0"
] | 1 | 2020-01-20T16:39:54.000Z | 2020-01-20T16:39:54.000Z | src/main.cpp | jvanstraten/dqcsim-qx | b9a95663233dbff43c0dd7f14bd964abe5422ffc | [
"Apache-2.0"
] | 1 | 2020-01-22T10:59:23.000Z | 2020-01-22T10:59:23.000Z | #include <dqcsim>
#include <memory>
#include <vector>
#include <xpu.h>
#include <xpu/runtime>
#include <qx_representation.h>
#include "json.hpp"
#include "bimap.hpp"
// Alias the dqcsim::wrap namespace to something shorter.
namespace dqcs = dqcsim::wrap;
/**
* Function pointer type for constructing/binding QX gates.
*/
using GateConstructor = void (*)(std::vector<qx::gate*>&, std::vector<size_t>&&, dqcs::ArbData&&);
/**
* Hadamard gate constructor.
*/
static void construct_h(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::hadamard(qubits[0]));
}
/**
* CNOT gate constructor.
*/
static void construct_cnot(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::cnot(qubits[0], qubits[1]));
}
/**
* Toffoli gate constructor.
*/
static void construct_toffoli(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::toffoli(qubits[0], qubits[1], qubits[2]));
}
/**
* Identity gate constructor.
*/
static void construct_identity(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::identity(qubits[0]));
}
/**
* X gate constructor.
*/
static void construct_pauli_x(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::pauli_x(qubits[0]));
}
/**
* Y gate constructor.
*/
static void construct_pauli_y(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::pauli_y(qubits[0]));
}
/**
* Z gate constructor.
*/
static void construct_pauli_z(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::pauli_z(qubits[0]));
}
/**
* S gate constructor.
*/
static void construct_s(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::phase_shift(qubits[0]));
}
/**
* S dagger gate constructor.
*/
static void construct_s_dag(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::s_dag_gate(qubits[0]));
}
/**
* T gate constructor.
*/
static void construct_t(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::t_gate(qubits[0]));
}
/**
* T dagger gate constructor.
*/
static void construct_t_dag(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::t_dag_gate(qubits[0]));
}
/**
* Controlled phase gate constructor.
*/
static void construct_ctrl_phase_shift(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
double angle = data.pop_arb_arg_as<double>();
gates.push_back(new qx::ctrl_phase_shift(qubits[0], qubits[1], angle));
}
/**
* Swap gate constructor.
*/
static void construct_swap(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::swap(qubits[0], qubits[1]));
}
/**
* RX gate constructor.
*/
static void construct_rx(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::rx(qubits[0], data.get_arb_arg_as<double>(0)));
}
/**
* RY gate constructor.
*/
static void construct_ry(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::ry(qubits[0], data.get_arb_arg_as<double>(0)));
}
/**
* RZ gate constructor.
*/
static void construct_rz(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
gates.push_back(new qx::rz(qubits[0], data.get_arb_arg_as<double>(0)));
}
/**
* Measure Z constructor.
*/
static void construct_measure_z(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::measure(qubit));
}
}
/**
* Measure X constructor.
*/
static void construct_measure_x(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::measure_x(qubit));
}
}
/**
* Measure Y constructor.
*/
static void construct_measure_y(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::measure_y(qubit));
}
}
/**
* Prep Z constructor.
*/
static void construct_prep_z(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::prepz(qubit));
}
}
/**
* Prep X constructor.
*/
static void construct_prep_x(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::prepx(qubit));
}
}
/**
* Prep Y constructor.
*/
static void construct_prep_y(std::vector<qx::gate*> &gates, std::vector<size_t> &&qubits, dqcs::ArbData &&data) {
for (size_t qubit : qubits) {
gates.push_back(new qx::prepy(qubit));
}
}
/**
* Main plugin class for QX.
*/
class QxPlugin {
public:
// List of gates that have been received but have not been simulated yet.
// The integer before the gate specifies the number of simulation cycles
// advanced between the previous gate and this gate.
std::vector<qx::gate*> pending;
// Number of qubits allocated/to allocate within QX. This can't be changed
// anymore once QX is initialized.
size_t num_qubits = 0;
// Counter for the circuit name generator.
size_t circuit_counter = 0;
// The current quantum register. Initialized only when the first measurement
// is received.
std::shared_ptr<qx::qu_register> qreg;
// Map from upstream qubits to QX qubits.
QubitBiMap dqcs2qx;
// Map from DQCsim gates to QX gates.
dqcs::GateMap<GateConstructor> gatemap;
// Values for the depolarizing channel error model.
bool depolarizing_channel = false;
double error_probability = 0.0;
// Epsilon for gate recognition.
double epsilon = 1.0e-6;
/**
* Initialization callback.
*/
void initialize(
dqcs::PluginState &state,
dqcs::ArbCmdQueue &&cmds
) {
// Parse parameters.
for (; cmds.size() > 0; cmds.next()) {
handle_cmd(state, &cmds);
}
// Construct the gatemap.
gatemap.with_unitary(construct_h, dqcs::PredefinedGate::H, 0, epsilon);
gatemap.with_unitary(construct_cnot, dqcs::PredefinedGate::X, 1, epsilon);
gatemap.with_unitary(construct_toffoli, dqcs::PredefinedGate::X, 2, epsilon);
gatemap.with_unitary(construct_identity, dqcs::PredefinedGate::I, 0, epsilon);
gatemap.with_unitary(construct_pauli_x, dqcs::PredefinedGate::X, 0, epsilon);
gatemap.with_unitary(construct_pauli_y, dqcs::PredefinedGate::Y, 0, epsilon);
gatemap.with_unitary(construct_pauli_z, dqcs::PredefinedGate::Z, 0, epsilon);
gatemap.with_unitary(construct_s, dqcs::PredefinedGate::S, 0, epsilon);
gatemap.with_unitary(construct_s_dag, dqcs::PredefinedGate::S_DAG, 0, epsilon);
gatemap.with_unitary(construct_t, dqcs::PredefinedGate::T, 0, epsilon);
gatemap.with_unitary(construct_t_dag, dqcs::PredefinedGate::T_DAG, 0, epsilon);
gatemap.with_unitary(construct_ctrl_phase_shift, dqcs::PredefinedGate::Phase, 1, epsilon);
gatemap.with_unitary(construct_swap, dqcs::PredefinedGate::Swap, 0, epsilon);
gatemap.with_unitary(construct_rx, dqcs::PredefinedGate::RX, 0, epsilon);
gatemap.with_unitary(construct_ry, dqcs::PredefinedGate::RY, 0, epsilon);
gatemap.with_unitary(construct_rz, dqcs::PredefinedGate::RZ, 0, epsilon);
gatemap.with_measure(construct_measure_z, dqcs::PauliBasis::Z, epsilon);
gatemap.with_measure(construct_measure_x, dqcs::PauliBasis::X, epsilon);
gatemap.with_measure(construct_measure_y, dqcs::PauliBasis::Y, epsilon);
gatemap.with_prep(construct_prep_z, dqcs::PauliBasis::Z, epsilon);
gatemap.with_prep(construct_prep_x, dqcs::PauliBasis::X, epsilon);
gatemap.with_prep(construct_prep_y, dqcs::PauliBasis::Y, epsilon);
}
/**
* Qubit allocation callback.
*
* DQCsim supports allocating and freeing qubits at will, but QX doesn't.
* The trivial solution would be to just error out on the N+1'th qubit
* allocation, but we can do better than that when there are deallocations
* as well by reusing qubits that were freed. Furthermore, we only initialize
* QX when the first measurement is performed, with as many qubits as have
* been allocated at that point. The dqcs2qx bimap is used to keep track of
* which upstream qubit maps to which QX qubit.
*/
void allocate(
dqcs::PluginState &state,
dqcs::QubitSet &&qubits,
dqcs::ArbCmdQueue &&cmds
) {
// Loop over the qubits that are to be allocated.
while (qubits.size()) {
// A new DQCsim upstream qubit index to allocate.
size_t dqcsim_qubit = qubits.pop().get_index();
// Look for the first free QX qubit index.
ssize_t qx_qubit = -1;
for (size_t q = 0; q < num_qubits; q++) {
if (dqcs2qx.reverse_lookup(q) < 0) {
qx_qubit = q;
break;
}
}
// If no qubits are free, see if we can still allocate more.
if (!qreg) {
qx_qubit = num_qubits;
num_qubits++;
}
if (qx_qubit >= 0) {
DQCSIM_DEBUG("Placed upstream qubit %d at QX index %d", dqcsim_qubit, qx_qubit);
dqcs2qx.map(dqcsim_qubit, qx_qubit);
} else {
throw std::runtime_error("Upstream plugin requires too many live qubits!");
}
}
}
/**
* Qubit deallocation callback.
*
* Inverse of `allocate()`.
*/
void free(
dqcs::PluginState &state,
dqcs::QubitSet &&qubits
) {
// Loop over the qubits that are to be freed.
while (qubits.size()) {
// The DQCsim upstream qubit index to free.
size_t dqcsim_qubit = qubits.pop().get_index();
// Unmap it in the bimap to do the free.
DQCSIM_DEBUG("Freed upstream qubit %d", dqcsim_qubit);
dqcs2qx.unmap_upstream(dqcsim_qubit);
}
}
/**
* Simulates all pending gates.
*
* When this is called for the first time, it also initializes the quantum
* register.
*/
void simulate_pending() {
// Initialize the qubit state if we haven't already.
if (!qreg) {
DQCSIM_INFO("Creating quantum register of %d qubits...", num_qubits);
try {
qreg = std::make_shared<qx::qu_register>(num_qubits);
} catch(std::bad_alloc& exception) {
DQCSIM_FATAL("Not enough memory for quantum state");
throw std::runtime_error("out of memory");
}
}
// Construct a circuit from the pending gates.
qx::circuit perfect_circuit = qx::circuit(
num_qubits, "circuit_" + std::to_string(circuit_counter++));
for (qx::gate *gate : pending) {
perfect_circuit.add(gate);
}
pending.clear();
// Add error using the depolarizing channel model if required.
qx::circuit *circuit = &perfect_circuit;
if (depolarizing_channel) {
size_t total_errors = 0;
circuit = qx::noisy_dep_ch(&perfect_circuit, error_probability, total_errors);
DQCSIM_INFO("Depolarizing channel model inserted %d errors", total_errors);
}
// Simulate the circuit.
circuit->execute(*qreg);
}
/**
* Gate callback.
*/
dqcs::MeasurementSet gate(
dqcs::PluginState &state,
dqcs::Gate &&gate
) {
// Convert the DQCsim gate to a QX gate and queue it up.
const GateConstructor *gate_constructor = nullptr;
dqcs::QubitSet dqcsim_qubits = dqcs::QubitSet(0);
dqcs::ArbData data = dqcs::ArbData(0);
if (!gatemap.detect(gate, &gate_constructor, &dqcsim_qubits, &data)) {
DQCSIM_DEBUG("Unsupported gate! Here's a dump: %s", gate.dump().c_str());
throw std::runtime_error("unsupported gate");
}
std::vector<size_t> qx_qubits;
while (dqcsim_qubits.size()) {
size_t dqcsim_index = dqcsim_qubits.pop().get_index();
ssize_t qx_index = dqcs2qx.forward_lookup(dqcsim_index);
if (qx_index < 0) {
throw std::runtime_error("failed to resolve DQCsim qubit to QX qubit");
}
qx_qubits.push_back(qx_index);
}
(*gate_constructor)(pending, std::move(qx_qubits), std::move(data));
// Simulate once we receive a measurement, because then we have to return a
// result.
if (gate.has_measures()) {
simulate_pending();
}
// Return the state of the measurement register for any measured qubits.
dqcs::QubitSet measured_qubits = gate.get_measures();
dqcs::MeasurementSet measurements = dqcs::MeasurementSet();
while (measured_qubits.size()) {
dqcs::QubitRef dqcsim_ref = measured_qubits.pop();
size_t dqcsim_index = dqcsim_ref.get_index();
ssize_t qx_index = dqcs2qx.forward_lookup(dqcsim_index);
if (qx_index < 0) {
throw std::runtime_error("failed to resolve DQCsim qubit to QX qubit");
}
dqcs::MeasurementValue value = qreg->get_measurement(qx_index)
? dqcs::MeasurementValue::One : dqcs::MeasurementValue::Zero;
measurements.set(dqcs::Measurement(dqcsim_ref, value));
}
return measurements;
}
/**
* Drop callback.
*
* We use this to flush out any pending operations occurring after the last
* measurement.
*/
void drop(
dqcs::PluginState &state
) {
simulate_pending();
}
/**
* Handles an ArbCmd. Used for both upstream, host, and init arbs alike.
*/
dqcs::ArbData handle_cmd(
dqcs::PluginState &state,
const dqcs::Cmd *cmd
) {
if (cmd->is_iface("qx")) {
if (cmd->is_oper("epsilon")) {
auto json = cmd->get_arb_json<nlohmann::json>();
epsilon = json["epsilon"];
DQCSIM_DEBUG("Set gate detection epsilon to %f", epsilon);
} else if (cmd->is_oper("error")) {
auto json = cmd->get_arb_json<nlohmann::json>();
std::string model = json["model"];
if (model == "none") {
depolarizing_channel = false;
DQCSIM_DEBUG("Disabled error modelling");
} else if (model == "depolarizing_channel") {
depolarizing_channel = true;
error_probability = json["error_probability"];
DQCSIM_DEBUG("Selected depolarizing channel error model with probability %f", error_probability);
} else {
throw std::runtime_error("Unknown error model requested: " + model + "!");
}
} else if (cmd->is_oper("dump_state")) {
DQCSIM_DEBUG("Simulating pending gates due to state dump request");
simulate_pending();
if (!qreg) {
throw std::runtime_error("No state register after simulate_pending(), this is weird!");
} else {
qreg->dump(false);
}
} else {
throw std::runtime_error("Unknown ArbCmd: qx." + cmd->get_oper() + "!");
}
}
return dqcs::ArbData();
}
/**
* Upstream or host ArbCmd callback.
*/
dqcs::ArbData arbcmd(
dqcs::PluginState &state,
dqcs::ArbCmd cmd
) {
return handle_cmd(state, &cmd);
}
};
int main(int argc, char *argv[]) {
QxPlugin qxPlugin;
return dqcs::Plugin::Backend("qx", "JvS", "0.0.5")
.with_initialize(&qxPlugin, &QxPlugin::initialize)
.with_allocate(&qxPlugin, &QxPlugin::allocate)
.with_free(&qxPlugin, &QxPlugin::free)
.with_gate(&qxPlugin, &QxPlugin::gate)
.with_drop(&qxPlugin, &QxPlugin::drop)
.with_host_arb(&qxPlugin, &QxPlugin::arbcmd)
.with_upstream_arb(&qxPlugin, &QxPlugin::arbcmd)
.run(argc, argv);
}
| 31.572289 | 123 | 0.664949 | QE-Lab |
13c82c88e3c0ef2adf1066587a763c57d1d1e433 | 34,351 | hxx | C++ | libs/maps/include/mrpt/otherlibs/octomap/OccupancyOcTreeBase.hxx | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 4 | 2017-08-04T15:44:04.000Z | 2021-02-02T02:00:18.000Z | libs/maps/include/mrpt/otherlibs/octomap/OccupancyOcTreeBase.hxx | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | null | null | null | libs/maps/include/mrpt/otherlibs/octomap/OccupancyOcTreeBase.hxx | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 2 | 2017-10-03T23:10:09.000Z | 2018-07-29T09:41:33.000Z | // $Id: OccupancyOcTreeBase.hxx 440 2012-11-02 10:41:10Z ahornung $
/**
* OctoMap:
* A probabilistic, flexible, and compact 3D mapping library for robotic systems.
* @author K. M. Wurm, A. Hornung, University of Freiburg, Copyright (C) 2009.
* @see http://octomap.sourceforge.net/
* License: New BSD License
*/
/*
* Copyright (c) 2009-2011, K. M. Wurm, A. Hornung, University of Freiburg
* 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 University of Freiburg nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <bitset>
namespace octomap {
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double resolution)
: OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(resolution), use_bbx_limit(false), use_change_detection(false)
{
}
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double resolution, unsigned int tree_depth, unsigned int tree_max_val)
: OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(resolution, tree_depth, tree_max_val), use_bbx_limit(false), use_change_detection(false)
{
}
template <class NODE>
OccupancyOcTreeBase<NODE>::~OccupancyOcTreeBase(){
}
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(const OccupancyOcTreeBase<NODE>& rhs) :
OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(rhs), use_bbx_limit(rhs.use_bbx_limit),
bbx_min(rhs.bbx_min), bbx_max(rhs.bbx_max),
bbx_min_key(rhs.bbx_min_key), bbx_max_key(rhs.bbx_max_key),
use_change_detection(rhs.use_change_detection), changed_keys(rhs.changed_keys)
{
this->clamping_thres_min = rhs.clamping_thres_min;
this->clamping_thres_max = rhs.clamping_thres_max;
this->prob_hit_log = rhs.prob_hit_log;
this->prob_miss_log = rhs.prob_miss_log;
this->occ_prob_thres_log = rhs.occ_prob_thres_log;
}
// performs transformation to data and sensor origin first
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const ScanNode& scan, double maxrange, bool pruning, bool lazy_eval) {
Pointcloud& cloud = *(scan.scan);
pose6d frame_origin = scan.pose;
point3d sensor_origin = frame_origin.inv().transform(scan.pose.trans());
insertScan(cloud, sensor_origin, frame_origin, maxrange, pruning, lazy_eval);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const Pointcloud& scan, const octomap::point3d& sensor_origin,
double maxrange, bool pruning, bool lazy_eval) {
KeySet free_cells, occupied_cells;
computeUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange);
// insert data into tree -----------------------
for (KeySet::iterator it = free_cells.begin(); it != free_cells.end(); ++it) {
updateNode(*it, false, lazy_eval);
}
for (KeySet::iterator it = occupied_cells.begin(); it != occupied_cells.end(); ++it) {
updateNode(*it, true, lazy_eval);
}
// TODO: does pruning make sense if we used "lazy_eval"?
if (pruning) this->prune();
}
template <class NODE>
template <class SCAN>
void OccupancyOcTreeBase<NODE>::insertScan_templ(const SCAN& scan, const octomap::point3d& sensor_origin,
double maxrange, bool pruning, bool lazy_eval) {
KeySet free_cells, occupied_cells;
computeUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange);
// insert data into tree -----------------------
for (KeySet::iterator it = free_cells.begin(); it != free_cells.end(); ++it) {
updateNode(*it, false, lazy_eval);
}
for (KeySet::iterator it = occupied_cells.begin(); it != occupied_cells.end(); ++it) {
updateNode(*it, true, lazy_eval);
}
// TODO: does pruning make sense if we used "lazy_eval"?
if (pruning) this->prune();
}
// performs transformation to data and sensor origin first
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const Pointcloud& pc, const point3d& sensor_origin, const pose6d& frame_origin,
double maxrange, bool pruning, bool lazy_eval) {
Pointcloud transformed_scan (pc);
transformed_scan.transform(frame_origin);
point3d transformed_sensor_origin = frame_origin.transform(sensor_origin);
insertScan(transformed_scan, transformed_sensor_origin, maxrange, pruning, lazy_eval);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScanNaive(const Pointcloud& pc, const point3d& origin, double maxrange, bool pruning, bool lazy_eval) {
if (pc.size() < 1)
return;
// integrate each single beam
octomap::point3d p;
for (octomap::Pointcloud::const_iterator point_it = pc.begin();
point_it != pc.end(); ++point_it) {
this->insertRay(origin, *point_it, maxrange, lazy_eval);
}
if (pruning)
this->prune();
}
template <class NODE>
inline void OccupancyOcTreeBase<NODE>::computeUpdate_onePoint(const point3d& p, const octomap::point3d& origin,
KeySet& free_cells, KeySet& occupied_cells, double maxrange)
{
if (!use_bbx_limit) {
// -------------- no BBX specified ---------------
if ((maxrange < 0.0) || ((p - origin).norm() <= maxrange) ) { // is not maxrange meas.
// free cells
if (this->computeRayKeys(origin, p, this->keyray)){
free_cells.insert(this->keyray.begin(), this->keyray.end());
}
// occupied endpoint
OcTreeKey key;
if (this->coordToKeyChecked(p, key))
occupied_cells.insert(key);
} // end if NOT maxrange
else { // user set a maxrange and this is reached
point3d direction = (p - origin).normalized ();
point3d new_end = origin + direction * (float) maxrange;
if (this->computeRayKeys(origin, new_end, this->keyray)){
free_cells.insert(this->keyray.begin(), this->keyray.end());
}
} // end if maxrange
}
// --- update limited by user specified BBX -----
else {
// endpoint in bbx and not maxrange?
if ( inBBX(p) && ((maxrange < 0.0) || ((p - origin).norm () <= maxrange) ) ) {
// occupied endpoint
OcTreeKey key;
if (this->coordToKeyChecked(p, key))
occupied_cells.insert(key);
// update freespace, break as soon as bbx limit is reached
if (this->computeRayKeys(origin, p, this->keyray)){
for(KeyRay::reverse_iterator rit=this->keyray.rbegin(); rit != this->keyray.rend(); ++rit) {
if (inBBX(*rit)) {
free_cells.insert(*rit);
}
else break;
}
} // end if compute ray
} // end if in BBX and not maxrange
} // end bbx case
}
template <class NODE>
template <class POINTCLOUD>
void OccupancyOcTreeBase<NODE>::computeUpdate_templ( const POINTCLOUD& scan, const octomap::point3d& origin, KeySet& free_cells, KeySet& occupied_cells, double maxrange)
{
const size_t N = scan.size();
const std::vector<float> &xs = scan.getPointsBufferRef_x();
const std::vector<float> &ys = scan.getPointsBufferRef_y();
const std::vector<float> &zs = scan.getPointsBufferRef_z();
for (size_t i=0;i<N;i++)
{
const point3d p(xs[i],ys[i],zs[i]);
computeUpdate_onePoint(p,origin,free_cells,occupied_cells,maxrange);
}
// prefer occupied cells over free ones (and make sets disjunct)
for(KeySet::iterator it = free_cells.begin(), end=free_cells.end(); it!= end; )
{
if (occupied_cells.find(*it) != occupied_cells.end())
it = free_cells.erase(it);
else ++it;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::computeUpdate(const Pointcloud& scan, const octomap::point3d& origin,
KeySet& free_cells, KeySet& occupied_cells,
double maxrange)
{
//#pragma omp parallel private (local_key_ray, point_it)
for (Pointcloud::const_iterator point_it = scan.begin(); point_it != scan.end(); ++point_it) {
const point3d& p = *point_it;
computeUpdate_onePoint(p,origin,free_cells,occupied_cells,maxrange);
}
// prefer occupied cells over free ones (and make sets disjunct)
for(KeySet::iterator it = free_cells.begin(), end=free_cells.end(); it!= end; ){
if (occupied_cells.find(*it) != occupied_cells.end()){
it = free_cells.erase(it);
} else {
++it;
}
}
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, float log_odds_update, bool lazy_eval) {
return updateNodeRecurs(this->root, false, key, 0, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, float log_odds_update, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(value, key))
return NULL;
return updateNode(key, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, float log_odds_update, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(x, y, z, key))
return NULL;
return updateNode(key, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, bool occupied, bool lazy_eval) {
NODE* leaf = this->search(key);
// no change: node already at threshold
if (leaf && (this->isNodeAtThreshold(leaf)) && (this->isNodeOccupied(leaf) == occupied)) {
return leaf;
}
if (occupied) return updateNodeRecurs(this->root, false, key, 0, this->prob_hit_log, lazy_eval);
else return updateNodeRecurs(this->root, false, key, 0, this->prob_miss_log, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, bool occupied, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(value, key))
return NULL;
return updateNode(key, occupied, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, bool occupied, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(x, y, z, key))
return NULL;
return updateNode(key, occupied, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNodeRecurs(NODE* node, bool node_just_created, const OcTreeKey& key,
unsigned int depth, const float& log_odds_update, bool lazy_eval) {
unsigned int pos = computeChildIdx(key, this->tree_depth-1-depth);
bool created_node = false;
// follow down to last level
if (depth < this->tree_depth) {
if (!node->childExists(pos)) {
// child does not exist, but maybe it's a pruned node?
if ((!node->hasChildren()) && !node_just_created && (node != this->root)) {
// current node does not have children AND it is not a new node
// AND its not the root node
// -> expand pruned node
node->expandNode();
this->tree_size+=8;
this->size_changed = true;
}
else {
// not a pruned node, create requested child
node->createChild(pos);
this->tree_size++;
this->size_changed = true;
created_node = true;
}
}
if (lazy_eval)
return updateNodeRecurs(node->getChild(pos), created_node, key, depth+1, log_odds_update, lazy_eval);
else {
NODE* retval = updateNodeRecurs(node->getChild(pos), created_node, key, depth+1, log_odds_update, lazy_eval);
// set own probability according to prob of children
node->updateOccupancyChildren();
return retval;
}
}
// at last level, update node, end of recursion
else {
if (use_change_detection) {
bool occBefore = this->isNodeOccupied(node);
updateNodeLogOdds(node, log_odds_update);
if (node_just_created){ // new node
changed_keys.insert(std::pair<OcTreeKey,bool>(key, true));
} else if (occBefore != this->isNodeOccupied(node)) { // occupancy changed, track it
KeyBoolMap::iterator it = changed_keys.find(key);
if (it == changed_keys.end())
changed_keys.insert(std::pair<OcTreeKey,bool>(key, false));
else if (it->second == false)
changed_keys.erase(it);
}
}
else {
updateNodeLogOdds(node, log_odds_update);
}
return node;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::calcNumThresholdedNodes(unsigned int& num_thresholded,
unsigned int& num_other) const {
num_thresholded = 0;
num_other = 0;
// TODO: The recursive call could be completely replaced with the new iterators
calcNumThresholdedNodesRecurs(this->root, num_thresholded, num_other);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::calcNumThresholdedNodesRecurs (NODE* node,
unsigned int& num_thresholded,
unsigned int& num_other) const {
assert(node != NULL);
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
NODE* child_node = node->getChild(i);
if (this->isNodeAtThreshold(child_node))
num_thresholded++;
else
num_other++;
calcNumThresholdedNodesRecurs(child_node, num_thresholded, num_other);
} // end if child
} // end for children
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateInnerOccupancy(){
this->updateInnerOccupancyRecurs(this->root, 0);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateInnerOccupancyRecurs(NODE* node, unsigned int depth){
// only recurse and update for inner nodes:
if (node->hasChildren()){
// return early for last level:
if (depth < this->tree_depth){
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
updateInnerOccupancyRecurs(node->getChild(i), depth+1);
}
}
}
node->updateOccupancyChildren();
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::toMaxLikelihood() {
// convert bottom up
for (unsigned int depth=this->tree_depth; depth>0; depth--) {
toMaxLikelihoodRecurs(this->root, 0, depth);
}
// convert root
nodeToMaxLikelihood(this->root);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::toMaxLikelihoodRecurs(NODE* node, unsigned int depth,
unsigned int max_depth) {
if (depth < max_depth) {
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
toMaxLikelihoodRecurs(node->getChild(i), depth+1, max_depth);
}
}
}
else { // max level reached
nodeToMaxLikelihood(node);
}
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::castRay(const point3d& origin, const point3d& directionP, point3d& end,
bool ignoreUnknown, double maxRange) const {
/// ---------- see OcTreeBase::computeRayKeys -----------
// Initialization phase -------------------------------------------------------
OcTreeKey current_key;
if ( !OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::coordToKeyChecked(origin, current_key) ) {
OCTOMAP_WARNING_STR("Coordinates out of bounds during ray casting");
return false;
}
NODE* startingNode = this->search(current_key);
if (startingNode){
if (this->isNodeOccupied(startingNode)){
// Occupied node found at origin
// (need to convert from key, since origin does not need to be a voxel center)
end = this->keyToCoord(current_key);
return true;
}
} else if(!ignoreUnknown){
OCTOMAP_ERROR_STR("Origin node at " << origin << " for raycasting not found, does the node exist?");
end = this->keyToCoord(current_key);
return false;
}
point3d direction = directionP.normalized();
bool max_range_set = (maxRange > 0.0);
int step[3];
double tMax[3];
double tDelta[3];
for(unsigned int i=0; i < 3; ++i) {
// compute step direction
if (direction(i) > 0.0) step[i] = 1;
else if (direction(i) < 0.0) step[i] = -1;
else step[i] = 0;
// compute tMax, tDelta
if (step[i] != 0) {
// corner point of voxel (in direction of ray)
double voxelBorder = this->keyToCoord(current_key[i]);
voxelBorder += double(step[i] * this->resolution * 0.5);
tMax[i] = ( voxelBorder - origin(i) ) / direction(i);
tDelta[i] = this->resolution / fabs( direction(i) );
}
else {
tMax[i] = std::numeric_limits<double>::max();
tDelta[i] = std::numeric_limits<double>::max();
}
}
if (step[0] == 0 && step[1] == 0 && step[2] == 0){
OCTOMAP_ERROR("Raycasting in direction (0,0,0) is not possible!");
return false;
}
// for speedup:
double maxrange_sq = maxRange *maxRange;
// Incremental phase ---------------------------------------------------------
bool done = false;
while (!done) {
unsigned int dim;
// find minimum tMax:
if (tMax[0] < tMax[1]){
if (tMax[0] < tMax[2]) dim = 0;
else dim = 2;
}
else {
if (tMax[1] < tMax[2]) dim = 1;
else dim = 2;
}
// check for overflow:
if ((step[dim] < 0 && current_key[dim] == 0)
|| (step[dim] > 0 && current_key[dim] == 2* this->tree_max_val-1))
{
OCTOMAP_WARNING("Coordinate hit bounds in dim %d, aborting raycast\n", dim);
// return border point nevertheless:
end = this->keyToCoord(current_key);
return false;
}
// advance in direction "dim"
current_key[dim] += step[dim];
tMax[dim] += tDelta[dim];
// generate world coords from key
end = this->keyToCoord(current_key);
// check for maxrange:
if (max_range_set){
double dist_from_origin_sq(0.0);
for (unsigned int j = 0; j < 3; j++) {
dist_from_origin_sq += ((end(j) - origin(j)) * (end(j) - origin(j)));
}
if (dist_from_origin_sq > maxrange_sq)
return false;
}
NODE* currentNode = this->search(current_key);
if (currentNode){
if (this->isNodeOccupied(currentNode)) {
done = true;
break;
}
// otherwise: node is free and valid, raycasting continues
} else if (!ignoreUnknown){ // no node found, this usually means we are in "unknown" areas
OCTOMAP_WARNING_STR("Search failed in OcTree::castRay() => an unknown area was hit in the map: " << end);
return false;
}
} // end while
return true;
}
template <class NODE> inline bool
OccupancyOcTreeBase<NODE>::integrateMissOnRay(const point3d& origin, const point3d& end, bool lazy_eval) {
if (!this->computeRayKeys(origin, end, this->keyray)) {
return false;
}
for(KeyRay::iterator it=this->keyray.begin(); it != this->keyray.end(); ++it) {
updateNode(*it, false, lazy_eval); // insert freespace measurement
}
return true;
}
template <class NODE> bool
OccupancyOcTreeBase<NODE>::insertRay(const point3d& origin, const point3d& end, double maxrange, bool lazy_eval)
{
// cut ray at maxrange
if ((maxrange > 0) && ((end - origin).norm () > maxrange))
{
point3d direction = (end - origin).normalized ();
point3d new_end = origin + direction * (float) maxrange;
return integrateMissOnRay(origin, new_end,lazy_eval);
}
// insert complete ray
else
{
if (!integrateMissOnRay(origin, end,lazy_eval))
return false;
updateNode(end, true, lazy_eval); // insert hit cell
return true;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(point3d_list& node_centers, unsigned int max_depth) const {
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it))
node_centers.push_back(it.getCoordinate());
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(std::list<OcTreeVolume>& occupied_nodes, unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it))
occupied_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(std::list<OcTreeVolume>& binary_nodes,
std::list<OcTreeVolume>& delta_nodes,
unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it)){
if (it->getLogOdds() >= this->clamping_thres_max)
binary_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
else
delta_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getFreespace(std::list<OcTreeVolume>& free_nodes, unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(!this->isNodeOccupied(*it))
free_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getFreespace(std::list<OcTreeVolume>& binary_nodes,
std::list<OcTreeVolume>& delta_nodes,
unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(!this->isNodeOccupied(*it)){
if (it->getLogOdds() <= this->clamping_thres_min)
binary_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
else
delta_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::setBBXMin (point3d& min) {
bbx_min = min;
if (!this->genKey(bbx_min, bbx_min_key)) {
OCTOMAP_ERROR("ERROR while generating bbx min key.\n");
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::setBBXMax (point3d& max) {
bbx_max = max;
if (!this->genKey(bbx_max, bbx_max_key)) {
OCTOMAP_ERROR("ERROR while generating bbx max key.\n");
}
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::inBBX(const point3d& p) const {
return ((p.x() >= bbx_min.x()) && (p.y() >= bbx_min.y()) && (p.z() >= bbx_min.z()) &&
(p.x() <= bbx_max.x()) && (p.y() <= bbx_max.y()) && (p.z() <= bbx_max.z()) );
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::inBBX(const OcTreeKey& key) const {
return ((key[0] >= bbx_min_key[0]) && (key[1] >= bbx_min_key[1]) && (key[2] >= bbx_min_key[2]) &&
(key[0] <= bbx_max_key[0]) && (key[1] <= bbx_max_key[1]) && (key[2] <= bbx_max_key[2]) );
}
template <class NODE>
point3d OccupancyOcTreeBase<NODE>::getBBXBounds () const {
octomap::point3d obj_bounds = (bbx_max - bbx_min);
obj_bounds /= 2.;
return obj_bounds;
}
template <class NODE>
point3d OccupancyOcTreeBase<NODE>::getBBXCenter () const {
octomap::point3d obj_bounds = (bbx_max - bbx_min);
obj_bounds /= 2.;
return bbx_min + obj_bounds;
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupiedLeafsBBX(point3d_list& node_centers, point3d min, point3d max) const {
OcTreeKey root_key, min_key, max_key;
root_key[0] = root_key[1] = root_key[2] = this->tree_max_val;
if (!this->genKey(min, min_key)) return;
if (!this->genKey(max, max_key)) return;
getOccupiedLeafsBBXRecurs(node_centers, this->tree_depth, this->root, 0, root_key, min_key, max_key);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupiedLeafsBBXRecurs( point3d_list& node_centers, unsigned int max_depth,
NODE* node, unsigned int depth, const OcTreeKey& parent_key,
const OcTreeKey& min, const OcTreeKey& max) const {
if (depth == max_depth) { // max level reached
if (this->isNodeOccupied(node)) {
node_centers.push_back(this->keyToCoords(parent_key, depth));
}
}
if (!node->hasChildren()) return;
unsigned short int center_offset_key = this->tree_max_val >> (depth + 1);
OcTreeKey child_key;
for (unsigned int i=0; i<8; ++i) {
if (node->childExists(i)) {
computeChildKey(i, center_offset_key, parent_key, child_key);
// overlap of query bbx and child bbx?
if (!(
( min[0] > (child_key[0] + center_offset_key)) ||
( max[0] < (child_key[0] - center_offset_key)) ||
( min[1] > (child_key[1] + center_offset_key)) ||
( max[1] < (child_key[1] - center_offset_key)) ||
( min[2] > (child_key[2] + center_offset_key)) ||
( max[2] < (child_key[2] - center_offset_key))
)) {
getOccupiedLeafsBBXRecurs(node_centers, max_depth, node->getChild(i), depth+1, child_key, min, max);
}
}
}
}
// -- I/O -----------------------------------------
template <class NODE>
std::istream& OccupancyOcTreeBase<NODE>::readBinaryData(std::istream &s){
this->readBinaryNode(s, this->root);
this->size_changed = true;
this->tree_size = OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::calcNumNodes(); // compute number of nodes
return s;
}
template <class NODE>
std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryData(std::ostream &s) const{
OCTOMAP_DEBUG("Writing %u nodes to output stream...", static_cast<unsigned int>(this->size()));
this->writeBinaryNode(s, this->root);
return s;
}
template <class NODE>
std::istream& OccupancyOcTreeBase<NODE>::readBinaryNode(std::istream &s, NODE* node) const {
char child1to4_char;
char child5to8_char;
s.read((char*)&child1to4_char, sizeof(char));
s.read((char*)&child5to8_char, sizeof(char));
std::bitset<8> child1to4 ((unsigned long long) child1to4_char);
std::bitset<8> child5to8 ((unsigned long long) child5to8_char);
// std::cout << "read: "
// << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " "
// << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl;
// inner nodes default to occupied
node->setLogOdds(this->clamping_thres_max);
for (unsigned int i=0; i<4; i++) {
if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 0)) {
// child is free leaf
node->createChild(i);
node->getChild(i)->setLogOdds(this->clamping_thres_min);
}
else if ((child1to4[i*2] == 0) && (child1to4[i*2+1] == 1)) {
// child is occupied leaf
node->createChild(i);
node->getChild(i)->setLogOdds(this->clamping_thres_max);
}
else if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 1)) {
// child has children
node->createChild(i);
node->getChild(i)->setLogOdds(-200.); // child is unkown, we leave it uninitialized
}
}
for (unsigned int i=0; i<4; i++) {
if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 0)) {
// child is free leaf
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(this->clamping_thres_min);
}
else if ((child5to8[i*2] == 0) && (child5to8[i*2+1] == 1)) {
// child is occupied leaf
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(this->clamping_thres_max);
}
else if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 1)) {
// child has children
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(-200.); // set occupancy when all children have been read
}
// child is unkown, we leave it uninitialized
}
// read children's children and set the label
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
NODE* child = node->getChild(i);
if (fabs(child->getLogOdds() + 200.)<1e-3) {
readBinaryNode(s, child);
child->setLogOdds(child->getMaxChildLogOdds());
}
} // end if child exists
} // end for children
return s;
}
template <class NODE>
std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryNode(std::ostream &s, const NODE* node) const{
// 2 bits for each children, 8 children per node -> 16 bits
std::bitset<8> child1to4;
std::bitset<8> child5to8;
// 10 : child is free node
// 01 : child is occupied node
// 00 : child is unkown node
// 11 : child has children
// speedup: only set bits to 1, rest is init with 0 anyway,
// can be one logic expression per bit
for (unsigned int i=0; i<4; i++) {
if (node->childExists(i)) {
const NODE* child = node->getChild(i);
if (child->hasChildren()) { child1to4[i*2] = 1; child1to4[i*2+1] = 1; }
else if (this->isNodeOccupied(child)) { child1to4[i*2] = 0; child1to4[i*2+1] = 1; }
else { child1to4[i*2] = 1; child1to4[i*2+1] = 0; }
}
else {
child1to4[i*2] = 0; child1to4[i*2+1] = 0;
}
}
for (unsigned int i=0; i<4; i++) {
if (node->childExists(i+4)) {
const NODE* child = node->getChild(i+4);
if (child->hasChildren()) { child5to8[i*2] = 1; child5to8[i*2+1] = 1; }
else if (this->isNodeOccupied(child)) { child5to8[i*2] = 0; child5to8[i*2+1] = 1; }
else { child5to8[i*2] = 1; child5to8[i*2+1] = 0; }
}
else {
child5to8[i*2] = 0; child5to8[i*2+1] = 0;
}
}
// std::cout << "wrote: "
// << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " "
// << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl;
char child1to4_char = (char) child1to4.to_ulong();
char child5to8_char = (char) child5to8.to_ulong();
s.write((char*)&child1to4_char, sizeof(char));
s.write((char*)&child5to8_char, sizeof(char));
// write children's children
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
const NODE* child = node->getChild(i);
if (child->hasChildren()) {
writeBinaryNode(s, child);
}
}
}
return s;
}
//-- Occupancy queries on nodes:
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateNodeLogOdds(NODE* occupancyNode, const float& update) const {
occupancyNode->addValue(update);
if (occupancyNode->getLogOdds() < this->clamping_thres_min) {
occupancyNode->setLogOdds(this->clamping_thres_min);
return;
}
if (occupancyNode->getLogOdds() > this->clamping_thres_max) {
occupancyNode->setLogOdds(this->clamping_thres_max);
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::integrateHit(NODE* occupancyNode) const {
updateNodeLogOdds(occupancyNode, this->prob_hit_log);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::integrateMiss(NODE* occupancyNode) const {
updateNodeLogOdds(occupancyNode, this->prob_miss_log);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE* occupancyNode) const{
if (this->isNodeOccupied(occupancyNode))
occupancyNode->setLogOdds(this->clamping_thres_max);
else
occupancyNode->setLogOdds(this->clamping_thres_min);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE& occupancyNode) const{
if (this->isNodeOccupied(occupancyNode))
occupancyNode.setLogOdds(this->clamping_thres_max);
else
occupancyNode.setLogOdds(this->clamping_thres_min);
}
} // namespace
| 35.819604 | 170 | 0.623446 | feroze |
13c8c3fc0493f79463cd40a996423a2bb40dd1d7 | 7,943 | cpp | C++ | bcos-crypto/demo/perf_demo.cpp | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | 4 | 2022-01-12T11:46:11.000Z | 2022-01-19T04:51:00.000Z | bcos-crypto/demo/perf_demo.cpp | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | 22 | 2021-03-12T11:10:56.000Z | 2022-03-31T17:50:21.000Z | bcos-crypto/demo/perf_demo.cpp | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | 6 | 2021-02-22T04:13:24.000Z | 2022-01-12T11:46:15.000Z | /**
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @brief perf for bcos-crypto
* @file perf_demo.cpp
* @date 2021.04.07
* @author yujiechen
*/
#include "../encrypt/AESCrypto.h"
#include "../encrypt/SM4Crypto.h"
#include "../hash/Keccak256.h"
#include "../hash/SM3.h"
#include "../hash/Sha3.h"
#include "../signature/ed25519/Ed25519Crypto.h"
#include "../signature/secp256k1/Secp256k1Crypto.h"
#include "../signature/sm2/SM2Crypto.h"
#include <bcos-framework/libutilities/Common.h>
using namespace bcos;
using namespace bcos::crypto;
const std::string HASH_CMD = "hash";
const std::string SIGN_CMD = "sign";
const std::string ENCRYPT_CMD = "enc";
void Usage(std::string const& _appName)
{
std::cout << _appName << " [" << HASH_CMD << "/" << SIGN_CMD << "/" << ENCRYPT_CMD << "] count"
<< std::endl;
}
double getTPS(int64_t _endT, int64_t _startT, size_t _count)
{
return (1000.0 * (double)_count) / (double)(_endT - _startT);
}
void hashPerf(
Hash::Ptr _hash, std::string const& _hashName, std::string const& _inputData, size_t _count)
{
std::cout << std::endl;
std::cout << "----------- " << _hashName << " perf start -----------" << std::endl;
auto startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
_hash->hash(bytesConstRef((byte const*)_inputData.c_str(), _inputData.size()));
}
std::cout << "input data size: " << (double)_inputData.size() / 1000.0
<< "KB, loops: " << _count << ", timeCost: " << utcTime() - startT << std::endl;
std::cout << "TPS of " << _hashName << ": "
<< getTPS(utcTime(), startT, _count) * (double)_inputData.size() / 1000.0 << " KB/s"
<< std::endl;
std::cout << "----------- " << _hashName << " perf end -----------" << std::endl;
std::cout << std::endl;
}
void hashPerf(size_t _count)
{
std::string inputData = "abcdwer234q4@#2424wdf";
std::string deltaData = inputData;
for (int i = 0; i < 50; i++)
{
inputData += deltaData;
}
// sha3 perf
Hash::Ptr hashImpl = std::make_shared<class Sha3>();
hashPerf(hashImpl, "SHA3", inputData, _count);
// keccak256 perf
hashImpl = std::make_shared<Keccak256>();
hashPerf(hashImpl, "Keccak256", inputData, _count);
// sm3 perf
hashImpl = std::make_shared<SM3>();
hashPerf(hashImpl, "SM3", inputData, _count);
}
void signaturePerf(SignatureCrypto::Ptr _signatureImpl, HashType const& _msgHash,
std::string const& _signatureName, size_t _count)
{
std::cout << std::endl;
std::cout << "----------- " << _signatureName << " perf test start -----------" << std::endl;
auto keyPair = _signatureImpl->generateKeyPair();
// sign
std::shared_ptr<bytes> signedData;
auto startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
signedData = _signatureImpl->sign(keyPair, _msgHash, false);
}
std::cout << "TPS of " << _signatureName << " sign:" << getTPS(utcTime(), startT, _count)
<< std::endl;
// verify
startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
assert(_signatureImpl->verify(keyPair->publicKey(), _msgHash, ref(*signedData)));
}
std::cout << "TPS of " << _signatureName << " verify:" << getTPS(utcTime(), startT, _count)
<< std::endl;
// recover
signedData = _signatureImpl->sign(keyPair, _msgHash, true);
startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
_signatureImpl->recover(_msgHash, ref(*signedData));
}
std::cout << "TPS of " << _signatureName << " recover:" << getTPS(utcTime(), startT, _count)
<< std::endl;
std::cout << "----------- " << _signatureName << " perf test end -----------" << std::endl;
std::cout << std::endl;
}
void signaturePerf(size_t _count)
{
std::string inputData = "signature perf test";
auto msgHash = keccak256Hash(bytesConstRef((byte const*)inputData.c_str(), inputData.size()));
// secp256k1 perf
SignatureCrypto::Ptr signatureImpl = std::make_shared<Secp256k1Crypto>();
signaturePerf(signatureImpl, msgHash, "secp256k1", _count);
// sm2 perf
signatureImpl = std::make_shared<SM2Crypto>();
signaturePerf(signatureImpl, msgHash, "SM2", _count);
// ed25519 perf
signatureImpl = std::make_shared<Ed25519Crypto>();
signaturePerf(signatureImpl, msgHash, "Ed25519", _count);
}
void encryptPerf(SymmetricEncryption::Ptr _encryptor, std::string const& _inputData,
const std::string& _encryptorName, size_t _count)
{
std::cout << std::endl;
std::cout << "----------- " << _encryptorName << " perf test start -----------" << std::endl;
std::string key = "abcdefgwerelkewrwerw";
// encrypt
bytesPointer encryptedData;
auto startT = utcTime();
for (size_t i = 0; i < _count; i++)
{
encryptedData = _encryptor->symmetricEncrypt((const unsigned char*)_inputData.c_str(),
_inputData.size(), (const unsigned char*)key.c_str(), key.size());
}
std::cout << "PlainData size:" << (double)_inputData.size() / 1000.0 << " KB, loops: " << _count
<< ", timeCost: " << utcTime() - startT << " ms" << std::endl;
std::cout << "TPS of " << _encryptorName << " encrypt:"
<< (getTPS(utcTime(), startT, _count) * (double)(_inputData.size())) / 1000.0
<< "KB/s" << std::endl;
std::cout << std::endl;
// decrypt
startT = utcTime();
bytesPointer decryptedData;
for (size_t i = 0; i < _count; i++)
{
decryptedData = _encryptor->symmetricDecrypt((const unsigned char*)encryptedData->data(),
encryptedData->size(), (const unsigned char*)key.c_str(), key.size());
}
std::cout << "CiperData size:" << (double)encryptedData->size() / 1000.0
<< " KB, loops: " << _count << ", timeCost:" << utcTime() - startT << " ms"
<< std::endl;
std::cout << "TPS of " << _encryptorName << " decrypt:"
<< (getTPS(utcTime(), startT, _count) * (double)_inputData.size()) / 1000.0 << "KB/s"
<< std::endl;
bytes plainBytes(_inputData.begin(), _inputData.end());
assert(plainBytes == *decryptedData);
std::cout << "----------- " << _encryptorName << " perf test end -----------" << std::endl;
std::cout << std::endl;
}
void encryptPerf(size_t _count)
{
std::string inputData = "w3rwerk2-304swlerkjewlrjoiur4kslfjsd,fmnsdlfjlwerlwerjw;erwe;rewrew";
std::string deltaData = inputData;
for (int i = 0; i < 100; i++)
{
inputData += deltaData;
}
// AES
SymmetricEncryption::Ptr encryptor = std::make_shared<AESCrypto>();
encryptPerf(encryptor, inputData, "AES", _count);
// SM4
encryptor = std::make_shared<SM4Crypto>();
encryptPerf(encryptor, inputData, "SM4", _count);
}
int main(int argc, char* argv[])
{
if (argc < 3)
{
Usage(argv[0]);
return -1;
}
auto cmd = argv[1];
size_t count = atoi(argv[2]);
if (HASH_CMD == cmd)
{
hashPerf(count);
}
else if (SIGN_CMD == cmd)
{
signaturePerf(count);
}
else if (ENCRYPT_CMD == cmd)
{
encryptPerf(count);
}
else
{
std::cout << "Invalid subcommand \"" << cmd << "\"" << std::endl;
Usage(argv[0]);
}
return 0;
}
| 34.837719 | 100 | 0.595871 | xueying4402 |
13ca083a152c87220128c173deb0bebd0b70d116 | 683 | cpp | C++ | LightOJ/1202 - Bishops - 1003257.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 5 | 2020-10-03T17:15:26.000Z | 2022-03-29T21:39:22.000Z | LightOJ/1202 - Bishops - 1003257.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | null | null | null | LightOJ/1202 - Bishops - 1003257.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 1 | 2021-03-01T12:56:50.000Z | 2021-03-01T12:56:50.000Z | #include <bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
for(int i = 1; i <= T; i++) {
int r1, r2, c1, c2;
cin >> r1 >> c1 >> r2 >> c2;
if((r1 & 1) == (r2 & 1)) {
if((c1 & 1) != (c2 & 1)) {
printf("Case %d: impossible\n", i);
continue;
}
}
else {
if((c1 & 1) == (c2 & 1)) {
printf("Case %d: impossible\n", i);
continue;
}
}
printf("Case %d: ", i);
if(abs(r2 - r1) == abs(c2 - c1))
printf("1\n");
else
printf("2\n");
}
return 0;
}
| 22.032258 | 51 | 0.330893 | Shefin-CSE16 |
13cb4600cd0847afe1d5de708f5be41f1f87540d | 8,583 | cc | C++ | cc/subtle/aes_gcm_hkdf_streaming_test.cc | rohansingh/tink | c2338bef4663870d3855fb0236ab0092d976434d | [
"Apache-2.0"
] | 1 | 2022-03-15T03:21:44.000Z | 2022-03-15T03:21:44.000Z | cc/subtle/aes_gcm_hkdf_streaming_test.cc | frankfanslc/tink | fee9b771017baeaa65f13f82c8a10b3a1119d44d | [
"Apache-2.0"
] | null | null | null | cc/subtle/aes_gcm_hkdf_streaming_test.cc | frankfanslc/tink | fee9b771017baeaa65f13f82c8a10b3a1119d44d | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
#include "tink/subtle/aes_gcm_hkdf_streaming.h"
#include <sstream>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "tink/config/tink_fips.h"
#include "tink/output_stream.h"
#include "tink/subtle/common_enums.h"
#include "tink/subtle/random.h"
#include "tink/subtle/streaming_aead_test_util.h"
#include "tink/subtle/test_util.h"
#include "tink/util/istream_input_stream.h"
#include "tink/util/ostream_output_stream.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_matchers.h"
namespace crypto {
namespace tink {
namespace subtle {
namespace {
using ::crypto::tink::test::IsOk;
using ::crypto::tink::test::StatusIs;
TEST(AesGcmHkdfStreamingTest, testBasic) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) {
for (int ikm_size : {16, 32}) {
for (int derived_key_size = 16;
derived_key_size <= ikm_size;
derived_key_size += 16) {
for (int ct_segment_size : {80, 128, 200}) {
for (int ciphertext_offset : {0, 10, 16}) {
SCOPED_TRACE(absl::StrCat(
"hkdf_hash = ", EnumToString(hkdf_hash),
", ikm_size = ", ikm_size,
", derived_key_size = ", derived_key_size,
", ciphertext_segment_size = ", ct_segment_size,
", ciphertext_offset = ", ciphertext_offset));
// Create AesGcmHkdfStreaming.
AesGcmHkdfStreaming::Params params;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.hkdf_hash = hkdf_hash;
params.derived_key_size = derived_key_size;
params.ciphertext_segment_size = ct_segment_size;
params.ciphertext_offset = ciphertext_offset;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_TRUE(result.ok()) << result.status();
auto streaming_aead = std::move(result.ValueOrDie());
// Try to get an encrypting stream to a "null" ct_destination.
std::string associated_data = "some associated data";
auto failed_result = streaming_aead->NewEncryptingStream(
nullptr, associated_data);
EXPECT_FALSE(failed_result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument,
failed_result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "non-null",
std::string(failed_result.status().message()));
for (int pt_size : {0, 16, 100, 1000, 10000}) {
SCOPED_TRACE(absl::StrCat(" pt_size = ", pt_size));
std::string pt = Random::GetRandomBytes(pt_size);
EXPECT_THAT(
EncryptThenDecrypt(streaming_aead.get(), streaming_aead.get(),
pt, associated_data, ciphertext_offset),
IsOk());
}
}
}
}
}
}
}
TEST(AesGcmHkdfStreamingTest, testIkmSmallerThanDerivedKey) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 16;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 17;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ikm too small",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testIkmSize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
for (int ikm_size : {5, 10, 15}) {
AesGcmHkdfStreaming::Params params;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 17;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 0;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ikm too small",
std::string(result.status().message()));
}
}
TEST(AesGcmHkdfStreamingTest, testWrongHkdfHash) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 16;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 16;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA384;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "unsupported hkdf_hash",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongDerivedKeySize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 20;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 20;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be 16 or 32",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongCiphertextOffset) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = -5;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be non-negative",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongCiphertextSegmentSize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 64;
params.ciphertext_offset = 40;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ciphertext_segment_size too small",
std::string(result.status().message()));
}
// FIPS only mode tests
TEST(AesGcmHkdfStreamingTest, TestFipsOnly) {
if (!IsFipsModeEnabled()) {
GTEST_SKIP() << "Only supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 64;
params.ciphertext_offset = 40;
params.hkdf_hash = SHA256;
EXPECT_THAT(AesGcmHkdfStreaming::New(std::move(params)).status(),
StatusIs(absl::StatusCode::kInternal));
}
} // namespace
} // namespace subtle
} // namespace tink
} // namespace crypto
| 36.368644 | 80 | 0.670628 | rohansingh |
13cfc5cddd87c4fcd50b78d139ef3aca8462d039 | 1,187 | cpp | C++ | src/Engine/Geometry/Quad.cpp | fromasmtodisasm/BlackBox | 36b4fa56e62a81d9483e76f1272b1203981b97fe | [
"MIT"
] | 1 | 2019-12-10T00:37:05.000Z | 2019-12-10T00:37:05.000Z | src/Engine/Geometry/Quad.cpp | fromasmtodisasm/BlackBox | 36b4fa56e62a81d9483e76f1272b1203981b97fe | [
"MIT"
] | 3 | 2020-02-17T21:12:09.000Z | 2022-01-19T10:28:02.000Z | src/Engine/Geometry/Quad.cpp | fromasmtodisasm/BlackBox | 36b4fa56e62a81d9483e76f1272b1203981b97fe | [
"MIT"
] | 3 | 2019-03-14T16:28:47.000Z | 2020-05-17T20:42:55.000Z | #include <BlackBox/Renderer/Quad.hpp>
#include <BlackBox/Renderer/IGeometry.hpp>
#include <BlackBox/Renderer/OpenGL/Debug.hpp>
Quad::Quad()
{
float verts[] = {
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
glGenVertexArrays(1, &id);
glBindVertexArray(id);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), &verts, GL_STATIC_DRAW);
// 3. Устанавливаем указатели на вершинные атрибуты
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(float)));
debuger::vertex_array_label(id, "Quad");
glBindVertexArray(0);
}
Quad::~Quad()
{
glDeleteBuffers(1, &VBO);
}
void Quad::draw() {
glCheck(glBindVertexArray(id));
glCheck(glDrawArrays(GL_TRIANGLES, 0, 6));
glCheck(glBindVertexArray(0));
}
bool Quad::init()
{
return true;
} | 24.22449 | 101 | 0.644482 | fromasmtodisasm |
13d280044dee59537eb728ef1b4c5b813675f74f | 3,199 | cc | C++ | src/operator/contrib/ctc_loss.cc | axbaretto/mxnet | 5f593885356ff6d14f5519fa18e79b944beb51cd | [
"Apache-2.0"
] | 36 | 2018-02-10T07:14:27.000Z | 2021-09-03T09:11:59.000Z | src/operator/contrib/ctc_loss.cc | axbaretto/mxnet | 5f593885356ff6d14f5519fa18e79b944beb51cd | [
"Apache-2.0"
] | 2 | 2018-05-10T02:17:26.000Z | 2019-12-23T13:49:49.000Z | src/operator/contrib/ctc_loss.cc | axbaretto/mxnet | 5f593885356ff6d14f5519fa18e79b944beb51cd | [
"Apache-2.0"
] | 15 | 2017-09-20T15:24:53.000Z | 2018-01-11T11:14:03.000Z | /*!
* Copyright (c) 2015 by Contributors
* \file ctc_loss.cc
* \brief
* \author Sebastian Bodenstein
*/
#include "./ctc_loss-inl.h"
#include "./ctc_include/detail/cpu_ctc.h"
namespace mshadow {
template <typename DType>
ctcStatus_t compute_ctc_cost(const Tensor<cpu, 3, DType> activations,
DType *costs, DType *grads, int *labels,
int *label_lengths, int *input_lengths,
void *workspace, int train) {
int minibatch = static_cast<int>(activations.size(1));
int alphabet_size = static_cast<int>(activations.size(2));
int blank_label = 0;
CpuCTC<DType> ctc(alphabet_size, minibatch, workspace, blank_label);
if (train)
return ctc.cost_and_grad(activations.dptr_, grads, costs, labels,
label_lengths, input_lengths);
else
return ctc.score_forward(activations.dptr_, costs, labels, label_lengths,
input_lengths);
}
} // namespace mshadow
namespace mxnet {
namespace op {
template <>
Operator *CreateOp<cpu>(CTCLossParam param, int dtype) {
return new CTCLossOp<cpu>(param);
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *CTCLossProp::CreateOperatorEx(Context ctx,
std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}
DMLC_REGISTER_PARAMETER(CTCLossParam);
MXNET_REGISTER_OP_PROPERTY(_contrib_CTCLoss, CTCLossProp)
.describe(R"code(Connectionist Temporal Classification Loss.
The shapes of the inputs and outputs:
- **data**: *(sequence_length, batch_size, alphabet_size + 1)*
- **label**: *(batch_size, label_sequence_length)*
- **out**: *(batch_size)*.
``label`` is a tensor of integers between 1 and *alphabet_size*. If a
sequence of labels is shorter than *label_sequence_length*, use the special
padding character 0 at the end of the sequence to conform it to the correct
length. For example, if *label_sequence_length* = 4, and one has two sequences
of labels [2, 1] and [3, 2, 2], the resulting ```label``` tensor should be
padded to be::
[[2, 1, 0, 0], [3, 2, 2, 0]]
The ``data`` tensor consists of sequences of activation vectors. The layer
applies a softmax to each vector, which then becomes a vector of probabilities
over the alphabet. Note that the 0th element of this vector is reserved for the
special blank character.
See *Connectionist Temporal Classification: Labelling Unsegmented
Sequence Data with Recurrent Neural Networks*, A. Graves *et al*. for more
information.
)code" ADD_FILELINE)
.add_argument("data", "NDArray-or-Symbol", "Input data to the ctc_loss op.")
.add_argument("label", "NDArray-or-Symbol",
"Ground-truth labels for the loss.")
.add_arguments(CTCLossParam::__FIELDS__());
NNVM_REGISTER_OP(_contrib_CTCLoss).add_alias("_contrib_ctc_loss");
} // namespace op
} // namespace mxnet
| 35.94382 | 80 | 0.687715 | axbaretto |
13d3cfe9951e3096138afc5c73a2545fe41c3717 | 1,388 | hpp | C++ | include/dca/phys/domains/quantum/particle_number_domain.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 27 | 2018-08-02T04:28:23.000Z | 2021-07-08T02:14:20.000Z | include/dca/phys/domains/quantum/particle_number_domain.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 200 | 2018-08-02T18:19:03.000Z | 2022-03-16T21:28:41.000Z | include/dca/phys/domains/quantum/particle_number_domain.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 22 | 2018-08-15T15:50:00.000Z | 2021-09-30T13:41:46.000Z | // Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Peter Staar (taa@zurich.ibm.com)
//
// This file provides the particle number domain.
#ifndef DCA_PHYS_DOMAINS_QUANTUM_PARTICLE_NUMBER_DOMAIN_HPP
#define DCA_PHYS_DOMAINS_QUANTUM_PARTICLE_NUMBER_DOMAIN_HPP
#include <vector>
namespace dca {
namespace phys {
namespace domains {
// dca::phys::domains::
template <typename band_dmn_t, typename cluster_t, typename e_spin_t>
class particle_number_domain {
public:
typedef int element_type;
static int& get_size() {
static int size = band_dmn_t::dmn_size() * cluster_t::dmn_size() * e_spin_t::dmn_size() + 1;
return size;
}
static std::vector<int>& get_elements() {
static std::vector<int>& v = initialize_elements();
return v;
}
private:
static std::vector<int>& initialize_elements();
};
template <typename band_dmn_t, typename cluster_t, typename e_spin_t>
std::vector<int>& particle_number_domain<band_dmn_t, cluster_t, e_spin_t>::initialize_elements() {
static std::vector<int> v(get_size());
for (int i = 0; i < get_size(); i++)
v[i] = i;
return v;
}
} // domains
} // phys
} // dca
#endif // DCA_PHYS_DOMAINS_QUANTUM_PARTICLE_NUMBER_DOMAIN_HPP
| 24.785714 | 98 | 0.722622 | PMDee |
13d42f4223dd4e218fda1fdc3b6cca7e6ecf00e0 | 8,763 | cc | C++ | chrome_frame/simple_resource_loader.cc | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | 7 | 2015-05-20T22:41:35.000Z | 2021-11-18T19:07:59.000Z | chrome_frame/simple_resource_loader.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | 1 | 2015-02-02T06:55:08.000Z | 2016-01-20T06:11:59.000Z | chrome_frame/simple_resource_loader.cc | jianglong0156/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/simple_resource_loader.h"
#include <atlbase.h>
#include <algorithm>
#include "base/base_paths.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/i18n/rtl.h"
#include "base/memory/singleton.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/win/i18n.h"
#include "base/win/windows_version.h"
#include "chrome_frame/policy_settings.h"
#include "ui/base/resource/data_pack.h"
namespace {
const wchar_t kLocalesDirName[] = L"Locales";
bool IsInvalidTagCharacter(wchar_t tag_character) {
return !(L'-' == tag_character ||
IsAsciiDigit(tag_character) ||
IsAsciiAlpha(tag_character));
}
// A helper function object that performs a lower-case ASCII comparison between
// two strings.
class CompareInsensitiveASCII
: public std::unary_function<const std::wstring&, bool> {
public:
explicit CompareInsensitiveASCII(const std::wstring& value)
: value_lowered_(WideToASCII(value)) {
StringToLowerASCII(&value_lowered_);
}
bool operator()(const std::wstring& comparand) {
return LowerCaseEqualsASCII(comparand, value_lowered_.c_str());
}
private:
std::string value_lowered_;
};
// Returns true if the value was added.
bool PushBackIfAbsent(
const std::wstring& value,
std::vector<std::wstring>* collection) {
if (collection->end() ==
std::find_if(collection->begin(), collection->end(),
CompareInsensitiveASCII(value))) {
collection->push_back(value);
return true;
}
return false;
}
// Returns true if the collection is modified.
bool PushBackWithFallbackIfAbsent(
const std::wstring& language,
std::vector<std::wstring>* collection) {
bool modified = false;
if (!language.empty()) {
// Try adding the language itself.
modified = PushBackIfAbsent(language, collection);
// Now try adding its fallback, if it has one.
std::wstring::size_type dash_pos = language.find(L'-');
if (0 < dash_pos && language.size() - 1 > dash_pos)
modified |= PushBackIfAbsent(language.substr(0, dash_pos), collection);
}
return modified;
}
} // namespace
SimpleResourceLoader::SimpleResourceLoader()
: data_pack_(NULL),
locale_dll_handle_(NULL) {
// Find and load the resource DLL.
std::vector<std::wstring> language_tags;
// First, try the locale dictated by policy and its fallback.
PushBackWithFallbackIfAbsent(
PolicySettings::GetInstance()->ApplicationLocale(),
&language_tags);
// Next, try the thread, process, user, system languages.
GetPreferredLanguages(&language_tags);
// Finally, fall-back on "en-US" (which may already be present in the vector,
// but that's okay since we'll exit with success when the first is tried).
language_tags.push_back(L"en-US");
FilePath locales_path;
DetermineLocalesDirectory(&locales_path);
if (!LoadLocalePack(language_tags, locales_path, &locale_dll_handle_,
&data_pack_, &language_)) {
NOTREACHED() << "Failed loading any resource dll (even \"en-US\").";
}
}
SimpleResourceLoader::~SimpleResourceLoader() {
delete data_pack_;
}
// static
SimpleResourceLoader* SimpleResourceLoader::GetInstance() {
return Singleton<SimpleResourceLoader>::get();
}
// static
void SimpleResourceLoader::GetPreferredLanguages(
std::vector<std::wstring>* language_tags) {
DCHECK(language_tags);
// The full set of preferred languages and their fallbacks are given priority.
std::vector<std::wstring> languages;
if (base::win::i18n::GetThreadPreferredUILanguageList(&languages)) {
for (std::vector<std::wstring>::const_iterator scan = languages.begin(),
end = languages.end(); scan != end; ++scan) {
PushBackIfAbsent(*scan, language_tags);
}
}
// Use the base i18n routines (i.e., ICU) as a last, best hope for something
// meaningful for the user.
PushBackWithFallbackIfAbsent(ASCIIToWide(base::i18n::GetConfiguredLocale()),
language_tags);
}
// static
void SimpleResourceLoader::DetermineLocalesDirectory(FilePath* locales_path) {
DCHECK(locales_path);
FilePath module_path;
PathService::Get(base::DIR_MODULE, &module_path);
*locales_path = module_path.Append(kLocalesDirName);
// We may be residing in the "locales" directory's parent, or we might be
// in a sibling directory. Move up one and look for Locales again in the
// latter case.
if (!file_util::DirectoryExists(*locales_path)) {
*locales_path = module_path.DirName();
*locales_path = locales_path->Append(kLocalesDirName);
}
// Don't make a second check to see if the dir is in the parent. We'll notice
// and log that in LoadLocaleDll when we actually try loading DLLs.
}
// static
bool SimpleResourceLoader::IsValidLanguageTag(
const std::wstring& language_tag) {
// "[a-zA-Z]+(-[a-zA-Z0-9]+)*" is a simplification, but better than nothing.
// Rather than pick up the weight of a regex processor, just search for a
// character that isn't in the above set. This will at least weed out
// attempts at "../../EvilBinary".
return language_tag.end() == std::find_if(language_tag.begin(),
language_tag.end(),
&IsInvalidTagCharacter);
}
// static
bool SimpleResourceLoader::LoadLocalePack(
const std::vector<std::wstring>& language_tags,
const FilePath& locales_path,
HMODULE* dll_handle,
ui::DataPack** data_pack,
std::wstring* language) {
DCHECK(language);
// The dll should only have resources, not executable code.
const DWORD load_flags =
(base::win::GetVersion() >= base::win::VERSION_VISTA ?
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE :
DONT_RESOLVE_DLL_REFERENCES);
const std::wstring dll_suffix(L".dll");
const std::wstring pack_suffix(L".pak");
bool found_pack = false;
for (std::vector<std::wstring>::const_iterator scan = language_tags.begin(),
end = language_tags.end();
scan != end;
++scan) {
if (!IsValidLanguageTag(*scan)) {
LOG(WARNING) << "Invalid language tag supplied while locating resources:"
" \"" << *scan << "\"";
continue;
}
// Attempt to load both the resource pack and the dll. We return success
// only we load both.
FilePath resource_pack_path = locales_path.Append(*scan + pack_suffix);
FilePath dll_path = locales_path.Append(*scan + dll_suffix);
if (file_util::PathExists(resource_pack_path) &&
file_util::PathExists(dll_path)) {
scoped_ptr<ui::DataPack> cur_data_pack(
new ui::DataPack(ui::SCALE_FACTOR_100P));
if (!cur_data_pack->LoadFromPath(resource_pack_path))
continue;
HMODULE locale_dll_handle = LoadLibraryEx(dll_path.value().c_str(), NULL,
load_flags);
if (locale_dll_handle) {
*dll_handle = locale_dll_handle;
*language = dll_path.BaseName().RemoveExtension().value();
*data_pack = cur_data_pack.release();
found_pack = true;
break;
} else {
*data_pack = NULL;
}
}
}
DCHECK(found_pack || file_util::DirectoryExists(locales_path))
<< "Could not locate locales DLL directory.";
return found_pack;
}
std::wstring SimpleResourceLoader::GetLocalizedResource(int message_id) {
if (!data_pack_) {
DLOG(ERROR) << "locale resources are not loaded";
return std::wstring();
}
DCHECK(IS_INTRESOURCE(message_id));
base::StringPiece data;
if (!data_pack_->GetStringPiece(message_id, &data)) {
DLOG(ERROR) << "Unable to find string for resource id:" << message_id;
return std::wstring();
}
// Data pack encodes strings as either UTF8 or UTF16.
string16 msg;
if (data_pack_->GetTextEncodingType() == ui::DataPack::UTF16) {
msg = string16(reinterpret_cast<const char16*>(data.data()),
data.length() / 2);
} else if (data_pack_->GetTextEncodingType() == ui::DataPack::UTF8) {
msg = UTF8ToUTF16(data);
}
return msg;
}
// static
std::wstring SimpleResourceLoader::GetLanguage() {
return SimpleResourceLoader::GetInstance()->language_;
}
// static
std::wstring SimpleResourceLoader::Get(int message_id) {
SimpleResourceLoader* loader = SimpleResourceLoader::GetInstance();
return loader->GetLocalizedResource(message_id);
}
HMODULE SimpleResourceLoader::GetResourceModuleHandle() {
return locale_dll_handle_;
}
| 32.455556 | 80 | 0.686181 | junmin-zhu |
13d4c9b5bcc4411ea79f00fc38502230ba2f402c | 5,655 | cpp | C++ | OREData/ored/portfolio/builders/cms.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 335 | 2016-10-07T16:31:10.000Z | 2022-03-02T07:12:03.000Z | OREData/ored/portfolio/builders/cms.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 59 | 2016-10-31T04:20:24.000Z | 2022-01-03T16:39:57.000Z | OREData/ored/portfolio/builders/cms.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 180 | 2016-10-08T14:23:50.000Z | 2022-03-28T10:43:05.000Z | /*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ored/portfolio/builders/cms.hpp>
#include <ored/utilities/log.hpp>
#include <ored/utilities/parsers.hpp>
#include <boost/make_shared.hpp>
using namespace QuantLib;
namespace ore {
namespace data {
namespace {
Real parseCcyReversion(const std::map<string, string>& p, const std::string& ccy) {
// either we have a ccy specific reversion or require a ccy independent reversion parameter
if (p.find("MeanReversion_" + ccy) != p.end())
return parseReal(p.at("MeanReversion_" + ccy));
else
return parseReal(p.at("MeanReversion"));
}
} // namespace
GFunctionFactory::YieldCurveModel ycmFromString(const string& s) {
if (s == "Standard")
return GFunctionFactory::Standard;
else if (s == "ExactYield")
return GFunctionFactory::ExactYield;
else if (s == "ParallelShifts")
return GFunctionFactory::ParallelShifts;
else if (s == "NonParallelShifts")
return GFunctionFactory::NonParallelShifts;
else
QL_FAIL("unknown string for YieldCurveModel");
}
boost::shared_ptr<FloatingRateCouponPricer> AnalyticHaganCmsCouponPricerBuilder::engineImpl(const Currency& ccy) {
const string& ccyCode = ccy.code();
Real rev = parseCcyReversion(engineParameters_, ccyCode);
string ycmstr = engineParameter("YieldCurveModel");
GFunctionFactory::YieldCurveModel ycm = ycmFromString(ycmstr);
Handle<Quote> revQuote(boost::shared_ptr<Quote>(new SimpleQuote(rev)));
Handle<SwaptionVolatilityStructure> vol = market_->swaptionVol(ccyCode, configuration(MarketContext::pricing));
boost::shared_ptr<FloatingRateCouponPricer> pricer = boost::make_shared<AnalyticHaganPricer>(vol, ycm, revQuote);
// Return the cached pricer
return pricer;
}
boost::shared_ptr<FloatingRateCouponPricer> NumericalHaganCmsCouponPricerBuilder::engineImpl(const Currency& ccy) {
const string& ccyCode = ccy.code();
Real rev = parseCcyReversion(engineParameters_, ccyCode);
string ycmstr = engineParameter("YieldCurveModel");
GFunctionFactory::YieldCurveModel ycm = ycmFromString(ycmstr);
Rate llim = parseReal(engineParameter("LowerLimit"));
Rate ulim = parseReal(engineParameter("UpperLimit"));
Real prec = parseReal(engineParameter("Precision"));
Handle<Quote> revQuote(boost::shared_ptr<Quote>(new SimpleQuote(rev)));
Handle<SwaptionVolatilityStructure> vol = market_->swaptionVol(ccyCode, configuration(MarketContext::pricing));
boost::shared_ptr<FloatingRateCouponPricer> pricer =
boost::make_shared<NumericHaganPricer>(vol, ycm, revQuote, llim, ulim, prec);
// Return the cached pricer
return pricer;
}
boost::shared_ptr<FloatingRateCouponPricer> LinearTSRCmsCouponPricerBuilder::engineImpl(const Currency& ccy) {
const string& ccyCode = ccy.code();
Real rev = parseCcyReversion(engineParameters_, ccyCode);
string policy = engineParameter("Policy");
Handle<Quote> revQuote(boost::shared_ptr<Quote>(new SimpleQuote(rev)));
Handle<SwaptionVolatilityStructure> vol = market_->swaptionVol(ccyCode, configuration(MarketContext::pricing));
Handle<YieldTermStructure> yts = market_->discountCurve(ccyCode, configuration(MarketContext::pricing));
string lowerBoundStr =
(vol->volatilityType() == ShiftedLognormal) ? "LowerRateBoundLogNormal" : "LowerRateBoundNormal";
string upperBoundStr =
(vol->volatilityType() == ShiftedLognormal) ? "UpperRateBoundLogNormal" : "UpperRateBoundNormal";
LinearTsrPricer::Settings settings;
if (policy == "RateBound") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
settings.withRateBound(lower, upper);
} else if (policy == "VegaRatio") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
Real vega = parseReal(engineParameter("VegaRatio"));
settings.withVegaRatio(vega, lower, upper);
} else if (policy == "PriceThreshold") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
Real threshold = parseReal(engineParameter("PriceThreshold"));
settings.withPriceThreshold(threshold, lower, upper);
} else if (policy == "BsStdDev") {
Real lower = parseReal(engineParameter(lowerBoundStr));
Real upper = parseReal(engineParameter(upperBoundStr));
Real stddevs = parseReal(engineParameter("BSStdDevs"));
settings.withPriceThreshold(stddevs, lower, upper);
} else
QL_FAIL("unknown string for policy parameter");
boost::shared_ptr<FloatingRateCouponPricer> pricer =
boost::make_shared<LinearTsrPricer>(vol, revQuote, yts, settings);
// Return the cached pricer
return pricer;
}
} // namespace data
} // namespace ore
| 41.888889 | 117 | 0.732449 | mrslezak |
13d525628e0cd5326d11d9868b0bc43343a73ae6 | 1,863 | hpp | C++ | include/voxel/async_structure.hpp | InjectorGames/VoxelLibrary | be8cc4ec179e9d86eb1bd25b1c7f8adfe8ad4198 | [
"BSD-3-Clause"
] | 1 | 2021-09-16T12:30:49.000Z | 2021-09-16T12:30:49.000Z | include/voxel/async_structure.hpp | InjectorGames/VoxelSpaceCPP | be8cc4ec179e9d86eb1bd25b1c7f8adfe8ad4198 | [
"BSD-3-Clause"
] | 1 | 2020-05-08T14:24:41.000Z | 2020-05-08T14:24:41.000Z | include/voxel/async_structure.hpp | InjectorGames/Voxel | be8cc4ec179e9d86eb1bd25b1c7f8adfe8ad4198 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <voxel/structure.hpp>
#include <mutex>
#include <thread>
namespace VOXEL_NAMESPACE
{
template<class T = Sector>
class AsyncStructure : public Structure<T>
{
protected:
bool isRunning;
std::mutex updateMutex;
std::thread updateThread;
inline void update(const Registry& registry)
{
std::chrono::steady_clock::time_point lastTime;
while (isRunning)
{
updateMutex.lock();
const auto time = std::chrono::high_resolution_clock::now();
const auto deltaTime = std::chrono::duration_cast<
std::chrono::duration<time_t>>(time - lastTime);
lastTime = time;
Structure<T>::update(registry, deltaTime.count());
if (sleepDelay > 0)
std::this_thread::sleep_for(std::chrono::milliseconds(sleepDelay));
updateMutex.unlock();
}
}
public:
int sleepDelay;
AsyncStructure(const size3_t& size,
const structure_pos_t& position,
const std::shared_ptr<T> sector,
const int _sleepDelay = 1) :
Structure<T>(size, position, sector),
sleepDelay(_sleepDelay),
isRunning(false),
updateMutex(),
updateThread()
{}
virtual ~AsyncStructure()
{
if (isRunning)
stopUpdate();
}
AsyncStructure(const AsyncStructure<T>&) = delete;
inline void lockUpdate() noexcept
{
updateMutex.lock();
}
inline void unlockUpdate() noexcept
{
updateMutex.unlock();
}
inline void startUpdate(const Registry& registry)
{
if (isRunning)
throw std::runtime_error("Thread is already running");
isRunning = true;
updateThread = std::thread(&AsyncStructure<T>::update, this, registry);
}
inline void stopUpdate()
{
if (!isRunning)
throw std::runtime_error("Thread is not running");
isRunning = false;
if (updateThread.get_id() != std::this_thread::get_id() &&
updateThread.joinable())
updateThread.join();
}
};
}
| 21.170455 | 74 | 0.677939 | InjectorGames |