hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
761ba923dd918978d91b341aeb08f26cf68b7724 | 665 | cpp | C++ | linear_ds/no_problem.cpp | alpha721/Competitive-Programming-3- | 548fe84e69beca6fd1ddfedac3aa306d9870cd29 | [
"MIT"
] | null | null | null | linear_ds/no_problem.cpp | alpha721/Competitive-Programming-3- | 548fe84e69beca6fd1ddfedac3aa306d9870cd29 | [
"MIT"
] | null | null | null | linear_ds/no_problem.cpp | alpha721/Competitive-Programming-3- | 548fe84e69beca6fd1ddfedac3aa306d9870cd29 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
using namespace std;
int main()
{
int t = 1;
while(1)
{
int n;
cin >> n;
if( n < 0)
break;
cout << "Case " << t << ":" << endl;
int available = n;
vector<int> created;
vector<int> required;
int x;
for(int i = 0; i < 12; i++)
{
cin >> x;
created.push_back(x);
}
for(int i = 0; i < 12; i++)
{
cin >> x;
required.push_back(x);
}
for(int i = 0; i < 12; i++)
{
if( available - required[i] < 0)
cout << "No problem. :(" << endl;
else
{
cout << "No problem! :D" << endl;
available -= required[i];
}
available += created[i];
}
t++;
}
return 0;
}
| 13.571429 | 38 | 0.488722 | [
"vector"
] |
761bff1bed662120b7098edba20a4b91f0e6ae50 | 7,013 | cpp | C++ | unit_tests/imaging/view_transforms.cpp | mghro/astroid-core | 72736f64bed19ec3bb0e92ebee4d7cf09fc0399f | [
"MIT"
] | null | null | null | unit_tests/imaging/view_transforms.cpp | mghro/astroid-core | 72736f64bed19ec3bb0e92ebee4d7cf09fc0399f | [
"MIT"
] | 3 | 2020-10-26T18:45:47.000Z | 2020-10-26T18:46:06.000Z | unit_tests/imaging/view_transforms.cpp | mghro/astroid-core | 72736f64bed19ec3bb0e92ebee4d7cf09fc0399f | [
"MIT"
] | null | null | null | #include <cradle/common.hpp>
#include <cradle/imaging/geometry.hpp>
#include <cradle/imaging/sample.hpp>
#include <cradle/imaging/view_transforms.hpp>
#include <cradle/imaging/test.hpp>
using namespace cradle;
TEST_CASE("r90ccw_test")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
image<2, cradle::uint8_t, const_view> xformed
= raw_rotated_90ccw_view(view);
cradle::uint8_t correct[] = {
3,
6,
9,
2,
5,
8,
1,
4,
7,
};
CRADLE_CHECK_IMAGE(xformed, correct, correct + sizeof(correct));
}
TEST_CASE("r90cw_test")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
image<2, cradle::uint8_t, const_view> xformed
= raw_rotated_90cw_view(view);
cradle::uint8_t correct[] = {
7,
4,
1,
8,
5,
2,
9,
6,
3,
};
CRADLE_CHECK_IMAGE(xformed, correct, correct + sizeof(correct));
}
TEST_CASE("r180_test")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
image<2, cradle::uint8_t, const_view> xformed = raw_rotated_180_view(view);
cradle::uint8_t correct[] = {
9,
8,
7,
6,
5,
4,
3,
2,
1,
};
CRADLE_CHECK_IMAGE(xformed, correct, correct + sizeof(correct));
}
TEST_CASE("raw_flipx_test")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
image<2, cradle::uint8_t, const_view> xformed = raw_flipped_view(view, 0);
cradle::uint8_t correct[] = {
3,
2,
1,
6,
5,
4,
9,
8,
7,
};
CRADLE_CHECK_IMAGE(xformed, correct, correct + sizeof(correct));
}
TEST_CASE("raw_flipy_test")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
image<2, cradle::uint8_t, const_view> xformed = raw_flipped_view(view, 1);
cradle::uint8_t correct[] = {
7,
8,
9,
4,
5,
6,
1,
2,
3,
};
CRADLE_CHECK_IMAGE(xformed, correct, correct + sizeof(correct));
}
TEST_CASE("flipx_test")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
image<2, cradle::uint8_t, const_view> xformed = flipped_view(view, 0);
size_t const n_points = 10;
double points[n_points][2]
= {{1, 0},
{2, 1},
{1.5, 1},
{0, 0},
{2.5, 1.5},
{2.5, 1},
{-1, 0},
{0, 1},
{0.5, 2},
{0.5, 1}};
for (size_t i = 0; i != n_points; ++i)
{
optional<double> s1 = interpolated_image_sample(
view, make_vector(points[i][0], points[i][1]));
optional<double> s2 = interpolated_image_sample(
xformed, make_vector(-points[i][0], points[i][1]));
REQUIRE((s1 ? true : false) == (s2 ? true : false));
if (s1 && s2)
CRADLE_CHECK_ALMOST_EQUAL(s1.get(), s2.get());
}
}
TEST_CASE("flipy_test")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
image<2, cradle::uint8_t, const_view> xformed = flipped_view(view, 1);
size_t const n_points = 10;
double points[n_points][2]
= {{1, 0},
{2, 1},
{1.5, 1},
{1, -1},
{2.5, 1.5},
{1, 2.5},
{-1, 2.5},
{0, 1},
{0.5, 2},
{0.5, 0.5}};
for (size_t i = 0; i != n_points; ++i)
{
optional<double> s1 = interpolated_image_sample(
view, make_vector(points[i][0], points[i][1]));
optional<double> s2 = interpolated_image_sample(
xformed, make_vector(points[i][0], -points[i][1]));
REQUIRE((s1 ? true : false) == (s2 ? true : false));
if (s1 && s2)
CRADLE_CHECK_ALMOST_EQUAL(s1.get(), s2.get());
}
}
void
test_aligned_view(image<2, cradle::uint8_t, const_view> const& view)
{
REQUIRE(is_orthogonal_to_axes(view));
image<2, cradle::uint8_t, const_view> aligned = aligned_view(view);
REQUIRE(is_axis_aligned(aligned));
size_t const n_points = 20;
double points[n_points][2]
= {{1, 0.1}, {2, 1}, {1.5, 1}, {1, -1}, {2.5, 1.5},
{1, 2.5}, {-1, 2.5}, {-0.1, 1}, {0.5, 2}, {0.5, 0.5},
{-1, 0.5}, {-2, 1}, {-1.5, -1}, {-1, 1}, {-2.5, -1.5},
{-1, -2.5}, {-1, -2.5}, {0.1, -1}, {0.5, -2}, {-0.5, 0.5}};
for (size_t i = 0; i != n_points; ++i)
{
vector2d p = make_vector(points[i][0], points[i][1]);
optional<double> s1 = interpolated_image_sample(view, p);
optional<double> s2 = interpolated_image_sample(aligned, p);
REQUIRE((s1 ? true : false) == (s2 ? true : false));
if (s1 && s2)
CRADLE_CHECK_ALMOST_EQUAL(s1.get(), s2.get());
}
}
TEST_CASE("aligned_test_2d")
{
cradle::uint8_t original[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
};
image<2, cradle::uint8_t, const_view> view
= make_const_view(original, make_vector<unsigned>(3, 3));
test_aligned_view(view);
test_aligned_view(flipped_view(view, 0));
test_aligned_view(flipped_view(view, 1));
test_aligned_view(
transformed_view(view, rotation(angle<double, degrees>(90))));
test_aligned_view(
transformed_view(view, rotation(angle<double, degrees>(-90))));
test_aligned_view(
transformed_view(view, rotation(angle<double, degrees>(180))));
test_aligned_view(transformed_view(
flipped_view(view, 1), rotation(angle<double, degrees>(-90))));
}
| 22.993443 | 79 | 0.494653 | [
"geometry"
] |
761fcc1a0bd73a3a1e951ed74a703430046ccf83 | 1,953 | cpp | C++ | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Inspector/ContentHeaderWidget.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Inspector/ContentHeaderWidget.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Inspector/ContentHeaderWidget.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Inspector/ContentHeaderWidget.h>
#include <QHBoxLayout>
#include <QLabel>
namespace EMStudio
{
ContentHeaderWidget::ContentHeaderWidget(QWidget* parent)
: QWidget(parent)
{
m_iconLabel = new QLabel();
m_titleLabel = new QLabel();
m_titleLabel->setStyleSheet("font-weight: bold;");
QHBoxLayout* filenameLayout = new QHBoxLayout();
filenameLayout->setMargin(2);
filenameLayout->addWidget(m_titleLabel, 0, Qt::AlignTop);
QVBoxLayout* vLayout = new QVBoxLayout();
vLayout->addLayout(filenameLayout);
QHBoxLayout* mainLayout = new QHBoxLayout(this);
mainLayout->addWidget(m_iconLabel, 0, Qt::AlignLeft | Qt::AlignTop);
mainLayout->addLayout(vLayout);
mainLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
}
void ContentHeaderWidget::Update(const QString& title, const QString& iconFilename)
{
m_titleLabel->setText(title);
m_iconLabel->setPixmap(FindOrCreateIcon((iconFilename)));
}
const QPixmap& ContentHeaderWidget::FindOrCreateIcon(const QString& iconFilename)
{
// Check if we have already loaded the icon.
const auto iterator = m_cachedIcons.find(iconFilename);
if (iterator != m_cachedIcons.end())
{
return iterator.value();
}
// Load it in case the icon is not in the cache.
m_cachedIcons[iconFilename] = QPixmap(iconFilename).scaled(QSize(s_iconSize, s_iconSize), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
return m_cachedIcons[iconFilename];
}
} // namespace EMStudio
| 34.875 | 147 | 0.687148 | [
"3d"
] |
7631ae34ce2d234ca82df974150b4e6de645452f | 454 | cpp | C++ | src/iterator.cpp | Toxe/test-cpp | 75485d683c4cf172818a5b62a903d415fcafe024 | [
"MIT"
] | null | null | null | src/iterator.cpp | Toxe/test-cpp | 75485d683c4cf172818a5b62a903d415fcafe024 | [
"MIT"
] | null | null | null | src/iterator.cpp | Toxe/test-cpp | 75485d683c4cf172818a5b62a903d415fcafe024 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
int main()
{
std::vector<int> v1{1, 2, 3, 4, 5};
auto it1 = v1.begin(); // std::vector<int>::iterator
auto it2 = v1.cbegin(); // std::vector<int>::const_iterator
for (auto it = v1.begin(); it != v1.end(); ++it)
std::cout << *it << std::endl;
int a[] = {10, 11, 12};
for (auto it = std::begin(a); it != std::end(a); ++it)
std::cout << *it << std::endl;
return 0;
}
| 22.7 | 64 | 0.511013 | [
"vector"
] |
764a77ddd0ae682f54066bf38774bcb48b18d4f9 | 2,169 | cpp | C++ | visualization/src/VisualizationApp/AudioManager.cpp | HellicarAndLewis/RedLeaf | 41ed7a293dbc3c905e3ce7559fff19b685003198 | [
"MIT"
] | 1 | 2015-11-05T13:33:04.000Z | 2015-11-05T13:33:04.000Z | visualization/src/VisualizationApp/AudioManager.cpp | HellicarAndLewis/RedLeaf | 41ed7a293dbc3c905e3ce7559fff19b685003198 | [
"MIT"
] | null | null | null | visualization/src/VisualizationApp/AudioManager.cpp | HellicarAndLewis/RedLeaf | 41ed7a293dbc3c905e3ce7559fff19b685003198 | [
"MIT"
] | null | null | null | /*
* AudioManager.cpp
*
* Created on: Sep 20, 2012
* Author: arturo
*/
#include "AudioManager.h"
AudioManager::AudioManager() {
tweet = NULL;
leds = NULL;
}
AudioManager::~AudioManager() {
// TODO Auto-generated destructor stub
}
void AudioManager::setup(){
audioTest.addListener(this,&AudioManager::audioTestChanged);
parameters.setName("Audio");
parameters.add(vumeter.set("audioInAmp",0,0,1));
parameters.add(cutDown.set("cutDown",0,0,1));
parameters.add(cutUp.set("cutUp",1,0,1));
parameters.add(mappedVumeter.set("mappedAudioIn",0,0,1));
parameters.add(smoothedVumeter.set("smoothedAudioIn",0,0,1));
parameters.add(smoothFactor.set("smoothFactor",0.9,0,0.9));
parameters.add(fineSmoothFactor.set("fineSmoothFactor",0,0,0.09999));
parameters.add(audioEnabledForBursts.set("audioEnabledForBursts",false));
parameters.add(audioEnabledForText.set("audioEnabledForText",false));
parameters.add(audioTest.set("audioTest",false));
soundBuffer.resize(256,0);
soundBuffer.setSampleRate(44100);
sound.setup(0,1,44100,256,1);
sound.setInput(this);
}
void AudioManager::audioTestChanged(bool & enabled){
for(u_int i=0;i<leds->size();i++){
leds->at(i).setTestMode(enabled);
}
}
void AudioManager::setLeds(vector<LEDStrip> & _leds){
leds = &_leds;
}
void AudioManager::setCurrentTweet(TweetText * _tweet){
tweet = _tweet;
}
void AudioManager::update(){
u_long now = ofGetElapsedTimeMillis();
if(audioTest){
for(u_int i=0;i<leds->size();i++){
leds->at(i).trigger(ofColor::white*smoothedVumeter,now);
}
}else{
if(audioEnabledForBursts){
for(u_int i=0;i<leds->size();i++){
leds->at(i).setAmplitude(smoothedVumeter);
}
}
if(tweet && audioEnabledForText){
tweet->setAmplitude(smoothedVumeter);
}
}
}
void AudioManager::audioIn(float * in,int bufferSize,int nChannels,int deviceID,unsigned long long tickCount){
soundBuffer.set(in,bufferSize,nChannels);
vumeter = soundBuffer.getRMSAmplitude();
mappedVumeter = ofMap(vumeter,cutDown,cutUp,0,1,true);
smoothedVumeter = max((float)mappedVumeter,smoothedVumeter*(smoothFactor+fineSmoothFactor) + mappedVumeter*(1-(smoothFactor+fineSmoothFactor)));
}
| 26.45122 | 145 | 0.73029 | [
"vector"
] |
7652b18757719fd91e79636f2aa4a3cfbaf96371 | 347 | hpp | C++ | lib/errors.hpp | martinogden/mer | 33b4b39b1604ce0708b0d3d1c809b95683a2f4cb | [
"Unlicense"
] | 2 | 2019-11-17T22:54:16.000Z | 2020-08-07T20:53:25.000Z | lib/errors.hpp | martinogden/mer | 33b4b39b1604ce0708b0d3d1c809b95683a2f4cb | [
"Unlicense"
] | null | null | null | lib/errors.hpp | martinogden/mer | 33b4b39b1604ce0708b0d3d1c809b95683a2f4cb | [
"Unlicense"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include "parser/token.hpp"
class Errors {
private:
std::vector<std::string> errors;
std::string label;
public:
Errors(std::string label="Error");
void append(Errors&);
void add(const std::string&);
void add(const std::string&, Token);
std::vector<std::string>& get();
bool exist();
};
| 16.52381 | 37 | 0.682997 | [
"vector"
] |
76596fa04c5f416760f887a4eccd28befa410ae1 | 2,472 | hpp | C++ | gedl/include/FunctionWrapper.hpp | gaps-closure/capo | 894d2f6d291ff79e18c77e0ca7073531147cbee8 | [
"BSD-3-Clause"
] | 1 | 2021-04-20T18:43:44.000Z | 2021-04-20T18:43:44.000Z | gedl/include/FunctionWrapper.hpp | gaps-closure/capo | 894d2f6d291ff79e18c77e0ca7073531147cbee8 | [
"BSD-3-Clause"
] | 1 | 2021-09-23T14:55:43.000Z | 2021-09-23T18:09:35.000Z | gedl/include/FunctionWrapper.hpp | gaps-closure/capo | 894d2f6d291ff79e18c77e0ca7073531147cbee8 | [
"BSD-3-Clause"
] | 1 | 2020-05-21T03:12:16.000Z | 2020-05-21T03:12:16.000Z | #ifndef FUNCTIONWRAPPER_H_
#define FUNCTIONWRAPPER_H_
#include "llvm/IR/Function.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "InstructionWrapper.hpp"
#include "tree.hh"
#include <vector>
#include "ArgumentWrapper.hpp"
namespace pdg
{
class FunctionWrapper
{
public:
FunctionWrapper() = delete;
FunctionWrapper(llvm::Function *Func);
bool hasTrees();
void setTreeFlag(bool treeFlag) { this->treeFlag = treeFlag; }
bool isVisited();
void setVisited(bool visited) { this->visited = visited; }
void setEntryW(InstructionWrapper *entryW) { this->entryW = entryW; }
InstructionWrapper *getEntryW() { return entryW; }
std::vector<llvm::StoreInst *> &getStoreInstList() { return storeInstList; }
std::vector<llvm::LoadInst *> &getLoadInstList() { return loadInstList; }
std::vector<llvm::Instruction *> &getReturnInstList() { return returnInstList; }
std::vector<llvm::CallInst *> &getCallInstList() { return callInstList; }
std::vector<llvm::CastInst *> &getCastInstList() { return castInstList; }
std::vector<llvm::IntrinsicInst *> &getIntrinsicInstList() { return intrinsicInstList; }
std::vector<llvm::DbgDeclareInst *> &getDbgDeclareInstList() { return dbgDeclareInst; }
std::vector<ArgumentWrapper *> &getArgWList() { return argWList; }
void addStoreInst(llvm::Instruction *inst);
void addLoadInst(llvm::Instruction *inst);
void addReturnInst(llvm::Instruction *inst) { returnInstList.push_back(inst); }
void addCallInst(llvm::Instruction *inst);
void addCastInst(llvm::Instruction *inst);
void addIntrinsicInst(llvm::Instruction *inst);
void addDbgInst(llvm::Instruction *inst);
ArgumentWrapper *getArgWByArg(llvm::Argument &arg);
ArgumentWrapper *getArgWByIdx(int idx);
ArgumentWrapper *getRetW() { return retW; }
private:
llvm::Function *Func;
InstructionWrapper *entryW;
std::vector<llvm::StoreInst *> storeInstList;
std::vector<llvm::LoadInst *> loadInstList;
std::vector<llvm::Instruction *> returnInstList;
std::vector<llvm::CallInst *> callInstList;
std::vector<llvm::CastInst *> castInstList;
std::vector<llvm::IntrinsicInst *> intrinsicInstList;
std::vector<llvm::DbgDeclareInst *> dbgDeclareInst;
std::vector<ArgumentWrapper *> argWList;
std::set<llvm::Function *> dependent_funcs;
std::set<llvm::Value *> ptrSet;
ArgumentWrapper* retW;
bool treeFlag;
bool RWFlag;
bool visited;
};
} // namespace pdg
#endif | 38.625 | 90 | 0.737864 | [
"vector"
] |
7659cc3eb4e9aa14c75e37318f5e54d6328f5723 | 75,964 | cpp | C++ | platform/android/ndk/jni/NativeToJavaBridge.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | platform/android/ndk/jni/NativeToJavaBridge.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | platform/android/ndk/jni/NativeToJavaBridge.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "Core/Rtt_Build.h"
#include <android/log.h>
#include <stddef.h>
#include <stdio.h>
#include <fcntl.h>
#include "Rtt_AndroidPlatform.h"
#include "Rtt_Lua.h"
#include "Rtt_LuaContext.h"
#include "Rtt_LuaLibNative.h"
#include "Rtt_LuaLibSystem.h"
#include "Rtt_LuaResource.h"
#include "Rtt_MPlatform.h"
#include "Display/Rtt_PlatformBitmap.h"
#include "Rtt_PlatformWebPopup.h"
#include "Rtt_PreferenceCollection.h"
#include "Rtt_Runtime.h"
#include "NativeToJavaBridge.h"
#include "AndroidImageData.h"
#include "AndroidZipFileEntry.h"
#include "jniUtils.h"
// ----------------------------------------------------------------------------
static const char kNativeToJavaBridge[] = "com/ansca/corona/NativeToJavaBridge";
JavaVM *NativeToJavaBridge::fVM;
// Signatures available through:
// javap -classpath bin -protected com.ansca.corona.CoronaBridge -s
// TODO: check for exceptions
// ----------------------------------------------------------------------------
extern "C" void debugPrint(const char *msg)
{
#ifdef Rtt_DEBUG
__android_log_print(ANDROID_LOG_INFO, "Corona", "%s", msg);
#endif
}
void*
NativeToJavaBridge::JavaToNative( jpointer p )
{
Rtt_STATIC_ASSERT( sizeof( p ) == sizeof( jpointer ) );
return (void*)p;
}
NativeToJavaBridge*
NativeToJavaBridge::InitInstance( JNIEnv *env, Rtt::Runtime *runtime, jobject coronaRuntime )
{
JavaVM * vm;
jint result = env->GetJavaVM(&vm);
if ( 0 == result )
{
return new NativeToJavaBridge( vm, runtime, coronaRuntime );
}
return NULL;
}
// ----------------------------------------------------------------------------
NativeToJavaBridge::NativeToJavaBridge(JavaVM *vm, Rtt::Runtime *runtime, jobject coronaRuntime)
{
fVM = vm;
fRuntime = runtime;
fCoronaRuntime = coronaRuntime;
// fHasLuaErrorOccurred = false;
fAlertCallbackResource = NULL;
fPopupClosedEventResource = NULL;
}
JNIEnv *
NativeToJavaBridge::GetJNIEnv()
{
JNIEnv * env = NULL;
if (fVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
{
debugPrint( "> NativeToJavaBridge::GetJNIEnv null");
}
return env;
}
Rtt::Runtime *
NativeToJavaBridge::GetRuntime() const
{
return fRuntime;
}
Rtt::AndroidPlatform *
NativeToJavaBridge::GetPlatform() const
{
if (!fRuntime)
{
return NULL;
}
return (Rtt::AndroidPlatform*)&(fRuntime->Platform());
}
/// Checks if a Java exception was thrown.
/// If so, then the Java exception is caught and a Lua error gets raised so that the error can be handled
/// gracefully by a Lua pcall() or a Java handler given to the CoronaEnvironment.setLuaErrorHandler() method.
/// Note: This function will do a longjmp() if an exception was found to unwind the stack back to the caller
/// of the Lua function. This means that C++ objects on the stack will not have their destructors called.
void
NativeToJavaBridge::HandleJavaException() const
{
if (fRuntime)
{
HandleJavaExceptionUsing(fRuntime->VMContext().L());
}
}
/// Checks if a Java exception was thrown.
/// If so, then the Java exception is caught and a Lua error gets raised so that the error can be handled
/// gracefully by a Lua pcall() or a Java handler given to the CoronaEnvironment.setLuaErrorHandler() method.
/// Note: This function will do a longjmp() if an exception was found to unwind the stack back to the caller
/// of the Lua function. This means that C++ objects on the stack will not have their destructors called.
/// @param L Pointer to a lua_State to raise a Lua error on if an exception was found. Cannot be NULL.
void
NativeToJavaBridge::HandleJavaExceptionUsing( lua_State *L ) const
{
// Fetch the JNI environment.
JNIEnv *jniEnvironmentPointer = GetJNIEnv();
if (!jniEnvironmentPointer)
{
return;
}
// Check if a Java exception was thrown.
// If not, then there is no error to handle.
if (jniEnvironmentPointer->ExceptionCheck() == JNI_FALSE)
{
return;
}
// A Java exception was thrown.
// Catch it here so that the Java side of this application won't terminate.
jthrowable exception = jniEnvironmentPointer->ExceptionOccurred();
jniEnvironmentPointer->ExceptionClear();
// Fetch the exception's error message and stack trace.
const char *errorMessage = "Java exception occurred.";
jstringResult stringResult(jniEnvironmentPointer);
jclassInstance bridge(jniEnvironmentPointer, kNativeToJavaBridge);
if (bridge.isValid())
{
jmethodID getExceptionStackTraceMethodId = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(),
"callGetExceptionStackTraceFrom",
"(Ljava/lang/Throwable;)Ljava/lang/String;");
jobject objectResult = bridge.getEnv()->CallStaticObjectMethod(
bridge.getClass(), getExceptionStackTraceMethodId, exception);
if (objectResult)
{
stringResult.setString((jstring)objectResult);
}
}
if (stringResult.isValidString())
{
errorMessage = stringResult.getUTF8();
}
// Raise a Lua error using the Java exception's error message.
// This error can then be handled by the following:
// - A Lua pcall() function.
// - A Java handler passed to the CoronaEnvironment.setLuaErrorHandler() method.
// Note: This will do a longjmp() to unwind the stack back to where Lua called our native API.
if (L)
{
luaL_error(L, errorMessage);
}
}
/// Creates a new Java dictionary object populated with the given Lua state's table entries.
/// @param L The Lua state to read the table entries from.
/// @param t Index to the Lua table to read. It must be greater than zero. ie: It cannot be a relative index.
/// @param bridge The JNI bridge interfae to create the dictionary object in.
/// @return Returns the Java dictionary object populated with the Lua table's entries.
/// Returns NULL if failed to create the dictionary or if given invalid parameters.
NativeToJavaBridge::DictionaryRef
NativeToJavaBridge::DictionaryCreate( lua_State *L, int t, NativeToJavaBridge *bridge )
{
// Validate arguments.
if (!L || !bridge || (t <= 0))
{
return NULL;
}
// Do not continue if the referenced Lua object on the stack is not a table/array.
if (!lua_istable( L, t ))
{
return NULL;
}
// Create the Java dictionary object.
NativeToJavaBridge::DictionaryRef dict = bridge->DictionaryCreate();
if (!dict)
{
return NULL;
}
// Add all Lua table entries to the Java dictionary.
char stringBuffer[32];
for (lua_pushnil( L ); lua_next( L, t ) != 0; lua_pop( L, 1 ))
{
// Fetch the table entry's key.
const char *keyName = NULL;
int valueType = lua_type( L, -2 );
if (LUA_TSTRING == valueType)
{
keyName = lua_tostring( L, -2 );
}
else if (LUA_TNUMBER == valueType)
{
// The key will be a number if we're traversing a Lua array.
// Convert the numeric index to a string and use that as the key name in the hash table.
int value = (int)(lua_tonumber( L, -2 ) + 0.5);
if (snprintf(stringBuffer, sizeof(stringBuffer), "%d", value) > 0)
{
keyName = stringBuffer;
}
}
if (!keyName)
{
continue;
}
// Add the key/value pair to the Java dictionary.
valueType = lua_type( L, -1 );
switch (valueType)
{
case LUA_TSTRING:
((jHashMapParam*)dict)->put( keyName, lua_tostring( L, -1 ) );
break;
case LUA_TBOOLEAN:
((jHashMapParam*)dict)->put( keyName, lua_toboolean( L, -1 ) ? true : false );
break;
case LUA_TNUMBER:
((jHashMapParam*)dict)->put( keyName, (double)lua_tonumber( L, -1 ) );
break;
case LUA_TFUNCTION: // TODO: Exercise this!
((jHashMapParam*)dict)->put( keyName, lua_tocfunction( L, -1 ) );
break;
case LUA_TTABLE:
{
Rtt::LuaLibSystem::FileType fileType;
int addedLuaEntriesCount = Rtt::LuaLibSystem::PathForTable( L, -1, fileType );
if (addedLuaEntriesCount > 0)
{
// The value is a Lua table referencing a file path.
// Fetch the file path and store it into a Java File object.
jobject javaByteArray = NULL;
const char *fileName = lua_tostring( L, -1 );
if (fileName)
{
jFile fileJavaObject( bridge->GetJNIEnv(), fileName );
if (fileJavaObject.isValid())
{
((jHashMapParam*)dict)->put( keyName, fileJavaObject.getValue() );
}
}
lua_pop( L, addedLuaEntriesCount );
}
else
{
// The value is a Lua table or array. Add it is as a new dictionary object to this dictionary entry.
jHashMapParam *hashMapPointer = (jHashMapParam*)DictionaryCreate( L, lua_gettop( L ), bridge );
((jHashMapParam*)dict)->put( keyName, hashMapPointer->getHashMapObject() );
}
break;
}
default:
break;
}
}
// Return the populated Java dictionary object.
return dict;
}
NativeToJavaBridge::DictionaryRef
NativeToJavaBridge::DictionaryCreate()
{
jHashMapParam *p = new jHashMapParam( GetJNIEnv() );
return p;
}
void
NativeToJavaBridge::DictionaryDestroy( DictionaryRef dict )
{
delete (jHashMapParam*)dict;
}
// TODO
/*
void
NativeToJavaBridge::DictionaryGet( DictionaryRef dict, const char *key, Rtt::String& result );
{
const char *result = NULL;
if ( dict && key && value )
{
jHashMapParam *p = (jHashMapParam*)dict;
jstring value = p->get( key );
if ( value )
{
jstringResult jstr( bridge.getEnv() );
jstr.setString( (jstring)value );
if ( jstr.isValidString() )
{
result.Set( jstr.getUTF8() );
}
}
}
return result;
}
*/
bool
NativeToJavaBridge::RequestSystem( lua_State *L, const char *actionName, int optionsIndex )
{
NativeTrace trace( "NativeToJavaBridge::RequestSystem" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
jboolean result = false;
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(),
"callRequestSystem", "(Lcom/ansca/corona/CoronaRuntime;JLjava/lang/String;I)Z");
if (mid != NULL)
{
jstringParam actionNameJ(bridge.getEnv(), actionName);
result = bridge.getEnv()->CallStaticBooleanMethod(
bridge.getClass(), mid, fCoronaRuntime, (jlong)(uintptr_t)L, actionNameJ.getValue(), optionsIndex);
HandleJavaExceptionUsing(L);
}
}
return (bool)result;
}
void
NativeToJavaBridge::Ping()
{
CallVoidMethod( "ping" );
}
int
NativeToJavaBridge::LoadFile( lua_State *L, const char *fileName )
{
NativeTrace trace( "NativeToJavaBridge::LoadFile" );
int result = 0;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callLoadFile", "(Lcom/ansca/corona/CoronaRuntime;JLjava/lang/String;)I");
if ( mid != NULL ) {
jstringParam fileNameJ( bridge.getEnv(), fileName );
if ( fileNameJ.isValid() ) {
result = bridge.getEnv()->CallStaticIntMethod(
bridge.getClass(), mid, fCoronaRuntime, (jlong)(uintptr_t)L, fileNameJ.getValue() );
HandleJavaExceptionUsing(L);
}
}
}
return result;
}
int
NativeToJavaBridge::LoadClass( lua_State *L, const char *libName, const char *className )
{
NativeTrace trace( "NativeToJavaBridge::LoadClass" );
int result = 0;
// 2 bigger than the length for the terminating null and the underscore if needed
char libraryName[strlen(libName)+2];
const char * hasNative = strstr(libName, ".native.");
if (hasNative) {
// Copy everything before native, hasNative is the position where it first finds .native, libName is where the char array starts
// add 1 for the dot before native
strncpy(libraryName, libName, hasNative - libName + 1);
// Add in an underscore
libraryName[(hasNative-libName) + 1] = '_';
// Copy everything after native
strncpy(libraryName + (hasNative - libName + 2), libName + (hasNative - libName + 1), strlen(libName) - (hasNative - libName));
} else {
strncpy(libraryName, libName, strlen(libName) + 1);
}
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callLoadClass", "(Lcom/ansca/corona/CoronaRuntime;JLjava/lang/String;Ljava/lang/String;)I");
if ( mid != NULL ) {
jstringParam libNameJ( bridge.getEnv(), libraryName );
jstringParam classNameJ( bridge.getEnv(), className );
if ( libNameJ.isValid() && classNameJ.isValid() ) {
result = bridge.getEnv()->CallStaticIntMethod(
bridge.getClass(), mid, fCoronaRuntime, (jlong)(uintptr_t)L, libNameJ.getValue(), classNameJ.getValue());
HandleJavaExceptionUsing(L);
}
}
}
return result;
}
void
NativeToJavaBridge::OnRuntimeLoaded(lua_State *L)
{
CallLongMethod("callOnRuntimeLoaded", (jlong)(uintptr_t)L);
}
void
NativeToJavaBridge::OnRuntimeWillLoadMain()
{
CallVoidMethod("callOnRuntimeWillLoadMain");
}
void
NativeToJavaBridge::OnRuntimeStarted()
{
CallVoidMethod("callOnRuntimeStarted");
}
void
NativeToJavaBridge::OnRuntimeSuspended()
{
CallVoidMethod("callOnRuntimeSuspended");
}
void
NativeToJavaBridge::OnRuntimeResumed()
{
CallVoidMethod("callOnRuntimeResumed");
}
void
NativeToJavaBridge::OnRuntimeExiting()
{
fRuntime = NULL;
}
int
NativeToJavaBridge::InvokeLuaErrorHandler(lua_State *L)
{
NativeTrace trace( "NativeToJavaBridge::InvokeLuaErrorHandler" );
// Flag that a Lua error has occurred.
// fHasLuaErrorOccurred = true;
// Invoke the Lua error handler.
int result = 0;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(), "callInvokeLuaErrorHandler", "(J)I");
if ( mid != NULL )
{
result = bridge.getEnv()->CallStaticIntMethod(bridge.getClass(), mid, (jlong)(uintptr_t)L);
}
}
return result;
}
void
NativeToJavaBridge::PushLaunchArgumentsToLuaTable(lua_State *L)
{
NativeTrace trace( "NativeToJavaBridge::PushLaunchArgumentsToLuaTable" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callPushLaunchArgumentsToLuaTable", "(Lcom/ansca/corona/CoronaRuntime;J)V");
if (mid != NULL)
{
bridge.getEnv()->CallStaticVoidMethod(bridge.getClass(), mid, fCoronaRuntime, (jlong)(uintptr_t)L);
}
}
}
void
NativeToJavaBridge::PushApplicationOpenArgumentsToLuaTable(lua_State *L)
{
NativeTrace trace( "NativeToJavaBridge::PushApplicationOpenArgumentsToLuaTable" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callPushApplicationOpenArgumentsToLuaTable", "(Lcom/ansca/corona/CoronaRuntime;J)V");
if (mid != NULL)
{
bridge.getEnv()->CallStaticVoidMethod(bridge.getClass(), mid, fCoronaRuntime, (jlong)(uintptr_t)L);
}
}
}
#if 0
enum JNI_JAVATYPE { JNI_UNKNOWN, JNI_BYTEARRAY, JNI_SHORTARRAY, JNI_INTARRAY, JNI_LONGARRAY };
JNI_JAVATYPE jni_type(JNIEnv *jni,jobject object)
{
// get java array classes
jclass jbyte_class = jni->FindClass("[B");
jclass jshort_class = jni->FindClass("[S");
jclass jint_class = jni->FindClass("[I");
jclass jlong_class = jni->FindClass("[J");
// return array type id
if (jni->IsInstanceOf(object,jbyte_class)) return JNI_BYTEARRAY;
if (jni->IsInstanceOf(object,jshort_class)) return JNI_SHORTARRAY;
if (jni->IsInstanceOf(object,jint_class)) return JNI_INTARRAY;
if (jni->IsInstanceOf(object,jlong_class)) return JNI_LONGARRAY;
// unknown type
return JNI_UNKNOWN;
}
#endif
bool
NativeToJavaBridge::GetRawAsset( const char * assetName, Rtt::Data<char> & data )
{
// Validate.
if (!assetName)
{
return false;
}
NativeTrace trace( "NativeToJavaBridge::GetRawAsset" );
bool result = false;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if (bridge.isValid())
{
// Fetch the package file the given asset is contained in and its compression information.
AndroidZipFileEntry zipFileEntry(data.Allocator());
bool wasAssetFileFound = GetAssetFileLocation(assetName, zipFileEntry);
if (wasAssetFileFound && (zipFileEntry.GetByteCountInPackage() > 0))
{
// The asset file was located. Fetch its bytes.
if (zipFileEntry.IsCompressed())
{
// Asset is compressed. Decompress it in Java.
NativeTrace trace( "NativeToJavaBridge::GetBytesFromFile" );
jstringParam assetNameJ(bridge.getEnv(), assetName);
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(),
"callGetBytesFromFile", "(Ljava/lang/String;)[B");
if (mid)
{
jobject jo = bridge.getEnv()->CallStaticObjectMethod(
bridge.getClass(), mid, assetNameJ.getValue());
// HandleJavaException();
if (jo)
{
jbyteArrayResult bytesJ( bridge.getEnv(), (jbyteArray) jo );
data.Set( (const char *) bytesJ.getValues(), bytesJ.getLength() );
bytesJ.release();
result = true;
bridge.getEnv()->DeleteLocalRef(jo);
}
}
}
else
{
// Asset is not compressed. Fetch its bytes from within the package file directly here.
int fileDescriptor = open(zipFileEntry.GetPackageFilePath(), O_RDONLY);
if (fileDescriptor >= 0)
{
data.SetLength(zipFileEntry.GetByteCountInPackage());
lseek(fileDescriptor, zipFileEntry.GetByteOffsetInPackage(), SEEK_SET);
ssize_t readResult = read(fileDescriptor, data.Get(), zipFileEntry.GetByteCountInPackage());
result = (readResult >= 0);
close(fileDescriptor);
}
}
}
}
return result;
}
bool
NativeToJavaBridge::GetRawAssetExists( const char * assetName )
{
NativeTrace trace( "NativeToJavaBridge::GetRawAssetExists");
bool result = false;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
trace.Trace();
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callGetRawAssetExists", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;)Z" );
if ( mid != NULL ) {
trace.Trace();
jstringParam assetNameJ( bridge.getEnv(), assetName );
if ( assetNameJ.isValid() ) {
result = (bool) bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime, assetNameJ.getValue() );
HandleJavaException();
// #ifdef Rtt_DEBUG
// __android_log_print(ANDROID_LOG_INFO, "Corona", "NativeToJavaBridge::GetRawAssetExists call returned %d", (int) result);
// #endif
}
}
}
return result;
}
bool
NativeToJavaBridge::GetCoronaResourceFileExists( const char * assetName )
{
NativeTrace trace( "NativeToJavaBridge::GetCoronaResourceFileExists");
bool result = false;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
trace.Trace();
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callGetCoronaResourceFileExists", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;)Z" );
if ( mid != NULL ) {
trace.Trace();
jstringParam assetNameJ( bridge.getEnv(), assetName );
if ( assetNameJ.isValid() ) {
result = (bool) bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime, assetNameJ.getValue() );
HandleJavaException();
}
}
}
return result;
}
bool
NativeToJavaBridge::GetAssetFileLocation(const char *assetName, AndroidZipFileEntry &zipFileEntry)
{
NativeTrace trace( "NativeToJavaBridge::GetAssetFileLocation");
bool wasAssetFound = false;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(),
"callGetAssetFileLocation", "(Ljava/lang/String;J)Z");
if (mid)
{
jstringParam assetNameJ(bridge.getEnv(), assetName);
jboolean result = bridge.getEnv()->CallStaticBooleanMethod(
bridge.getClass(), mid, assetNameJ.getValue(), (jlong)(uintptr_t)(&zipFileEntry));
// HandleJavaException();
wasAssetFound = result ? true : false;
}
}
return wasAssetFound;
}
void
NativeToJavaBridge::SetTimer( int milliseconds )
{
CallIntMethod( "callSetTimer", milliseconds );
HandleJavaException();
}
void
NativeToJavaBridge::CancelTimer()
{
CallVoidMethod( "callCancelTimer" );
HandleJavaException();
}
void
NativeToJavaBridge::CallStringMethod( const char * method, const char * param ) const
{
NativeTrace trace( method );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), method, "(Ljava/lang/String;)V" );
if ( mid != NULL )
{
jstringParam paramJ( bridge.getEnv(), param );
if ( paramJ.isValid() )
{
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, paramJ.getValue() );
}
}
}
}
void
NativeToJavaBridge::CallIntMethod( const char * method, int param ) const
{
NativeTrace trace( method );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), method, "(ILcom/ansca/corona/CoronaRuntime;)V" );
if ( mid != NULL )
{
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, (jint) param, fCoronaRuntime );
}
}
}
void
NativeToJavaBridge::CallLongMethod( const char * method, long param ) const
{
NativeTrace trace( method );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), method, "(JLcom/ansca/corona/CoronaRuntime;)V" );
if ( mid != NULL )
{
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, (jlong) param, fCoronaRuntime );
}
}
}
void
NativeToJavaBridge::CallDoubleMethod( const char * method, double param ) const
{
NativeTrace trace( method );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), method, "(DLcom/ansca/corona/CoronaRuntime;)V" );
if ( mid != NULL )
{
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, (jdouble) param, fCoronaRuntime );
}
}
}
void
NativeToJavaBridge::CallFloatMethod( const char * method, float param ) const
{
NativeTrace trace( method );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), method, "(FLcom/ansca/corona/CoronaRuntime;)V" );
if ( mid != NULL )
{
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, (jfloat) param, fCoronaRuntime );
}
}
}
void
NativeToJavaBridge::CallVoidMethod( const char * method ) const
{
// NativeTrace trace( method );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), method, "(Lcom/ansca/corona/CoronaRuntime;)V" );
if ( mid != NULL )
{
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime );
}
}
}
void
NativeToJavaBridge::GetSafeAreaInsetsPixels(Rtt::Real &top, Rtt::Real &left, Rtt::Real &bottom, Rtt::Real &right)
{
top = left = bottom = right = 0;
NativeTrace trace( "NativeToJavaBridge::GetSafeAreaInsetsPixels" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID methodId = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callGetSafeAreaInsetPixels", "(Lcom/ansca/corona/CoronaRuntime;)[F" );
if (methodId)
{
jobject objArray = bridge.getEnv()->CallStaticObjectMethod( bridge.getClass(), methodId, fCoronaRuntime );
jfloatArray * jfArray = reinterpret_cast< jfloatArray* >( & objArray );
if(objArray == NULL) return;
jsize len = bridge.getEnv()->GetArrayLength( *jfArray );
float* data = bridge.getEnv()->GetFloatArrayElements( *jfArray, 0 );
if ( len == 4 )
{
top = data [ 0 ];
left = data [ 1 ];
right = data [ 2 ];
bottom = data [ 3 ];
}
bridge.getEnv()->ReleaseFloatArrayElements( *jfArray, data, 0 );
bridge.getEnv()->DeleteLocalRef( *jfArray );
HandleJavaException();
}
}
}
bool
NativeToJavaBridge::LoadImage(
const char *filePath, AndroidImageData &imageData, bool convertToGrayscale,
int maxWidth, int maxHeight, bool loadImageInfoOnly)
{
NativeTrace trace( "NativeToJavaBridge::LoadImage" );
bool wasLoaded = false;
jclassInstance bridge(GetJNIEnv(), kNativeToJavaBridge);
if (bridge.isValid())
{
jmethodID methodId = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callLoadBitmap", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;JZIIZ)Z");
if (methodId)
{
jstringParam filePathJ(bridge.getEnv(), filePath);
if (filePathJ.isValid())
{
jboolean javaBooleanResult;
javaBooleanResult = bridge.getEnv()->CallStaticBooleanMethod(
bridge.getClass(), methodId, fCoronaRuntime, filePathJ.getValue(),
(jlong)(uintptr_t)(&imageData),
convertToGrayscale ? JNI_TRUE : JNI_FALSE,
maxWidth, maxHeight,
loadImageInfoOnly ? JNI_TRUE : JNI_FALSE);
HandleJavaException();
wasLoaded = javaBooleanResult ? true : false;
}
}
}
return wasLoaded;
}
bool
NativeToJavaBridge::CanOpenUrl( const char * url )
{
NativeTrace trace( "NativeToJavaBridge::CanOpenUrl" );
jclassInstance bridge(GetJNIEnv(), kNativeToJavaBridge);
jboolean result = false;
if (bridge.isValid() && url)
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callCanOpenUrl", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;)Z");
if (mid)
{
jstringParam urlJ(bridge.getEnv(), url);
result = bridge.getEnv()->CallStaticBooleanMethod(bridge.getClass(), mid, fCoronaRuntime, urlJ.getValue());
HandleJavaException();
}
}
return (bool)result;
}
bool
NativeToJavaBridge::OpenUrl( const char * url )
{
NativeTrace trace( "NativeToJavaBridge::OpenUrl" );
jclassInstance bridge(GetJNIEnv(), kNativeToJavaBridge);
jboolean result = false;
if (bridge.isValid() && url)
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callOpenUrl", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;)Z");
if (mid)
{
jstringParam urlJ(bridge.getEnv(), url);
result = bridge.getEnv()->CallStaticBooleanMethod(bridge.getClass(), mid, fCoronaRuntime, urlJ.getValue());
HandleJavaException();
}
}
return (bool)result;
}
void
NativeToJavaBridge::ShowNativeAlert( const char * title, const char * msg, const char ** labels, int numLabels, Rtt::LuaResource * resource )
{
NativeTrace trace( "NativeToJavaBridge::ShowNativeAlert" );
if ( !title || !msg )
{
return;
}
if ( !labels )
{
numLabels = 0;
}
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callShowNativeAlert", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V" );
if ( mid != NULL ) {
jstringParam titleJ( bridge.getEnv(), title );
jstringParam msgJ( bridge.getEnv(), msg );
jstringArrayParam labelsJ( bridge.getEnv(), numLabels );
if ( labelsJ.isValid() && titleJ.isValid() && msgJ.isValid() ) {
for ( int i = 0; i < numLabels; i++ ) {
labelsJ.setElement( i, labels[i] );
}
bridge.getEnv()->CallStaticVoidMethod(
bridge.getClass(), mid, fCoronaRuntime, titleJ.getValue(), msgJ.getValue(), labelsJ.getValue());
HandleJavaException();
fAlertCallbackResource = resource;
}
}
}
}
void
NativeToJavaBridge::CancelNativeAlert( int which )
{
CallIntMethod( "callCancelNativeAlert", which );
HandleJavaException();
}
void
NativeToJavaBridge::AlertCallback( int which , bool cancelled)
{
if ( fAlertCallbackResource != NULL ) {
Rtt::LuaLibNative::AlertComplete( *fAlertCallbackResource, which, cancelled );
Rtt_DELETE( fAlertCallbackResource );
fAlertCallbackResource = NULL;
}
}
bool
NativeToJavaBridge::CanShowPopup( const char *name )
{
NativeTrace trace( "NativeToJavaBridge::CanShowPopup" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
jboolean result = false;
if ( bridge.isValid() && name )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callCanShowPopup", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;)Z" );
if ( mid != NULL )
{
jstringParam nameJ( bridge.getEnv(), name );
result = bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime, nameJ.getValue() );
HandleJavaException();
}
}
return (bool)result;
}
void
NativeToJavaBridge::ShowSendMailPopup( NativeToJavaBridge::DictionaryRef dictionaryOfSettings, Rtt::LuaResource *resource )
{
NativeTrace trace( "NativeToJavaBridge::ShowSendMailPopup" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callShowSendMailPopup", "(Lcom/ansca/corona/CoronaRuntime;Ljava/util/HashMap;)V" );
if ( mid != NULL )
{
if (!fPopupClosedEventResource)
{
fPopupClosedEventResource = resource;
}
jobject hashMapObject = NULL;
if (dictionaryOfSettings)
{
hashMapObject = ((jHashMapParam*)dictionaryOfSettings)->getHashMapObject();
}
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, hashMapObject );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::ShowSendSmsPopup( NativeToJavaBridge::DictionaryRef dictionaryOfSettings, Rtt::LuaResource *resource )
{
NativeTrace trace( "NativeToJavaBridge::ShowSendSmsPopup" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callShowSendSmsPopup", "(Lcom/ansca/corona/CoronaRuntime;Ljava/util/HashMap;)V" );
if ( mid != NULL )
{
if (!fPopupClosedEventResource)
{
fPopupClosedEventResource = resource;
}
jobject hashMapObject = NULL;
if (dictionaryOfSettings)
{
hashMapObject = ((jHashMapParam*)dictionaryOfSettings)->getHashMapObject();
}
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, hashMapObject );
HandleJavaException();
}
}
}
bool
NativeToJavaBridge::ShowAppStorePopup( NativeToJavaBridge::DictionaryRef dictionaryOfSettings, Rtt::LuaResource *resource )
{
NativeTrace trace( "NativeToJavaBridge::ShowAppStorePopup" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
jboolean result = false;
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callShowAppStorePopup", "(Lcom/ansca/corona/CoronaRuntime;Ljava/util/HashMap;)Z" );
if ( mid != NULL )
{
if (!fPopupClosedEventResource)
{
fPopupClosedEventResource = resource;
}
jobject hashMapObject = NULL;
if (dictionaryOfSettings)
{
hashMapObject = ((jHashMapParam*)dictionaryOfSettings)->getHashMapObject();
}
result = bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime, hashMapObject );
HandleJavaException();
}
}
return (bool)result;
}
void
NativeToJavaBridge::ShowRequestPermissionsPopup( NativeToJavaBridge::DictionaryRef dictionaryOfSettings, Rtt::LuaResource *resource )
{
NativeTrace trace( "NativeToJavaBridge::ShowRequestPermissionsPopup" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callShowRequestPermissionsPopup", "(Lcom/ansca/corona/CoronaRuntime;Ljava/util/HashMap;)V" );
if ( mid != NULL )
{
if (!fPopupClosedEventResource)
{
fPopupClosedEventResource = resource;
}
jobject hashMapObject = NULL;
if (dictionaryOfSettings)
{
hashMapObject = ((jHashMapParam*)dictionaryOfSettings)->getHashMapObject();
}
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, hashMapObject );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::RaisePopupClosedEvent( const char *popupName, bool wasCanceled )
{
if (fPopupClosedEventResource)
{
Rtt::LuaLibNative::PopupClosed(*fPopupClosedEventResource, popupName, wasCanceled);
Rtt_DELETE( fPopupClosedEventResource );
fPopupClosedEventResource = NULL;
}
}
void
NativeToJavaBridge::DisplayUpdate()
{
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayUpdate", "(Lcom/ansca/corona/CoronaRuntime;)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::GetString( const char *method, Rtt::String *outValue )
{
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
NativeTrace trace( method );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
method, "(Lcom/ansca/corona/CoronaRuntime;)Ljava/lang/String;" );
if ( mid != NULL ) {
jobject jo = bridge.getEnv()->CallStaticObjectMethod( bridge.getClass(), mid, fCoronaRuntime );
HandleJavaException();
if (jo)
{
jstringResult jstr( bridge.getEnv() );
jstr.setString( (jstring) jo );
if ( jstr.isValidString() )
{
outValue->Set( jstr.getUTF8() );
}
}
}
}
}
void
NativeToJavaBridge::GetStringWithInt( const char *method, int intParameter, Rtt::String *outValue )
{
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
NativeTrace trace( method );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
method, "(ILcom/ansca/corona/CoronaRuntime;)Ljava/lang/String;" );
if ( mid != NULL ) {
jobject jo = bridge.getEnv()->CallStaticObjectMethod( bridge.getClass(), mid, intParameter, fCoronaRuntime );
HandleJavaException();
if (jo)
{
jstringResult jstr( bridge.getEnv() );
jstr.setString( (jstring) jo );
if ( jstr.isValidString() )
{
outValue->Set( jstr.getUTF8() );
}
}
}
}
}
void
NativeToJavaBridge::GetStringWithLong( const char *method, long longParameter, Rtt::String *outValue )
{
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
NativeTrace trace( method );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
method, "(JLcom/ansca/corona/CoronaRuntime;)Ljava/lang/String;" );
if ( mid != NULL ) {
jobject jo = bridge.getEnv()->CallStaticObjectMethod( bridge.getClass(), mid, (jlong)longParameter, fCoronaRuntime );
HandleJavaException();
if (jo)
{
jstringResult jstr( bridge.getEnv() );
jstr.setString( (jstring) jo );
if ( jstr.isValidString() )
{
outValue->Set( jstr.getUTF8() );
}
}
}
}
}
void
NativeToJavaBridge::GetManufacturerName( Rtt::String *outValue )
{
GetString( "callGetManufacturerName", outValue );
HandleJavaException();
}
void
NativeToJavaBridge::GetModel( Rtt::String *outValue )
{
GetString( "callGetModel", outValue );
HandleJavaException();
}
void
NativeToJavaBridge::GetName( Rtt::String *outValue )
{
GetString( "callGetName", outValue );
HandleJavaException();
}
void
NativeToJavaBridge::GetUniqueIdentifier( int t, Rtt::String *outValue )
{
GetStringWithInt( "callGetUniqueIdentifier", t, outValue );
HandleJavaException();
}
void
NativeToJavaBridge::GetPlatformVersion( Rtt::String *outValue )
{
GetString( "callGetPlatformVersion", outValue );
HandleJavaException();
}
void
NativeToJavaBridge::GetProductName( Rtt::String *outValue )
{
GetString( "callGetProductName", outValue );
HandleJavaException();
}
int
NativeToJavaBridge::GetApproximateScreenDpi()
{
NativeTrace trace( "NativeToJavaBridge::GetApproximateScreenDpi" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
int result = 0;
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(),
"callGetApproximateScreenDpi", "()I" );
if (mid != NULL)
{
result = (int)bridge.getEnv()->CallStaticIntMethod(bridge.getClass(), mid);
HandleJavaException();
}
}
return result;
}
int
NativeToJavaBridge::PushSystemInfoToLua( lua_State *L, const char *key )
{
NativeTrace trace( "NativeToJavaBridge::PushSystemInfoToLua" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
int result = 0;
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(),
"callPushSystemInfoToLua", "(Lcom/ansca/corona/CoronaRuntime;JLjava/lang/String;)I" );
if (mid != NULL)
{
jstringParam keyJ(bridge.getEnv(), key);
result = (int)bridge.getEnv()->CallStaticIntMethod(
bridge.getClass(), mid, fCoronaRuntime, (jlong)(uintptr_t)L, keyJ.getValue());
HandleJavaExceptionUsing(L);
}
}
return result;
}
void
NativeToJavaBridge::GetPreference( int category, Rtt::String *outValue )
{
GetStringWithInt( "callGetPreference", category, outValue );
HandleJavaException();
}
Rtt::Preference::ReadValueResult
NativeToJavaBridge::GetPreference( const char* keyName )
{
// Fetch a reference to this feature's Java method.
jmethodID getPreferenceMethodId = NULL;
jclassInstance bridge(GetJNIEnv(), kNativeToJavaBridge);
if (bridge.isValid())
{
getPreferenceMethodId = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callGetPreference", "(Ljava/lang/String;)Ljava/lang/Object;" );
}
if (!getPreferenceMethodId)
{
return Rtt::Preference::ReadValueResult::FailedWith("JNI bridge failure.");
}
// Attempt to read the given preference key.
jstringParam javaKeyName(bridge.getEnv(), keyName);
jobject javaObjectResult = bridge.getEnv()->CallStaticObjectMethod(
bridge.getClass(), getPreferenceMethodId, javaKeyName.getValue());
HandleJavaException();
// If the Java method returned null, then the preference was not found.
if (!javaObjectResult)
{
return Rtt::Preference::ReadValueResult::kPreferenceNotFound;
}
// An object was returned.
// Use reflection to determine if we've received a valid preference value type.
{
// Is it a string?
jclassInstance javaValueType(GetJNIEnv(), "java/lang/String");
if (GetJNIEnv()->IsInstanceOf(javaObjectResult, javaValueType.getClass()))
{
jstringResult javaStringValue(bridge.getEnv());
javaStringValue.setString((jstring)javaObjectResult);
if (javaStringValue.isValidString())
{
return Rtt::Preference::ReadValueResult::SucceededWith(javaStringValue.getUTF8());
}
return Rtt::Preference::ReadValueResult::SucceededWith("");
}
}
{
// Is it a boolean?
jclassInstance javaValueType(GetJNIEnv(), "java/lang/Boolean");
if (GetJNIEnv()->IsInstanceOf(javaObjectResult, javaValueType.getClass()))
{
jmethodID methodId = javaValueType.getEnv()->GetMethodID(
javaValueType.getClass(), "booleanValue", "()Z");
if (!methodId)
{
return Rtt::Preference::ReadValueResult::FailedWith("Failed to extract value from Java 'Boolean' object.");
}
bool value = javaValueType.getEnv()->CallBooleanMethod(javaObjectResult, methodId) ? true : false;
HandleJavaException();
return Rtt::Preference::ReadValueResult::SucceededWith(value);
}
}
{
// Is it a 32-bit signed integer?
jclassInstance javaValueType(GetJNIEnv(), "java/lang/Integer");
if (GetJNIEnv()->IsInstanceOf(javaObjectResult, javaValueType.getClass()))
{
jmethodID methodId = javaValueType.getEnv()->GetMethodID(
javaValueType.getClass(), "intValue", "()I");
if (!methodId)
{
return Rtt::Preference::ReadValueResult::FailedWith("Failed to extract value from Java 'Integer' object.");
}
int value = (int)javaValueType.getEnv()->CallIntMethod(javaObjectResult, methodId);
HandleJavaException();
return Rtt::Preference::ReadValueResult::SucceededWith(value);
}
}
{
// Is it a 64-bit signed integer?
jclassInstance javaValueType(GetJNIEnv(), "java/lang/Long");
if (GetJNIEnv()->IsInstanceOf(javaObjectResult, javaValueType.getClass()))
{
jmethodID methodId = javaValueType.getEnv()->GetMethodID(
javaValueType.getClass(), "longValue", "()J");
if (!methodId)
{
return Rtt::Preference::ReadValueResult::FailedWith("Failed to extract value from Java 'Long' object.");
}
S64 value = (S64)javaValueType.getEnv()->CallLongMethod(javaObjectResult, methodId);
HandleJavaException();
return Rtt::Preference::ReadValueResult::SucceededWith(value);
}
}
{
// Is it a single precision float?
jclassInstance javaValueType(GetJNIEnv(), "java/lang/Float");
if (GetJNIEnv()->IsInstanceOf(javaObjectResult, javaValueType.getClass()))
{
jmethodID methodId = javaValueType.getEnv()->GetMethodID(
javaValueType.getClass(), "longValue", "()F");
if (!methodId)
{
return Rtt::Preference::ReadValueResult::FailedWith("Failed to extract value from Java 'Float' object.");
}
float value = (float)javaValueType.getEnv()->CallFloatMethod(javaObjectResult, methodId);
HandleJavaException();
return Rtt::Preference::ReadValueResult::SucceededWith(value);
}
}
// If a Java exception object was returned, then an error occurred.
// Return a failure result to the caller using the exception object's message.
{
jclassInstance javaThrowableType(GetJNIEnv(), "java/lang/Throwable");
if (GetJNIEnv()->IsInstanceOf(javaObjectResult, javaThrowableType.getClass()))
{
jmethodID methodId = javaThrowableType.getEnv()->GetMethodID(
javaThrowableType.getClass(), "getMessage", "()Ljava/lang/String;");
if (!methodId)
{
return Rtt::Preference::ReadValueResult::FailedWith("Failed to fetch message from Java 'Exception' object.");
}
javaObjectResult = javaThrowableType.getEnv()->CallObjectMethod(javaObjectResult, methodId);
HandleJavaException();
jstringResult javaExceptionMessage(bridge.getEnv());
if (javaObjectResult)
{
javaExceptionMessage.setString((jstring)javaObjectResult);
}
if (javaExceptionMessage.isValidString())
{
return Rtt::Preference::ReadValueResult::FailedWith(javaExceptionMessage.getUTF8());
}
else
{
return Rtt::Preference::ReadValueResult::FailedWith("Unknown Java exception error occurred.");
}
}
}
// An unknown Java object type was returned. Return a failure result.
return Rtt::Preference::ReadValueResult::FailedWith("Received unknown/unsupported Java value type.");
}
Rtt::OperationResult
NativeToJavaBridge::SetPreferences( const Rtt::PreferenceCollection& collection )
{
// Fetch a reference to this feature's Java method.
jmethodID setPreferencesMethodId = NULL;
jclassInstance bridge(GetJNIEnv(), kNativeToJavaBridge);
if (bridge.isValid())
{
setPreferencesMethodId = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callSetPreferences", "(Ljava/util/HashMap;)Ljava/lang/String;" );
}
if (!setPreferencesMethodId)
{
return Rtt::OperationResult::FailedWith("JNI bridge failure.");
}
// Set up a collection of all value types supported by Android's SharedPreferences feature.
Rtt::PreferenceValue::TypeSet supportedTypes;
supportedTypes.Add(Rtt::PreferenceValue::kTypeBoolean);
supportedTypes.Add(Rtt::PreferenceValue::kTypeSignedInt32);
supportedTypes.Add(Rtt::PreferenceValue::kTypeSignedInt64);
supportedTypes.Add(Rtt::PreferenceValue::kTypeFloatSingle);
supportedTypes.Add(Rtt::PreferenceValue::kTypeString);
// Copy the given native preference key-value pairs to a Java HashMap collection.
jHashMapParam hashMap(GetJNIEnv());
for (int index = 0; index < collection.GetCount(); index++)
{
// Fetch the next preference in the native collection.
Rtt::Preference* preferencePointer = collection.GetByIndex(index);
if (!preferencePointer || !preferencePointer->GetKeyName())
{
continue;
}
// Attempt to convert the given preference value to a type supported by Android's SharedPreferences feature.
Rtt::PreferenceValue preferenceValue = preferencePointer->GetValue();
Rtt::ValueResult<Rtt::PreferenceValue> conversionResult = preferenceValue.ToClosestValueTypeIn(supportedTypes);
if (conversionResult.HasFailed())
{
return Rtt::OperationResult::FailedWith(conversionResult.GetUtf8MessageAsSharedPointer());
}
preferenceValue = conversionResult.GetValue();
// Add the native preference key-value pair to the Java HashMap.
switch (preferenceValue.GetType())
{
case Rtt::PreferenceValue::kTypeBoolean:
hashMap.put(preferencePointer->GetKeyName(), preferenceValue.ToBoolean().GetValue());
break;
case Rtt::PreferenceValue::kTypeSignedInt32:
hashMap.put(preferencePointer->GetKeyName(), preferenceValue.ToSignedInt32().GetValue());
break;
case Rtt::PreferenceValue::kTypeSignedInt64:
hashMap.put(preferencePointer->GetKeyName(), preferenceValue.ToSignedInt64().GetValue());
break;
case Rtt::PreferenceValue::kTypeFloatSingle:
hashMap.put(preferencePointer->GetKeyName(), preferenceValue.ToFloatSingle().GetValue());
break;
case Rtt::PreferenceValue::kTypeString:
default:
hashMap.put(preferencePointer->GetKeyName(), preferenceValue.ToString().GetValue()->c_str());
break;
}
}
// Write the given preferences to Android's SharedPreferences feature.
jobject javaObjectResult = bridge.getEnv()->CallStaticObjectMethod(
bridge.getClass(), setPreferencesMethodId, hashMap.getHashMapObject());
HandleJavaException();
// If a string object was returned, then an error occurred.
// The returned string provides the error message.
if (javaObjectResult)
{
jstringResult javaStringValue(bridge.getEnv());
javaStringValue.setString((jstring)javaObjectResult);
if (javaStringValue.isValidString())
{
return Rtt::OperationResult::FailedWith(javaStringValue.getUTF8());
}
return Rtt::OperationResult::FailedWith("Unknown error occurred.");
}
// Java returned null. This means the operation was a success!
return Rtt::OperationResult::kSucceeded;
}
Rtt::OperationResult
NativeToJavaBridge::DeletePreferences( const char** keyNameArray, size_t keyNameCount )
{
// Validate arguments.
if (!keyNameArray || (keyNameCount <= 0))
{
return Rtt::OperationResult::FailedWith("Key name array is null or empty.");
}
// Fetch a reference to this feature's Java method.
jmethodID methodId = NULL;
jclassInstance bridge(GetJNIEnv(), kNativeToJavaBridge);
if (bridge.isValid())
{
methodId = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callDeletePreferences", "([Ljava/lang/String;)Ljava/lang/String;" );
}
if (!methodId)
{
return Rtt::OperationResult::FailedWith("JNI bridge failure.");
}
// Copy the given native strings to a Java string array.
jstringArrayParam javaStringArray(bridge.getEnv(), keyNameCount);
for (size_t index = 0; index < keyNameCount; index++)
{
javaStringArray.setElement((int)index, keyNameArray[index]);
}
// Attempt to delete the given keys from Android's SharedPreferences.
jobject javaObjectResult = bridge.getEnv()->CallStaticObjectMethod(
bridge.getClass(), methodId, javaStringArray.getValue());
HandleJavaException();
// If a string object was returned, then an error occurred.
// The returned string provides the error message.
if (javaObjectResult)
{
jstringResult javaStringValue(bridge.getEnv());
javaStringValue.setString((jstring)javaObjectResult);
if (javaStringValue.isValidString())
{
return Rtt::OperationResult::FailedWith(javaStringValue.getUTF8());
}
return Rtt::OperationResult::FailedWith("Unknown error occurred.");
}
// Java returned null. This means the operation was a success!
return Rtt::OperationResult::kSucceeded;
}
void
NativeToJavaBridge::GetSystemProperty( const char *name, Rtt::String *outValue )
{
// Validate arguments.
if (!name || !outValue)
{
return;
}
// Fetch the requested property from the Java "System" class.
jclassInstance bridge(GetJNIEnv(), "java/lang/System");
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "getProperty", "(Ljava/lang/String;)Ljava/lang/String;" );
if (mid != NULL) {
jstringParam nameJ(bridge.getEnv(), name);
jobject jo = bridge.getEnv()->CallStaticObjectMethod(bridge.getClass(), mid, nameJ.getValue());
HandleJavaException();
if (jo)
{
jstringResult jstr(bridge.getEnv());
jstr.setString((jstring)jo);
if (jstr.isValidString())
{
outValue->Set(jstr.getUTF8());
}
}
}
}
}
long
NativeToJavaBridge::GetUptimeInMilliseconds()
{
// Call the SystemClock.uptimeMillis() static method in Java.
long result = 0;
jclassInstance bridge(GetJNIEnv(), "android/os/SystemClock");
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(), "uptimeMillis", "()J");
if (mid != NULL)
{
result = (long)bridge.getEnv()->CallStaticLongMethod(bridge.getClass(), mid);
HandleJavaException();
}
}
return result;
}
void
NativeToJavaBridge::MakeLowerCase(Rtt::String *stringToConvert)
{
// Validate.
if (!stringToConvert || stringToConvert->IsEmpty())
{
return;
}
// Convert the given string to lower case via the String.toLowerCase() Java method.
// The reason we do this is because Java strings will correctly convert unicode strings.
jclassInstance bridge(GetJNIEnv(), "java/lang/String");
if (bridge.isValid())
{
jmethodID methodId = bridge.getEnv()->GetMethodID(
bridge.getClass(), "toLowerCase", "()Ljava/lang/String;");
if (methodId)
{
jstringParam javaString(bridge.getEnv(), stringToConvert->GetString());
jobject resultObject = bridge.getEnv()->CallObjectMethod(javaString.getObject(), methodId);
if (resultObject)
{
jstringResult lowerCaseJavaString(bridge.getEnv());
lowerCaseJavaString.setString((jstring)resultObject);
if (lowerCaseJavaString.isValidString())
{
stringToConvert->Set(lowerCaseJavaString.getUTF8());
}
}
}
}
}
void
NativeToJavaBridge::Vibrate(const char * hapticType, const char* hapticStyle)
{
HandleJavaException();
NativeTrace trace( "NativeToJavaBridge::Vibrate" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callVibrate", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;Ljava/lang/String;)V" );
if ( mid != NULL ) {
jstringParam hapticTypeJ( bridge.getEnv(), hapticType );
jstringParam hapticStyleJ( bridge.getEnv(), hapticStyle );
bridge.getEnv()->CallStaticVoidMethod(
bridge.getClass(), mid, fCoronaRuntime, hapticTypeJ.getValue(), hapticStyleJ.getValue());
HandleJavaException();
}
}
}
void
NativeToJavaBridge::SetAccelerometerInterval( int frequency )
{
CallIntMethod( "callSetAccelerometerInterval", frequency );
HandleJavaException();
}
void
NativeToJavaBridge::SetGyroscopeInterval( int frequency )
{
CallIntMethod( "callSetGyroscopeInterval", frequency );
HandleJavaException();
}
bool
NativeToJavaBridge::HasAccelerometer()
{
NativeTrace trace( "NativeToJavaBridge::HasAccelerometer" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
jboolean result = true;
if ( bridge.isValid() )
{
jmethodID mid;
mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), "callHasAccelerometer", "(Lcom/ansca/corona/CoronaRuntime;)Z" );
if ( mid != NULL )
{
result = bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime );
HandleJavaException();
}
}
return result;
}
bool
NativeToJavaBridge::HasGyroscope()
{
NativeTrace trace( "NativeToJavaBridge::HasGyroscope" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
jboolean result = true;
if ( bridge.isValid() )
{
jmethodID mid;
mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), "callHasGyroscope", "(Lcom/ansca/corona/CoronaRuntime;)Z" );
if ( mid != NULL )
{
result = bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime );
HandleJavaException();
}
}
return result;
}
void
NativeToJavaBridge::SetEventNotification( int eventType, bool enable )
{
NativeTrace trace( "NativeToJavaBridge::SetEventNotification" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callSetEventNotification",
"(Lcom/ansca/corona/CoronaRuntime;IZ)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, (jint) eventType, (jboolean) enable );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::DisplayObjectDestroy( int id )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectDestroy" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callDisplayObjectDestroy", "(Lcom/ansca/corona/CoronaRuntime;I)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, id );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::DisplayObjectSetVisible( int id, bool visible )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectSetVisible" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectSetVisible", "(Lcom/ansca/corona/CoronaRuntime;IZ)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, id, visible );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::DisplayObjectSetAlpha( int id, float alpha )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectSetAlpha" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectSetAlpha", "(Lcom/ansca/corona/CoronaRuntime;IF)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, id, alpha );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::DisplayObjectSetBackground( int id, bool bg )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectSetBackground" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectSetBackground", "(Lcom/ansca/corona/CoronaRuntime;IZ)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, id, bg );
HandleJavaException();
}
}
}
bool
NativeToJavaBridge::DisplayObjectGetVisible( int id )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectGetVisible" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectGetVisible", "(Lcom/ansca/corona/CoronaRuntime;I)Z" );
if ( mid != NULL ) {
jboolean result = bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime, id );
HandleJavaException();
return result;
}
}
return false;
}
float
NativeToJavaBridge::DisplayObjectGetAlpha( int id )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectGetAlpha" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectGetAlpha", "(Lcom/ansca/corona/CoronaRuntime;I)F" );
if ( mid != NULL ) {
jfloat result = bridge.getEnv()->CallStaticFloatMethod( bridge.getClass(), mid, fCoronaRuntime, id );
HandleJavaException();
return result;
}
}
return 0;
}
bool
NativeToJavaBridge::DisplayObjectGetBackground( int id )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectGetBackground" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
jboolean result = false;
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectGetBackground", "(Lcom/ansca/corona/CoronaRuntime;I)Z" );
if ( mid != NULL ) {
result = bridge.getEnv()->CallStaticBooleanMethod( bridge.getClass(), mid, fCoronaRuntime, id );
HandleJavaException();
}
}
return result;
}
void
NativeToJavaBridge::DisplayObjectSetFocus( int id, bool focus )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectSetFocus" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectSetFocus", "(Lcom/ansca/corona/CoronaRuntime;IZ)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, id, focus );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::DisplayObjectUpdateScreenBounds( int id, int x, int y, int width, int height )
{
NativeTrace trace( "NativeToJavaBridge::DisplayObjectUpdateScreenBounds" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callDisplayObjectUpdateScreenBounds", "(Lcom/ansca/corona/CoronaRuntime;IIIII)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, id, x, y, width, height );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::SaveBitmap( const Rtt::PlatformBitmap * bitmap, Rtt::Data<const char> & pngBytes )
{
NativeTrace trace( "NativeToJavaBridge::SaveBitmap" );
#ifdef Rtt_DEBUG
if ( bitmap == NULL || bitmap->GetBits( NULL ) == NULL )
{
__android_log_print(ANDROID_LOG_INFO, "Corona", "= NativeToJavaBridge::SaveBitmap NULL");
return false;
}
#endif
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid;
mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(), "callSaveBitmap", "(Lcom/ansca/corona/CoronaRuntime;[III)[B" );
if ( mid != NULL )
{
int width = bitmap->Width();
int height = bitmap->Height();
jintArrayParam array( bridge.getEnv(), width * height);
if ( array.isValid() )
{
if ( width > 0 )
{
array.setArray( (const int *) bitmap->GetBits( NULL ), 0, width * height );
}
}
jobject jo = bridge.getEnv()->CallStaticObjectMethod(bridge.getClass(), mid, fCoronaRuntime, array.getValue(), width, height);
jbyteArrayResult bytesJ( bridge.getEnv(), (jbyteArray) jo );
pngBytes.Set( (const char *) bytesJ.getValues(), bytesJ.getLength() );
bytesJ.release();
bridge.getEnv()->DeleteLocalRef(jo);
HandleJavaException();
}
}
}
void
NativeToJavaBridge::WebViewCreate(
int id, int left, int top, int width, int height, bool isPopup, bool autoCancelEnabled)
{
NativeTrace trace( "NativeToJavaBridge::WebViewCreate" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() ) {
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callWebViewCreate", "(Lcom/ansca/corona/CoronaRuntime;IIIIIZZ)V" );
if ( mid != NULL ) {
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid,
fCoronaRuntime, id, left, top, width, height, (jboolean)isPopup, (jboolean)autoCancelEnabled );
HandleJavaException();
}
}
}
void
NativeToJavaBridge::WebViewRequestLoadUrl( int id, const char * url )
{
NativeTrace trace( "NativeToJavaBridge::WebViewRequestLoadUrl" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callWebViewRequestLoadUrl", "(Lcom/ansca/corona/CoronaRuntime;ILjava/lang/String;)V" );
if ( mid != NULL )
{
jstringParam textJ( bridge.getEnv(), url );
if ( textJ.isValid() )
{
bridge.getEnv()->CallStaticVoidMethod( bridge.getClass(), mid, fCoronaRuntime, id, textJ.getValue() );
HandleJavaException();
}
}
}
}
void
NativeToJavaBridge::WebViewRequestReload( int id )
{
NativeTrace trace( "NativeToJavaBridge::WebViewRequestReload" );
CallIntMethod( "callWebViewRequestReload", id );
HandleJavaException();
}
void
NativeToJavaBridge::WebViewRequestStop( int id )
{
NativeTrace trace( "NativeToJavaBridge::WebViewRequestStop" );
CallIntMethod( "callWebViewRequestStop", id );
HandleJavaException();
}
void
NativeToJavaBridge::WebViewRequestGoBack( int id )
{
NativeTrace trace( "NativeToJavaBridge::WebViewRequestGoBack" );
CallIntMethod( "callWebViewRequestGoBack", id );
HandleJavaException();
}
void
NativeToJavaBridge::WebViewRequestGoForward( int id )
{
NativeTrace trace( "NativeToJavaBridge::WebViewRequestGoForward" );
CallIntMethod( "callWebViewRequestGoForward", id );
HandleJavaException();
}
void
NativeToJavaBridge::WebViewRequestDeleteCookies( int id )
{
NativeTrace trace( "NativeToJavaBridge::WebViewRequestDeleteCookies" );
CallIntMethod( "callWebViewRequestDeleteCookies", id );
HandleJavaException();
}
int
NativeToJavaBridge::CryptoGetDigestLength( const char * algorithm )
{
NativeTrace trace( "NativeToJavaBridge::CryptoGetDigestLength" );
int result = 0;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callCryptoGetDigestLength", "(Ljava/lang/String;)I" );
if ( mid != NULL )
{
jstringParam algorithmJ( bridge.getEnv(), algorithm );
if ( algorithmJ.isValid() )
{
result = bridge.getEnv()->CallStaticIntMethod( bridge.getClass(), mid, algorithmJ.getValue() );
HandleJavaException();
}
}
}
return result;
}
void
NativeToJavaBridge::CryptoCalculateDigest( const char * algorithm, const Rtt::Data<const char> & data, U8 * digest )
{
NativeTrace trace( "NativeToJavaBridge::CryptoCalculateDigest" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callCryptoCalculateDigest", "(Ljava/lang/String;[B)[B" );
if ( mid != NULL )
{
jstringParam algorithmJ( bridge.getEnv(), algorithm );
jbyteArrayParam dataJ( bridge.getEnv(), data.GetLength() );
dataJ.setArray( data.Get(), 0, data.GetLength() );
jobject jo = bridge.getEnv()->CallStaticObjectMethod(
bridge.getClass(), mid, algorithmJ.getValue(), dataJ.getValue() );
HandleJavaException();
if (jo)
{
jbyteArrayResult jbytes( bridge.getEnv(), (jbyteArray) jo );
memcpy( digest, (const char *) jbytes.getValues(), jbytes.getLength() );
jbytes.release();
bridge.getEnv()->DeleteLocalRef(jo);
}
}
}
}
void
NativeToJavaBridge::CryptoCalculateHMAC( const char * algorithm, const Rtt::Data<const char> & key, const Rtt::Data<const char> & data,
U8 * digest )
{
NativeTrace trace( "NativeToJavaBridge::CryptoCalculateHMAC" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callCryptoCalculateHMAC", "(Ljava/lang/String;[B[B)[B" );
if ( mid != NULL )
{
jstringParam algorithmJ( bridge.getEnv(), algorithm );
jbyteArrayParam keyJ( bridge.getEnv(), key.GetLength() );
keyJ.setArray( key.Get(), 0, key.GetLength() );
jbyteArrayParam dataJ( bridge.getEnv(), data.GetLength() );
dataJ.setArray( data.Get(), 0, data.GetLength() );
jobject jo = bridge.getEnv()->CallStaticObjectMethod(
bridge.getClass(), mid, algorithmJ.getValue(), keyJ.getValue(), dataJ.getValue() );
HandleJavaException();
if (jo)
{
jbyteArrayResult jbytes( bridge.getEnv(), (jbyteArray) jo );
memcpy( digest, (const char *) jbytes.getValues(), jbytes.getLength() );
jbytes.release();
bridge.getEnv()->DeleteLocalRef(jo);
}
}
}
}
bool
NativeToJavaBridge::WebPopupShouldLoadUrl( int id, const char * url )
{
Rtt::PlatformWebPopup * owner = (Rtt::PlatformWebPopup *) id;
bool result = owner->ShouldLoadUrl( url );
return result;
}
bool
NativeToJavaBridge::WebPopupDidFailLoadUrl( int id, const char * url, const char * msg, int code )
{
Rtt::PlatformWebPopup * owner = (Rtt::PlatformWebPopup *) id;
bool result = owner->DidFailLoadUrl( url, msg, code );
return result;
}
void
NativeToJavaBridge::ExternalizeResource( const char * assetName, Rtt::String * result )
{
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
NativeTrace trace( "NativeToJavaBridge::ExternalizeResource" );
if ( bridge.isValid() )
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID( bridge.getClass(),
"callExternalizeResource", "(Ljava/lang/String;Lcom/ansca/corona/CoronaRuntime;)Ljava/lang/String;" );
jstringParam assetNameJ( bridge.getEnv(), assetName );
if ( mid != NULL && assetNameJ.isValid() )
{
jobject jo = bridge.getEnv()->CallStaticObjectMethod( bridge.getClass(), mid, assetNameJ.getValue(), fCoronaRuntime );
HandleJavaException();
if ( jo )
{
jstringResult jstr( bridge.getEnv() );
jstr.setString( (jstring) jo );
if ( jstr.isValidString() )
{
result->Set( jstr.getUTF8() );
}
}
}
}
}
void
NativeToJavaBridge::GetAvailableStoreNames( Rtt::PtrArray<Rtt::String> &storeNames )
{
NativeTrace trace( "NativeToJavaBridge::GetAvailableStoreNames" );
// Fetch store names from the Java side of Corona.
bool didReceiveStrings = false;
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callGetAvailableStoreNames", "()[Ljava/lang/String;");
jobject resultArray = bridge.getEnv()->CallStaticObjectMethod(bridge.getClass(), mid);
HandleJavaException();
if (resultArray)
{
jstringArrayResult jstrings(bridge.getEnv(), (jobjectArray)resultArray);
jsize arraySize = jstrings.getLength();
if (arraySize > 0)
{
// Copy the received Java strings to the given string array.
// String objects allocated here will be automatically deleted by the given array.
storeNames.Reserve(arraySize);
jstringResult javaString(bridge.getEnv());
for (int index = 0; index < arraySize; index++)
{
javaString.setString(jstrings.getString(index));
storeNames.Append(new Rtt::String(storeNames.Allocator(), javaString.getUTF8()));
}
didReceiveStrings = true;
}
bridge.getEnv()->DeleteLocalRef(resultArray);
}
}
// If strings were not received, then clear the given array.
// Doing this last is an optimization. No sense in deleting the array's memory if we don't have to.
if (!didReceiveStrings)
{
storeNames.Empty();
}
}
void
NativeToJavaBridge::GetTargetedStoreName( Rtt::String *outValue )
{
GetString( "callGetTargetedStoreName", outValue );
HandleJavaException();
}
int
NativeToJavaBridge::NotificationSchedule( lua_State *L, int index )
{
NativeTrace trace( "NativeToJavaBridge::NotificationSchedule" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
int notificationId = -1;
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callNotificationSchedule", "(Lcom/ansca/corona/CoronaRuntime;JI)J");
if (mid)
{
notificationId = (int)bridge.getEnv()->CallStaticIntMethod(
bridge.getClass(), mid, fCoronaRuntime, (jlong)(uintptr_t)L, index);
HandleJavaExceptionUsing(L);
}
}
return notificationId;
}
void
NativeToJavaBridge::NotificationCancel( int id )
{
NativeTrace trace( "NativeToJavaBridge::NotificationCancel" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(), "callNotificationCancel", "(I)V");
if (mid)
{
bridge.getEnv()->CallStaticVoidMethod(bridge.getClass(), mid, id);
HandleJavaException();
}
}
}
void
NativeToJavaBridge::NotificationCancelAll()
{
NativeTrace trace( "NativeToJavaBridge::NotificationCancelAll" );
CallVoidMethod( "callNotificationCancelAll" );
HandleJavaException();
}
void
NativeToJavaBridge::GooglePushNotificationsRegister( const char *projectNumber )
{
NativeTrace trace( "NativeToJavaBridge::GooglePushNotificationsRegister" );
jclassInstance bridge( GetJNIEnv(), kNativeToJavaBridge );
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(
bridge.getClass(), "callGooglePushNotificationsRegister", "(Lcom/ansca/corona/CoronaRuntime;Ljava/lang/String;)V");
jstringParam projectNumberJ(bridge.getEnv(), projectNumber);
bridge.getEnv()->CallStaticVoidMethod(bridge.getClass(), mid, fCoronaRuntime, projectNumberJ.getValue());
HandleJavaException();
}
}
void
NativeToJavaBridge::GooglePushNotificationsUnregister()
{
NativeTrace trace( "NativeToJavaBridge::GooglePushNotificationsUnregister" );
CallVoidMethod( "callGooglePushNotificationsUnregister" );
HandleJavaException();
}
void
NativeToJavaBridge::FetchInputDevice(int coronaDeviceId)
{
NativeTrace trace( "NativeToJavaBridge::FetchInputDevice" );
CallIntMethod( "callFetchInputDevice", coronaDeviceId );
}
void
NativeToJavaBridge::FetchAllInputDevices()
{
NativeTrace trace( "NativeToJavaBridge::FetchAllInputDevices" );
CallVoidMethod( "callFetchAllInputDevices" );
}
void
NativeToJavaBridge::VibrateInputDevice(int coronaDeviceId)
{
NativeTrace trace( "NativeToJavaBridge::VibrateInputDevice" );
CallIntMethod( "callVibrateInputDevice", coronaDeviceId );
}
void NativeToJavaBridge::SetRuntime(Rtt::Runtime *runtime)
{
fRuntime = runtime;
}
/**
* Base64 decodes a given byte array
* @param payloadData The char object to decode
* @param data The object that will be populated with the correctly decoded data
* @return true if decoding was successful else false
*/
bool
NativeToJavaBridge::DecodeBase64( const Rtt::Data<const char> & payloadData, Rtt::Data<char> & data )
{
JNIEnv *env = GetJNIEnv();
jclass base64 = env->FindClass("android/util/Base64");
jmethodID mid = env->GetStaticMethodID(base64, "decode", "([BI)[B");
if ( mid != NULL )
{
jbyteArrayParam payloadJ( env, payloadData.GetLength() );
payloadJ.setArray( payloadData.Get(), 0, payloadData.GetLength() );
jobject jo = env->CallStaticObjectMethod(base64, mid, payloadJ.getValue(), 0);
if (jo)
{
jbyteArrayResult bytesJ( env, (jbyteArray) jo );
data.Set( (const char *) bytesJ.getValues(), bytesJ.getLength() );
env->DeleteLocalRef(base64);
return true;
}
}
return false;
}
bool
NativeToJavaBridge::Check( const Rtt::Data<const char> & publicKey, const Rtt::Data<const char> & signature, const Rtt::Data<const char> & payloadData)
{
NativeTrace trace( "NativeToJavaBridge::Check" );
bool result = false;
JNIEnv *env = GetJNIEnv();
// byte[] decodedKey = Base64.Decode(publicKey, Base64.DEFAULT);
Rtt::Data<char> decodedKey(publicKey.Allocator());
if (!DecodeBase64(publicKey, decodedKey))
{
return false;
}
jbyteArrayParam decodedKeyJ( env, decodedKey.GetLength() );
decodedKeyJ.setArray( decodedKey.Get(), 0, decodedKey.GetLength() );
// byte[] decodedSignature = Base64.Decode(Signature, Base64.DEFAULT);
Rtt::Data<char> decodedSignature(signature.Allocator());
if (!DecodeBase64(signature, decodedSignature))
{
return false;
}
jbyteArrayParam decodedSignatureJ( env, decodedSignature.GetLength() );
decodedSignatureJ.setArray( decodedSignature.Get(), 0, decodedSignature.GetLength() );
// byte[] payload = payloadData;
jbyteArrayParam dataJ( env, payloadData.GetLength() );
dataJ.setArray( payloadData.Get(), 0, payloadData.GetLength() );
// X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodedKey);
jclass X509EncodedKeySpecClass = env->FindClass("java/security/spec/X509EncodedKeySpec");
jmethodID X509EncodedKeySpecConstructor = env->GetMethodID(X509EncodedKeySpecClass, "<init>", "([B)V");
jobject X509EncodedKeySpecObject = env->NewObject(X509EncodedKeySpecClass, X509EncodedKeySpecConstructor, decodedKeyJ.getValue());
// KeyFactory keyFactory = KeyFactory.getInstance("RSA");
jclass KeyFactoryClass = env->FindClass("java/security/KeyFactory");
jmethodID KeyFactoryMid = env->GetStaticMethodID(KeyFactoryClass, "getInstance", "(Ljava/lang/String;)Ljava/security/KeyFactory;");
jstringParam encryption(env, "RSA");
jobject KeyFactoryObject = env->CallStaticObjectMethod(KeyFactoryClass, KeyFactoryMid, encryption.getValue());
// PublicKey public = keyFactory.generatePublic(publicKeySpec);
jmethodID KeyFactoryMid1 = env->GetMethodID(KeyFactoryClass, "generatePublic", "(Ljava/security/spec/KeySpec;)Ljava/security/PublicKey;");
jobject PublicKey = env->CallObjectMethod(KeyFactoryObject, KeyFactoryMid1, X509EncodedKeySpecObject);
// Signature signature = Signature.getInstance("SHA1withRSA");
jclass SignatureClass = env->FindClass("java/security/Signature");
jmethodID SignatureMid = env->GetStaticMethodID(SignatureClass, "getInstance", "(Ljava/lang/String;)Ljava/security/Signature;");
jstringParam sigencryption(env, "SHA1withRSA");
jobject SignatureObject = env->CallStaticObjectMethod(SignatureClass, SignatureMid, sigencryption.getValue());
// signature.initVerify(publicKey);
jmethodID initVerifyMid = env->GetMethodID(SignatureClass, "initVerify", "(Ljava/security/PublicKey;)V");
env->CallVoidMethod(SignatureObject, initVerifyMid, PublicKey);
// signature.update(payload);
jmethodID updateMid = env->GetMethodID(SignatureClass, "update", "([B)V");
env->CallVoidMethod(SignatureObject, updateMid, dataJ.getValue());
// bool verified = signature.verify(decodedSignature);
jmethodID verifyMid = env->GetMethodID(SignatureClass, "verify", "([B)Z");
jboolean verified = env->CallBooleanMethod(SignatureObject, verifyMid, decodedSignatureJ.getValue());
// This shouldn't be necessary because all objects returned by jni functions are local references.
// Local references are automatically freed once the method exits.
env->DeleteLocalRef(X509EncodedKeySpecClass);
env->DeleteLocalRef(X509EncodedKeySpecObject);
env->DeleteLocalRef(KeyFactoryClass);
env->DeleteLocalRef(KeyFactoryObject);
env->DeleteLocalRef(PublicKey);
env->DeleteLocalRef(SignatureClass);
env->DeleteLocalRef(SignatureObject);
return verified;
}
void
NativeToJavaBridge::getAudioOutputSettings(std::vector<int>& settings)
{
NativeTrace trace("NativeToJavaBridge::getAudioOutputSettings");
// Fetch the JNI environment.
JNIEnv *jniEnvironmentPointer = GetJNIEnv();
if (!jniEnvironmentPointer)
{
return;
}
jclassInstance bridge(GetJNIEnv(), kNativeToJavaBridge);
if (bridge.isValid())
{
jmethodID mid = bridge.getEnv()->GetStaticMethodID(bridge.getClass(), "getAudioOutputSettings", "()Ljava/lang/String;");
if (mid != NULL)
{
jobject objectResult = bridge.getEnv()->CallStaticObjectMethod(bridge.getClass(), mid);
if (objectResult)
{
jstringResult stringResult(jniEnvironmentPointer);
stringResult.setString((jstring)objectResult);
if (stringResult.isValidString())
{
const char* res = stringResult.getUTF8();
char *token, *str, *tofree;
tofree = str = strdup(res); // We own str's memory now.
while ((token = strsep(&str, ",")))
{
settings.push_back(atoi(token));
}
free(tofree);
}
}
}
}
}
// ----------------------------------------------------------------------
| 30.3856 | 151 | 0.714904 | [
"object",
"vector"
] |
765c7557186d3ff96271cd8dfc676483f5ed274d | 11,313 | cpp | C++ | tools/mapgen.cpp | cookingclub/polarity | 187f8ac33e873f649ff3faea2f3ed60815cba9ef | [
"BSD-2-Clause"
] | 4 | 2015-09-03T04:49:35.000Z | 2017-11-21T22:25:30.000Z | tools/mapgen.cpp | cookingclub/polarity | 187f8ac33e873f649ff3faea2f3ed60815cba9ef | [
"BSD-2-Clause"
] | null | null | null | tools/mapgen.cpp | cookingclub/polarity | 187f8ac33e873f649ff3faea2f3ed60815cba9ef | [
"BSD-2-Clause"
] | null | null | null |
#include <assert.h>
#include "mapgen.h"
//Default map settings
#define DEFAULT_MAP_HEIGHT 28
#define DEFAULT_MAP_WIDTH 150
#define DEFAULT_MIN_PLATFORM_WIDTH 2
#define DEFAULT_MAX_PLATFORM_WIDTH 5
#define DEFAULT_MIN_GAP_WIDTH 2
#define DEFAULT_MAX_GAP_WIDTH 4
#define DEFAULT_MIN_PLATFORM_POSITION_CHANGE -2
#define DEFAULT_MAX_PLATFORM_POSITION_CHANGE 2
#define DEFAULT_INITIAL_PLATFORM_HEIGHT 4
//internal stuff, careful!
#define BUFFER_SIZE 50
#define GRASSTYPE_SHORT 0
#define GRASSTYPE_TALL 1
Mapgen::Mapgen() {
setWidth(DEFAULT_MAP_WIDTH);
setHeight(DEFAULT_MAP_HEIGHT);
setPlatformWidth(DEFAULT_MIN_PLATFORM_WIDTH, DEFAULT_MAX_PLATFORM_WIDTH);
setGapWidth(DEFAULT_MIN_GAP_WIDTH, DEFAULT_MAX_GAP_WIDTH);
setPlatformPositionChange(DEFAULT_MIN_PLATFORM_POSITION_CHANGE, DEFAULT_MAX_PLATFORM_POSITION_CHANGE);
setMinPlatformPosition(DEFAULT_MAP_HEIGHT / 2);
setInitialPlatformHeight(DEFAULT_INITIAL_PLATFORM_HEIGHT);
useShortGrass();
srand(time(NULL));
}
void Mapgen::setWidth(int width){iWidth = width;}
void Mapgen::setHeight(int height){iHeight = height;}
void Mapgen::setPlatformWidth(int min_width, int max_width){
iMinPlatformWidth = min_width;
iMaxPlatformWidth = max_width;
}
void Mapgen::setGapWidth(int min_gap_width, int max_gap_width){
iMinGapWidth = min_gap_width;
iMaxGapWidth = max_gap_width;
}
void Mapgen::setPlatformPositionChange(int min, int max) {
iMinPlatformPositionChange = min;
iMaxPlatformPositionChange = max;
}
void Mapgen::setMinPlatformPosition(int min) { iMinPlatformPosition = min;}
void Mapgen::setInitialPlatformHeight(int initial){iInitialPlatformHeight=initial;}
void Mapgen::useShortGrass(){iGrassType = GRASSTYPE_SHORT;}
void Mapgen::useTallGrass(){iGrassType = GRASSTYPE_TALL;}
void addTileSet(TiXmlElement *map, int gid, const char* name,int tilewidth, int tileheight, const char *filename, int width, int height) {
char buffer[BUFFER_SIZE];
TiXmlElement *tileset = new TiXmlElement("tileset");
map->LinkEndChild(tileset);
tileset->SetAttribute("name",name);
sprintf(buffer, "%d", gid);
tileset->SetAttribute("firstgid",buffer);
sprintf(buffer, "%d",tilewidth);
tileset->SetAttribute("tilewidth",buffer);
sprintf(buffer, "%d",tileheight);
tileset->SetAttribute("tileheight",buffer);
TiXmlElement *image = new TiXmlElement("image");
tileset->LinkEndChild(image);
image->SetAttribute("source", filename);
sprintf(buffer, "%d",height);
image->SetAttribute("height",buffer);
sprintf(buffer, "%d",width);
image->SetAttribute("width",buffer);
}
void Mapgen::addBackground(TiXmlElement *map, int width, int height, const char *background_source){
char buffer[BUFFER_SIZE];
TiXmlElement *imagelayer = new TiXmlElement("imagelayer");
map->LinkEndChild(imagelayer);
imagelayer->SetAttribute("name","background");
sprintf(buffer,"%d",width);
imagelayer->SetAttribute("width",buffer);
sprintf(buffer,"%d", height);
imagelayer->SetAttribute("height",buffer);
TiXmlElement *image = new TiXmlElement("image");
imagelayer->LinkEndChild(image);
image->SetAttribute("source",background_source);
}
void Mapgen::populate_mapbuffer(int *mapbuffer, int width, int height) {
int max_fillheight = height - 1;
memset(mapbuffer, 0, width * height); //assumes 0 is empty
int current_height = height - iInitialPlatformHeight;
int current_col = 0; //here we are 0 indexed
int old_height;
while(current_col < width) {
old_height = current_height;
int panelwidth = rand() % (iMaxPlatformWidth - iMinPlatformWidth) + iMinPlatformWidth;
// printf("rand times (%d - %d) + %d\n",iMaxPlatformPositionChange, iMinPlatformPositionChange, iMinPlatformPositionChange);
int delta_height = rand() % (iMaxPlatformPositionChange - iMinPlatformPositionChange) + iMinPlatformPositionChange;
// printf("Current height = %d Delta height %d",current_height, delta_height);
current_height = current_height + delta_height; //adjust height
current_height = std::min(current_height, max_fillheight); //block illegal platform positions
current_height = std::max(current_height, iMinPlatformPosition); //block illegal platform positions
// printf(" final height %d\n",current_height);
int end_col = std::min(width-1, current_col + panelwidth); //write the data
// printf("current_col = %d end_col = %d current_height = %d\n",current_col, end_col, current_height);
int firstcol = 1; //true if this is first column of platform
// int ascending = current_height > old_height;
// int descending = current_height < old_height;
for(;current_col <= end_col; current_col++) {
for(int row = current_height; row < height; row++) {
if(row==current_height) {
if(firstcol) {
switch(iGrassType) {
case GRASSTYPE_SHORT:
if(rand()%2)
mapbuffer[row*width + current_col] = 52;
else
mapbuffer[row*width + current_col] = 54;
break;
case GRASSTYPE_TALL:
mapbuffer[row*width + current_col] = 103;
break;
default:
assert(0);
}
} else if(current_col==end_col) {
switch(iGrassType) {
case GRASSTYPE_SHORT:
if(rand()%2)
mapbuffer[row*width + current_col] = 51;
else
mapbuffer[row*width + current_col] = 53;
break;
case GRASSTYPE_TALL:
switch (rand()%3) {
case 2:
mapbuffer[row*width + current_col] = 104;
break;
case 1:
mapbuffer[row*width + current_col] = 105;
break;
case 0:
mapbuffer[row*width + current_col] = 102;
break;
}
break;
default:
assert(0);
}
} else {
switch(iGrassType) {
case GRASSTYPE_SHORT:
mapbuffer[row*width + current_col] = 6 + rand() % 45;
break;
case GRASSTYPE_TALL:
mapbuffer[row*width + current_col] = 56 + rand() % 46;
// printf("%d\n", mapbuffer[row*width + current_col]);
break;
default:
assert(0);
}
}
// printf("Setting (%d, %d) = 3\n",row, current_col);
} else {
mapbuffer[row*width + current_col] = 1 + rand() % 4;
// printf("Setting (%d, %d) = 9\n",row, current_col);
}
}
firstcol = 0;
}
int gap_length = rand() % (iMaxGapWidth - iMinGapWidth) + iMinGapWidth;
current_col = current_col + gap_length;
}
}
void Mapgen::populate_doorbuffer(int *doorbuffer, int *mapbuffer, int width, int height) {
int door_row;
memset(mapbuffer, 0, width * height); //assumes 0 is empty
int door1, door2, door3, door4;
//FIND WHERE THE ROW WHERE THE DOOR SHOULD GO this is awful
for(door1 = 0; mapbuffer[door1 * width + width-2]==0 && door1 < height - 1; door1++) {
assert((door1 + 1) * width + width - 1 <= width * height);
}
for(door2 = 0; mapbuffer[door2 * width + width-3]==0 && door2 < height - 1; door2++) {
assert((door2 + 1) * width + width - 1 <= width * height);
}
for(door3 = 0; mapbuffer[door3 * width + width-4]==0 && door3 < height - 1; door3++) {
assert((door3 + 1) * width + width - 1 <= width * height);
}
for(door4 = 0; mapbuffer[door4 * width + width-5]==0 && door4 < height - 1; door4++) {
assert((door4 + 1) * width + width - 1 <= width * height);
}
door_row = std::min(std::min(std::min(door1, door2), door3), door4);
int door_initial_col = width - 5;
int k = 106;
for(int i = 4; i >= 0; i--) {
for(int j = 0; j < 4; j++) {
// fprintf(stderr, "populating at %d \n",(door_row - j) * width + door_initial_col + j);
assert((door_row - i) * width + door_initial_col + j >= 0);
assert((door_row - i) * width + door_initial_col + j < iWidth * iHeight);
doorbuffer[(door_row - i) * width + door_initial_col + j] = k;
k = k + 1;
}
}
}
void Mapgen::addGrass(TiXmlElement *map, int *mapbuffer, int width, int height) {
char buffer[BUFFER_SIZE];
TiXmlElement *layer = new TiXmlElement("layer");
map->LinkEndChild(layer);
layer->SetAttribute("name","Grass");
sprintf(buffer,"%d",width);
layer->SetAttribute("width",buffer);
sprintf(buffer,"%d", height);
layer->SetAttribute("height",buffer);
TiXmlElement *data = new TiXmlElement("data");
layer->LinkEndChild(data);
for(int row = 0; row < height; row++) {
for(int col = 0; col < width; col++) {
TiXmlElement *tile = new TiXmlElement("tile");
data->LinkEndChild(tile);
sprintf(buffer, "%d", mapbuffer[row * width + col]);
tile->SetAttribute("gid",buffer);
}
}
}
void Mapgen::addDoor(TiXmlElement *map, int *mapbuffer, int width, int height) {
char buffer[BUFFER_SIZE];
TiXmlElement *layer = new TiXmlElement("layer");
map->LinkEndChild(layer);
layer->SetAttribute("name","Static");
sprintf(buffer,"%d",width);
layer->SetAttribute("width",buffer);
sprintf(buffer,"%d", height);
layer->SetAttribute("height",buffer);
TiXmlElement *data = new TiXmlElement("data");
layer->LinkEndChild(data);
for(int row = 0; row < height; row++) {
for(int col = 0; col < width; col++) {
TiXmlElement *tile = new TiXmlElement("tile");
data->LinkEndChild(tile);
sprintf(buffer, "%d", mapbuffer[row * width + col]);
tile->SetAttribute("gid",buffer);
}
}
}
void Mapgen::addMap(TiXmlDocument *doc){
char buffer[BUFFER_SIZE];
TiXmlElement *map = new TiXmlElement("map");
doc->LinkEndChild(map);
map->SetAttribute("version","1.0");
map->SetAttribute("orientation","orthogonal");
sprintf(buffer,"%d", iWidth);
map->SetAttribute("width",buffer);
sprintf(buffer,"%d", iHeight);
map->SetAttribute("height",buffer);
map->SetAttribute("tilewidth","32");
map->SetAttribute("tileheight","32");
addTileSet(map,1,"fill",32,32,"../graphics/fill.png",64,64);
addTileSet(map,5,"dood",64,192,"../graphics/dood.png",64,192);
addTileSet(map,6,"grass",32,64,"../graphics/grass.png",1600,64);
addTileSet(map,56,"grassfore",32,96,"../graphics/grassfore.png",1600,96);
addTileSet(map,106,"door",32,32,"../graphics/door.png",128,160);
addTileSet(map,126,"solid",32,32,"../graphics/solid.png",64,32);
addTileSet(map,128,"edges",32,32,"../graphics/edges.png",160,96);
addBackground(map, iWidth, iHeight, "../graphics/background.png");
int *mapbuffer = new int[iWidth*iHeight];
populate_mapbuffer(mapbuffer, iWidth, iHeight);
addGrass(map, mapbuffer, iWidth, iHeight);
int *doorbuffer = new int[iWidth*iHeight];
populate_doorbuffer(doorbuffer, mapbuffer, iWidth, iHeight);
addDoor(map, doorbuffer, iWidth, iHeight);
}
void Mapgen::generateMap(const char *output_file )
{
TiXmlDocument doc;
TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild( decl );
addMap(&doc);
doc.SaveFile(output_file);
}
int main() {
Mapgen m;
m.setWidth(800);
m.setHeight(28); //28
m.setPlatformWidth(10, 20);
m.setGapWidth(2, 7);
// m.setPlatformPositionChange(DEFAULT_MIN_PLATFORM_POSITION_CHANGE, DEFAULT_MAX_PLATFORM_POSITION_CHANGE);
// m.setMinPlatformPosition(DEFAULT_MAP_HEIGHT / 2);
// m.setInitialPlatformHeight(DEFAULT_INITIAL_PLATFORM_HEIGHT);
m.useShortGrass();
m.useTallGrass();
m.generateMap("asdf.tmx");
}
| 29.771053 | 138 | 0.673031 | [
"solid"
] |
765cc97208de23b6f77a7f8f4e8ea01047c72c03 | 1,110 | cpp | C++ | hdu-winter-2020/contests/PTA天梯/1/12.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | 1 | 2020-08-10T21:40:21.000Z | 2020-08-10T21:40:21.000Z | hdu-winter-2020/contests/PTA天梯/1/12.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | hdu-winter-2020/contests/PTA天梯/1/12.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | #include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#define ll long long
#define F(i,a,b) for(int i=(a);i<=(b);i++)
#define mst(a,b) memset((a),(b),sizeof(a))
#define PII pair<int,int>
using namespace std;
template<class T>inline void read(T &x) {
x=0; int ch=getchar(),f=0;
while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
if(f)x=-x;
}
const int inf=0x3f3f3f3f;
int T,n,m;
vector<int> a[55];
set<int> p[55];
int main()
{
cin>>T;
for(int t=1;t<=T;t++)
{
cin>>n;
for(int i=1;i<=n;i++)
{
int x;cin>>x;
a[t].push_back(x);
p[t].insert(x);
}
}
cin>>m;
while(m--)
{
int x,y;
read(x),read(y);
int t2=0;
map<int,int> vis;
vis.clear();
for(int i=0;i<a[y].size();i++)
{
if(p[x].find(a[y][i])!=p[x].end()&&vis[a[y][i]]==0)
{
t2++;
vis[a[y][i]]=1;
}
}
int t1=p[x].size()+p[y].size()-t2;
double res=(double)t2/(double)t1;
res*=100;
printf("%.2lf%\n",res);
}
return 0;
}
| 17.903226 | 67 | 0.543243 | [
"vector"
] |
7666d752231cea044f66b9b66f4fe318c4c08e55 | 34,784 | cpp | C++ | lib/Codegen.cpp | egunnarsson/llfp | cbaa70c53dc018cbf2923c2d847ba36cc38c1ca0 | [
"MIT"
] | 1 | 2020-06-07T14:56:55.000Z | 2020-06-07T14:56:55.000Z | lib/Codegen.cpp | egunnarsson/llfp | cbaa70c53dc018cbf2923c2d847ba36cc38c1ca0 | [
"MIT"
] | null | null | null | lib/Codegen.cpp | egunnarsson/llfp | cbaa70c53dc018cbf2923c2d847ba36cc38c1ca0 | [
"MIT"
] | null | null | null |
#include <stack>
#pragma warning(push, 0)
// C4996 use of function, class member, variable, or typedef that's marked deprecated
#pragma warning(disable : 4996)
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Verifier.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/Support/FormatVariadic.h"
#pragma warning(pop)
#include "GlobalContext.h"
#include "Error.h"
#include "Log.h"
#include "Module.h"
#include "Codegen.h"
namespace llfp
{
namespace codegen
{
const Value ExpCodeGenerator::EmptyValue{ nullptr, nullptr };
CodeGenerator::CodeGenerator(
Driver* driver_,
GlobalContext *globalContext_,
SourceModule *sourceModule_,
llvm::LLVMContext* llvmContext_,
llvm::Module* llvmModule_) :
driver{ driver_ },
globalContext{ globalContext_ },
sourceModule{ sourceModule_ },
llvmContext{ llvmContext_ },
llvmBuilder(*llvmContext),
llvmModule{ llvmModule_ },
typeContext(*llvmContext, sourceModule, globalContext_)
{
}
bool CodeGenerator::generateFunction(const ast::Function*ast)
{
std::vector<type::TypePtr> types;
if (ast->type.identifier.name.empty())
{
Log(ast->location, "generating exported function with unbound return type");
return false;
}
auto retType = typeContext.getTypeFromAst(ast->type);
if (retType == nullptr)
{
Log(ast->location, "unknown type: ", ast->type.identifier.str());
return false;
}
types.push_back(retType);
for (auto ¶m : ast->parameters)
{
if (param->type.identifier.name.empty())
{
Log(ast->location, "generating exported function containing unbound parameter types");
return false;
}
auto type = typeContext.getTypeFromAst(param->type);
if (type == nullptr)
{
Log(param->location, "unknown type \"", param->type.identifier.str(), '"');
return false;
}
types.push_back(type);
}
auto f = generatePrototype(sourceModule, ast, std::move(types));
if (f->llvm->empty())
{
return generateFunctionBody(f);
}
return true;
}
bool CodeGenerator::generateFunction(const ast::Function*ast, std::vector<type::TypePtr> types)
{
auto f = generatePrototype(sourceModule, ast, std::move(types));
if (f != nullptr && f->llvm->empty())
{
return generateFunctionBody(f);
}
return f != nullptr;
}
Function* CodeGenerator::generatePrototype(const ImportedModule* module, const ast::Function* ast, std::vector<type::TypePtr> types)
{
if (types.empty())
{
Log(ast->location, "no return type specified");
return nullptr;
}
if (types.size() - 1 != ast->parameters.size())
{
Log(ast->location, "incorrect number of arguments"); // location should be called..., maybe we check at call site also?
return nullptr;
}
// unify types / type check / remove literals (requires the value...)
types[0] = typeContext.unify(types[0], typeContext.getTypeFromAst(ast->type));
for (size_t i = 1; i < types.size(); ++i)
{
types[i] = typeContext.unify(types[i], typeContext.getTypeFromAst(ast->parameters[i - 1]->type));
}
if (std::any_of(types.begin(), types.end(), [](auto x) { return x == nullptr; }))
{
Log(ast->location, "failed to unify function types");
return nullptr;
}
auto name = module->getMangledName(ast, types);
auto funIt = functions.find(name);
if (funIt == functions.end())
{
llvm::Type* returnType = nullptr;
std::vector<llvm::Type*> parameterTypes;
const bool ptrReturn = types.front()->isStructType();
if (ptrReturn)
{
returnType = llvm::Type::getVoidTy(*llvmContext);
parameterTypes.push_back(llvm::PointerType::get(types.front()->llvmType(), 0));
}
else
{
returnType = types.front()->llvmType();
}
for (auto typeIt = types.begin() + 1; typeIt != types.end(); ++typeIt)
{
if ((*typeIt)->isStructType())
{
parameterTypes.push_back(llvm::PointerType::get((*typeIt)->llvmType(), 0));
}
else
{
parameterTypes.push_back((*typeIt)->llvmType());
}
}
auto functionType = llvm::FunctionType::get(returnType, parameterTypes, false);
auto llvmFunction = llvm::Function::Create(functionType, llvm::Function::ExternalLinkage, name, llvmModule);
auto argRange = llvmFunction->args();
if (ptrReturn)
{
argRange.begin()->addAttr(llvm::Attribute::NoAlias);
argRange.begin()->addAttr(llvm::Attribute::get(*llvmContext, llvm::Attribute::Alignment, 8));
argRange = { argRange.begin() + 1, argRange.end() };
}
size_t i = 0;
for (auto &arg : argRange)
{
arg.setName(ast->parameters[i++]->identifier);
}
Function fun{ ast, llvmFunction, std::move(types) };
funIt = functions.insert(std::make_pair(std::move(name), std::move(fun))).first;
}
return &funIt->second;
}
bool CodeGenerator::generateFunctionBody(Function *function)
{
auto llvmFunction = function->llvm;
auto ast = function->ast;
auto& types = function->types;
llvmFunction->addAttribute(0, llvm::Attribute::get(*llvmContext, "frame-pointer", "all"));
auto bb = llvm::BasicBlock::Create(*llvmContext, "entry", llvmFunction);
llvmBuilder.SetInsertPoint(bb);
// if return type is user type it is returned in first argument
size_t argOffset = types[0]->isStructType() ? 1 : 0;
std::map<std::string, Value> namedValues;
for (size_t i = 0; i < ast->parameters.size(); ++i)
{
auto ¶m = ast->parameters[i];
if (namedValues.find(param->identifier) != namedValues.end())
{
Log(param->location, "duplicate parameter \"", param->identifier, '"');
return false;
}
if (!param->type.identifier.name.empty())
{
if (!typeContext.equals(types[i + 1], param->type))
{
Log(ast->location, "type mismatch, expected '", param->type.identifier.str(), "' actual '", types[i + 1]->identifier().str(), '\'');
return false;
}
}
llvm::Value* llvmArg = (llvmFunction->arg_begin() + argOffset + i);
if (types[i + 1]->isStructType())
{
llvmArg = llvmBuilder.CreateLoad(types[i + 1]->llvmType(), llvmArg);
}
namedValues[param->identifier] = { types[i + 1], llvmArg };
}
// type check return
if (!ast->type.identifier.name.empty())
{
if (!typeContext.equals(types[0], ast->type))
{
Log(ast->location, "type mismatch, expected '", ast->type.identifier.str(), "' actual '", types[0]->identifier().str(), '\'');
return false;
}
}
ExpCodeGenerator expGenerator(types[0], this, std::move(namedValues));
ast->functionBody->accept(&expGenerator);
if (expGenerator.getResult() != nullptr)
{
if (types[0]->isStructType())
{
auto store = llvmBuilder.CreateStore(expGenerator.getResult(), llvmFunction->arg_begin());
store->setAlignment(llvm::Align(8));
llvmBuilder.CreateRetVoid();
}
else
{
llvmBuilder.CreateRet(expGenerator.getResult());
}
return true;
}
else
{
return false;
}
}
// TODO: only once per dll
void CodeGenerator::AddDllMain()
{
std::vector<llvm::Type*> parameterTypes;
parameterTypes.push_back(llvm::Type::getInt8PtrTy(*llvmContext));
parameterTypes.push_back(llvm::Type::getInt32Ty(*llvmContext));
parameterTypes.push_back(llvm::Type::getInt8PtrTy(*llvmContext));
auto returnType = llvm::Type::getInt32Ty(*llvmContext);
llvm::FunctionType *functionType = llvm::FunctionType::get(returnType, parameterTypes, false);
auto llvmFunction = llvm::Function::Create(functionType, llvm::Function::ExternalLinkage, "_DllMainCRTStartup", llvmModule);
llvmFunction->setCallingConv(llvm::CallingConv::X86_StdCall);
auto bb = llvm::BasicBlock::Create(*llvmContext, "entry", llvmFunction);
llvmBuilder.SetInsertPoint(bb);
auto value = llvm::ConstantInt::get(returnType, 1);
llvmBuilder.CreateRet(value);
}
namespace
{
bool typeVarEqual(const std::string& typeVar, const ast::TypeIdentifier& type)
{
return type.parameters.empty() &&
type.identifier.moduleName.empty() &&
type.identifier.name == typeVar;
}
std::stack<int> findTypeVariableIndex(const std::string &typeVar, const ast::TypeIdentifier& type)
{
int paramIndex = 0;
for (auto& param : type.parameters)
{
if (typeVarEqual(typeVar, param))
{
std::stack<int> typeVarIndex;
typeVarIndex.push(paramIndex);
return typeVarIndex;
}
{
auto typeVarIndex = findTypeVariableIndex(typeVar, param);
if (!typeVarIndex.empty())
{
typeVarIndex.push(paramIndex);
return typeVarIndex;
}
}
++paramIndex;
}
return {};
}
type::Identifier getTypeByIndex(std::stack<int> index, const type::TypePtr& type)
{
if (index.empty())
{
return type->identifier();
}
else
{
auto currentIndex = index.top();
index.pop();
return getTypeByIndex(std::move(index), type->getTypeParameter(currentIndex));
}
}
type::Identifier findInstanceType(const ast::Class *classDecl, const ast::FunctionDeclaration* funDecl, const std::vector<type::TypePtr> & types)
{
auto& typeVar = classDecl->typeVariable;
int first = -1;
auto typeVariableIndex = findTypeVariableIndex(typeVar, funDecl->type);
if (typeVariableIndex.empty() && !typeVarEqual(typeVar, funDecl->type))
{
for (int paramIndex = 0; paramIndex < funDecl->parameters.size(); ++paramIndex)
{
auto ¶mTypeId = funDecl->parameters[paramIndex]->type;
typeVariableIndex = findTypeVariableIndex(typeVar, paramTypeId);
if (!typeVariableIndex.empty() || typeVarEqual(typeVar, paramTypeId))
{
first = paramIndex + 1;
break;
}
}
}
else
{
first = 0;
}
if (first == -1)
{
return {};
}
else
{
return getTypeByIndex(std::move(typeVariableIndex), types[first]);
}
}
} // namespace
Function* CodeGenerator::getFunction(const GlobalIdentifier& identifier, std::vector<type::TypePtr> types)
{
auto ast = sourceModule->lookupFunction(identifier);
auto astDecl = sourceModule->lookupFunctionDecl(identifier);
if (!astDecl.empty())
{
if (!ast.empty())
{
throw Error(std::string{ "reference to \"" } + identifier.str() + "\" is ambiguous");
}
type::Identifier instanceType = findInstanceType(astDecl.class_, astDecl.function, types);
assert(!instanceType.name.name.empty());
auto instanceAst = globalContext->lookupInstance(identifier.name, instanceType);
if (instanceAst.empty())
{
throw Error(std::string{ "no instance of \"" } + astDecl.importedModule->name() + ':' + astDecl.class_->name + ' ' + instanceType.str() + '"');
}
ast = instanceAst;
}
if (ast.function == nullptr)
{
throw Error(std::string{ "undefined function \"" } + identifier.str() +'"');
}
auto proto = generatePrototype(ast.importedModule, ast.function, std::move(types));
if (proto != nullptr)
{
driver->push({ ast, &proto->types });
}
return proto;
}
ExpCodeGenerator::ExpCodeGenerator(const type::TypePtr &type_, CodeGenerator *generator_, std::map<std::string, Value> parameters_) :
parent{ nullptr },
generator{ generator_ },
expectedType{ type_ },
values{ std::move(parameters_) },
result{ nullptr }
{
assert(expectedType->llvmType() != nullptr);
}
ExpCodeGenerator::ExpCodeGenerator(const type::TypePtr &type_, ExpCodeGenerator *parent_) :
parent{ parent_ },
generator{ parent_->generator },
expectedType{ type_ },
result{ nullptr }
{
assert(expectedType->llvmType() != nullptr);
}
llvm::Value* ExpCodeGenerator::generate(ast::Exp &exp, const type::TypePtr &type, ExpCodeGenerator *parent)
{
if (type == nullptr) // or not?
{
return nullptr;
}
ExpCodeGenerator generator(type, parent);
exp.accept(&generator);
return generator.result;
}
void ExpCodeGenerator::visit(ast::LetExp &exp)
{
for (auto &var : exp.letStatments)
{
if (var->parameters.size() != 0)
{
Log(exp.location, "let function definitions not implemented");
return;
}
type::TypePtr varType;
if (var->type.identifier.name.empty())
{
varType = type::TypeInferer::infer(*var->functionBody, this);
}
else
{
varType = getTypeContext()->getTypeFromAst(var->type);
}
if (varType == nullptr)
{
return;
}
auto value = ExpCodeGenerator::generate(*var->functionBody, varType, this);
if (value == nullptr)
{
return;
}
if (values.find(var->name) != values.end())
{
Log(exp.location, "already defined");
return;
}
else
{
values[var->name] = { varType, value };
}
}
result = ExpCodeGenerator::generate(*exp.exp, expectedType, this);
}
void ExpCodeGenerator::visit(ast::IfExp &exp)
{
auto condV = ExpCodeGenerator::generate(*exp.condition, getTypeContext()->getBool(), this);
if (condV == nullptr)
{
return;
}
auto& builder = llvmBuilder();
auto function = builder.GetInsertBlock()->getParent();
auto thenBB = llvm::BasicBlock::Create(llvmContext(), "then", function);
auto elseBB = llvm::BasicBlock::Create(llvmContext(), "else");
auto mergeBB = llvm::BasicBlock::Create(llvmContext(), "ifcont");
builder.CreateCondBr(condV, thenBB, elseBB);
builder.SetInsertPoint(thenBB);
auto thenV = ExpCodeGenerator::generate(*exp.thenExp, expectedType, this);
if (thenV == nullptr)
{
return;
}
builder.CreateBr(mergeBB);
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
thenBB = builder.GetInsertBlock();
function->getBasicBlockList().push_back(elseBB);
builder.SetInsertPoint(elseBB);
auto elseV = ExpCodeGenerator::generate(*exp.elseExp, expectedType, this);
if (elseV == nullptr)
{
return;
}
builder.CreateBr(mergeBB);
elseBB = builder.GetInsertBlock();
// Emit merge block.
function->getBasicBlockList().push_back(mergeBB);
builder.SetInsertPoint(mergeBB);
auto PN = builder.CreatePHI(expectedType->llvmType(), 2, "iftmp");
PN->addIncoming(thenV, thenBB);
PN->addIncoming(elseV, elseBB);
result = PN;
}
void ExpCodeGenerator::visit(ast::CaseExp &exp)
{
Log(exp.location, "case not implemented");
}
namespace
{
void typeError(ast::Exp &exp, const type::TypePtr &expected, llvm::StringRef actual)
{
Log(exp.location, "type mismatch, expected '", expected->identifier().str(), "' actual '", actual, '\'');
}
bool checkNum(ast::Exp &exp, const type::TypePtr &type)
{
if (!type->isNum())
{
typeError(exp, type, "Num"); // TODO: TypeClass name
return false;
}
return true;
}
bool checkInteger(ast::Exp &exp, const type::TypePtr&type)
{
if (!type->isInteger())
{
typeError(exp, type, "Integer"); // TODO: TypeClass name
return false;
}
return true;
}
bool checkBool(ast::Exp &exp, const type::TypePtr&type)
{
if (!type->isBool())
{
typeError(exp, type, "Bool"); // TODO: TypeClass name
return false;
}
return true;
}
} // namespace
void ExpCodeGenerator::visit(ast::BinaryExp &exp)
{
// math
if (exp.op == "*")// Multiplication
{
generateBinary(exp, checkNum,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateFMul(v1, v2, "fmul"); },
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateMul(v1, v2, "mul", false, false); });
}
else if (exp.op == "/") // Division
{
generateBinary(exp, checkNum,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateFDiv(v1, v2, "fdiv"); },
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateSDiv(v1, v2, "sdiv", false); },
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateUDiv(v1, v2, "udiv", false); });
}
else if (exp.op == "%") // Remainder
{
generateBinary(exp, checkNum,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateFRem(v1, v2, "frem"); },
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateSRem(v1, v2, "srem"); },
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateURem(v1, v2, "urem"); });
}
else if (exp.op == "+") // Addition
{
generateBinary(exp, checkNum,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateFAdd(v1, v2, "fadd"); },
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateAdd(v1, v2, "add"); });
}
else if (exp.op == "-") // Subtraction
{
generateBinary(exp, checkNum,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateFSub(v1, v2, "fsub"); },
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateSub(v1, v2, "sub"); });
}
// bitwise
else if (exp.op == "<<") // Shift
{
// Both arguments to the 'shl' instruction must be the same integer or vector of integer type. 'op2' is treated as an unsigned value.
generateBinary(exp, checkInteger,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateShl(v1, v2, "shl", false, false); });
}
else if (exp.op == ">>") // Signed shift
{
generateBinary(exp, checkInteger,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateAShr(v1, v2, "ashr", false); });
}
else if (exp.op == ">>>") // Logical shift
{
generateBinary(exp, checkInteger,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateLShr(v1, v2, "lshr", false); });
}
// compare
else if (exp.op == ">") { generateCompare(llvm::CmpInst::Predicate::ICMP_UGT, exp); } // Greater than
else if (exp.op == ">=") { generateCompare(llvm::CmpInst::Predicate::ICMP_UGE, exp); } // Greater or equal
else if (exp.op == "<") { generateCompare(llvm::CmpInst::Predicate::ICMP_ULT, exp); } // Less than
else if (exp.op == "<=") { generateCompare(llvm::CmpInst::Predicate::ICMP_ULE, exp); } // Less or equal
else if (exp.op == "==") { generateCompare(llvm::CmpInst::Predicate::ICMP_EQ, exp); } // Equal
else if (exp.op == "!=") { generateCompare(llvm::CmpInst::Predicate::ICMP_NE, exp); } // Not equal
// bitwise
else if (exp.op == "&")
{
generateBinary(exp, checkInteger,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateAnd(v1, v2, "and"); });
}
else if (exp.op == "|")
{
generateBinary(exp, checkInteger,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateOr(v1, v2, "or"); });
}
else if (exp.op == "^")
{
generateBinary(exp, checkInteger,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateXor(v1, v2, "xor"); });
}
// logical
else if (exp.op == "&&")
{
generateBinary(exp, checkBool,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateAnd(v1, v2, "and"); });
}
else if (exp.op == "||")
{
generateBinary(exp, checkBool,
[this](llvm::Value* v1, llvm::Value* v2) { return llvmBuilder().CreateOr(v1, v2, "or"); });
}
else
{
Log(exp.location, "unknown operator: ", exp.op);
}
}
namespace
{
constexpr llvm::CmpInst::Predicate convertToFPredicate(llvm::CmpInst::Predicate predicate)
{
switch (predicate)
{
case llvm::CmpInst::ICMP_EQ: return llvm::CmpInst::FCMP_OEQ;
case llvm::CmpInst::ICMP_NE: return llvm::CmpInst::FCMP_ONE;
case llvm::CmpInst::ICMP_UGT: return llvm::CmpInst::FCMP_OGT;
case llvm::CmpInst::ICMP_UGE: return llvm::CmpInst::FCMP_OGE;
case llvm::CmpInst::ICMP_ULT: return llvm::CmpInst::FCMP_OLT;
case llvm::CmpInst::ICMP_ULE: return llvm::CmpInst::FCMP_OLE;
default: return llvm::CmpInst::BAD_FCMP_PREDICATE;
}
}
constexpr llvm::CmpInst::Predicate convertToSPredicate(llvm::CmpInst::Predicate predicate)
{
switch (predicate)
{
case llvm::CmpInst::ICMP_EQ: return llvm::CmpInst::ICMP_EQ;
case llvm::CmpInst::ICMP_NE: return llvm::CmpInst::ICMP_NE;
case llvm::CmpInst::ICMP_UGT: return llvm::CmpInst::ICMP_SGT;
case llvm::CmpInst::ICMP_UGE: return llvm::CmpInst::ICMP_SGE;
case llvm::CmpInst::ICMP_ULT: return llvm::CmpInst::ICMP_SLT;
case llvm::CmpInst::ICMP_ULE: return llvm::CmpInst::ICMP_SLE;
default: return llvm::CmpInst::BAD_ICMP_PREDICATE;
}
}
} // namespace
void ExpCodeGenerator::generateCompare(llvm::CmpInst::Predicate predicate, ast::BinaryExp &exp)
{
if (!expectedType->isBool())
{
typeError(exp, expectedType, type::name::Bool);
}
else
{
auto lhsT = type::TypeInferer::infer(*exp.lhs, this);
auto rhsT = type::TypeInferer::infer(*exp.rhs, this);
if (lhsT == nullptr || rhsT == nullptr)
{
return;
}
auto type = getTypeContext()->unify(lhsT, rhsT);
if (type != nullptr)
{
auto args = generateBinary(type, exp);
auto arg1 = std::get<0>(args), arg2 = std::get<1>(args);
if (arg1 == nullptr || arg2 == nullptr)
{
return;
}
if (type->isFloating())
{
result = llvmBuilder().CreateFCmp(convertToFPredicate(predicate), arg1, arg2, "fcmp");
}
else if (type->isSigned())
{
result = llvmBuilder().CreateICmp(convertToSPredicate(predicate), arg1, arg2, "scmp");
}
else
{
result = llvmBuilder().CreateICmp(predicate, arg1, arg2, "icmp");
}
}
else
{
Log(exp.location, "failed to unify types, '", lhsT->identifier().str(), "' and '", rhsT->identifier().str(), '\'');
}
}
}
void ExpCodeGenerator::visit(ast::UnaryExp &exp)
{
if (exp.op == "-")
{
if (!expectedType->isSigned())
{
typeError(exp, expectedType, "Signed"); // TODO: TypeClass name
}
else
{
auto value = ExpCodeGenerator::generate(*exp.operand, expectedType, this);
if (value != nullptr)
{
if (expectedType->isFloating())
{
result = llvmBuilder().CreateFNeg(value, "fneg");
}
else
{
result = llvmBuilder().CreateNeg(value, "neg");
}
}
}
}
else if (exp.op == "!")
{
if (!expectedType->isBool())
{
typeError(exp, expectedType, type::name::Bool);
}
else
{
auto value = ExpCodeGenerator::generate(*exp.operand, expectedType, this);
if (value != nullptr)
{
result = llvmBuilder().CreateNot(value, "lnot");
}
}
}
else if (exp.op == "~")
{
if (!expectedType->isInteger())
{
typeError(exp, expectedType, "Integer"); // TODO: TypeClass name
}
else
{
auto value = ExpCodeGenerator::generate(*exp.operand, expectedType, this);
if (value != nullptr)
{
result = llvmBuilder().CreateNot(value, "bnot");
}
}
}
else
{
Log(exp.location, "unknown unary operator: ", exp.op);
}
}
void ExpCodeGenerator::visit(ast::LiteralExp &exp)
{
llvm::Type *type = expectedType->llvmType();
// TODO: test if value fits in expectedType bit size
switch (exp.tokenType)
{
case lex::Token::Integer:
if (expectedType->isFloating())
{
result = llvm::ConstantFP::get(type, exp.value);
}
else if (expectedType->isInteger())
{
result = llvm::ConstantInt::get(llvm::IntegerType::get(llvmContext(), type->getIntegerBitWidth()), exp.value, 10);
}
else
{
typeError(exp, expectedType, "Num"); // TODO: TypeClass name
}
break;
case lex::Token::Float:
if (!expectedType->isFloating())
{
typeError(exp, expectedType, "Floating"); // TODO: TypeClass name
}
else
{
result = llvm::ConstantFP::get(type, exp.value);
}
break;
case lex::Token::Char:
if (!getTypeContext()->equals(expectedType, type::name::Char))
{
typeError(exp, expectedType, type::name::Char);
}
else
{
assert(exp.value.size() == 1);
result = llvm::ConstantInt::get(type, exp.value[0]);
}
break;
case lex::Token::String:
Log(exp.location, "string not supported");
break;
case lex::Token::Bool:
if (!expectedType->isBool())
{
typeError(exp, expectedType, type::name::Bool);
}
else
{
if (exp.value == "true")
{
result = llvm::ConstantInt::getTrue(llvmContext());
}
else if (exp.value == "false")
{
result = llvm::ConstantInt::getFalse(llvmContext());
}
else
{
// we should not have constructed ast::LiteralExp with tokenType lex::tok_bool
assert(false);
}
}
break;
default:
assert(false);
break;
}
}
void ExpCodeGenerator::visit(ast::CallExp &exp)
{
std::vector<type::TypePtr> types;
types.push_back(expectedType);
for (auto &arg : exp.arguments)
{
auto type = type::TypeInferer::infer(*arg, this);
if (type == nullptr)
{
return;
}
else
{
types.push_back(type);
}
}
try
{
auto function = getFunction(exp.identifier, std::move(types)); // these types have to be concreate but they have only been infered, will a fix solve it?
if (function == nullptr)
{
return;
}
else
{
std::vector<llvm::Value*> arguments;
// Returning user type it is done on the stack, function will return void
llvm::Value* retValue = nullptr;
if (expectedType->isStructType())
{
retValue = llvmBuilder().CreateAlloca(expectedType->llvmType());
arguments.push_back(retValue);
}
for (size_t i = 0; i < exp.arguments.size(); ++i)
{
auto argValue = generate(*exp.arguments[i], function->types[i + 1], this);
if (argValue == nullptr)
{
return;
}
// if arg is user type, alloca and store
if (argValue->getType()->isStructTy())
{
auto allocaValue = llvmBuilder().CreateAlloca(argValue->getType());
llvmBuilder().CreateStore(argValue, allocaValue);
argValue = allocaValue;
}
arguments.push_back(argValue);
}
// if return user type, result = load(first arg)
if (expectedType->isStructType())
{
llvmBuilder().CreateCall(function->llvm, arguments);
result = llvmBuilder().CreateLoad(expectedType->llvmType(), retValue);
}
else
{
result = llvmBuilder().CreateCall(function->llvm, arguments, "call");
}
}
}
catch(const Error &e)
{
Log(exp.location, e.what());
}
}
void ExpCodeGenerator::visit(ast::VariableExp &exp)
{
if (exp.identifier.moduleName.empty())
{
auto x = getNamedValue(exp.identifier.name);
if (x.value != nullptr)
{
// check type
if (x.type != expectedType)
{
typeError(exp, expectedType, x.type->identifier().str());
return;
}
result = x.value;
return;
}
}
std::vector<type::TypePtr> types;
types.push_back(expectedType);
auto y = getFunction(exp.identifier, std::move(types));
if (y != nullptr)
{
auto &function = *y;
if (function.ast->parameters.empty())
{
// generate call
if (!getTypeContext()->equals(expectedType, function.ast->type))
{
typeError(exp, expectedType, function.ast->type.identifier.str());
return;
}
result = llvmBuilder().CreateCall(function.llvm, std::vector<llvm::Value*>{}, "call");
}
else
{
Log(exp.location, exp.identifier.str(), " is not a zero parameter function");
}
}
else
{
Log(exp.location, "unknown identifier: ", exp.identifier.str());
}
}
void ExpCodeGenerator::visit(ast::FieldExp &exp)
{
auto lhsType = type::TypeInferer::infer(*exp.lhs, this);
if (lhsType == nullptr)
{
return;
}
auto index = lhsType->getFieldIndex(exp.fieldIdentifier);
if (index == type::Type::InvalidIndex)
{
Log(exp.location, "unknown field: ", exp.fieldIdentifier);
return;
}
// type check
auto inferedFieldType = lhsType->getFieldType(index);
auto fieldType = getTypeContext()->fixify(expectedType, inferedFieldType);
if (fieldType == nullptr)
{
Log(exp.location, "failed to unify types, '", expectedType->identifier().str(), "' and '", inferedFieldType->identifier().str(), '\'');
return;
}
if (fieldType != inferedFieldType) // the fieldType could be a literal for example
{
// lhsType = updateField(lhsType, index, fieldType);
auto lhsId = lhsType->identifier();
assert(lhsId.parameters.size() > index);
lhsId.parameters[index] = fieldType->identifier();
lhsType = getTypeContext()->getType(lhsId); // does this guarantee concrete? then we dont have to fix
}
lhsType = getTypeContext()->fix(lhsType);
if (lhsType == nullptr)
{
Log({}, "failed to fix lhs of field expression");
return;
}
// NOTE: Generating a struct where only one fieldType is guaranteed to be concreate
auto structValue = ExpCodeGenerator::generate(*exp.lhs, lhsType, this);
if (structValue == nullptr)
{
return;
}
// TODO: do we need to return fieldType for something?
// we have infered it and the caller doesn't know about it
result = llvmBuilder().CreateExtractValue(structValue, { index });
}
void ExpCodeGenerator::visit(ast::ConstructorExp &exp)
{
auto inferedType = type::TypeInferer::infer(exp, this);
if (inferedType == nullptr) { return; }
auto type = getTypeContext()->unify(expectedType, inferedType);
if (type != nullptr)
{
const auto size = type->getFieldCount();
if (size != exp.arguments.size())
{
Log(exp.location, "incorrect number of arguments");
return;
}
bool fail = false;
llvm::Value *value = llvm::UndefValue::get(type->llvmType());
for (unsigned int i = 0; i < size; ++i)
{
auto &arg = exp.arguments[i];
// at the moment name is only used to check correctness
if (!arg->name.empty())
{
auto index = type->getFieldIndex(arg->name);
if (index != i)
{
Log(arg->location, index == type::Type::InvalidIndex
? "unknown field name"
: "incorrect field position");
fail = true;
}
}
auto argValue = ExpCodeGenerator::generate(*arg->exp, type->getFieldType(i), this);
if (argValue != nullptr)
{
value = llvmBuilder().CreateInsertValue(value, argValue, { i });
}
else
{
fail = true;
}
}
if (!fail)
{
result = value;
}
}
}
const Value& ExpCodeGenerator::getNamedValue(const std::string &name)
{
auto it = values.find(name);
if (it == values.end())
{
if (parent == nullptr)
{
return EmptyValue;
}
else
{
return parent->getNamedValue(name);
}
}
return it->second;
}
type::TypePtr ExpCodeGenerator::getVariableType(const std::string& variable)
{
return getNamedValue(variable).type;
}
Function* ExpCodeGenerator::getFunction(const GlobalIdentifier& identifier, std::vector<type::TypePtr> types)
{
// TODO: add local functions
return generator->getFunction(identifier, std::move(types));
}
FunAst ExpCodeGenerator::getFunctionAST(const GlobalIdentifier& identifier)
{
return generator->sourceModule->lookupFunction(identifier);
}
FunDeclAst ExpCodeGenerator::getFunctionDeclarationAST(const GlobalIdentifier& identifier)
{
return generator->sourceModule->lookupFunctionDecl(identifier);
}
DataAst ExpCodeGenerator::getDataAST(const GlobalIdentifier& identifier)
{
return generator->sourceModule->lookupType(identifier);
}
llvm::Value* ExpCodeGenerator::getResult()
{
return result;
}
} // namespace codegen
} // namespace hpfp
| 30.246957 | 160 | 0.57285 | [
"vector"
] |
76672d78d54b628c940c8a6b3d465d89a6fa2e10 | 4,723 | cpp | C++ | blades/xbmc/xbmc/guilib/GUISettingsSliderControl.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/guilib/GUISettingsSliderControl.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/guilib/GUISettingsSliderControl.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "GUISettingsSliderControl.h"
CGUISettingsSliderControl::CGUISettingsSliderControl(int parentID, int controlID, float posX, float posY, float width, float height, float sliderWidth, float sliderHeight, const CTextureInfo &textureFocus, const CTextureInfo &textureNoFocus, const CTextureInfo& backGroundTexture, const CTextureInfo& nibTexture, const CTextureInfo& nibTextureFocus, const CLabelInfo &labelInfo, int iType)
: CGUISliderControl(parentID, controlID, posX, posY, sliderWidth, sliderHeight, backGroundTexture, nibTexture,nibTextureFocus, iType)
, m_buttonControl(parentID, controlID, posX, posY, width, height, textureFocus, textureNoFocus, labelInfo)
, m_label(posX, posY, width, height, labelInfo)
{
m_label.SetAlign((labelInfo.align & XBFONT_CENTER_Y) | XBFONT_RIGHT);
ControlType = GUICONTROL_SETTINGS_SLIDER;
}
CGUISettingsSliderControl::~CGUISettingsSliderControl(void)
{
}
void CGUISettingsSliderControl::Process(unsigned int currentTime, CDirtyRegionList &dirtyregions)
{
if (m_bInvalidated)
{
float sliderPosX = m_buttonControl.GetXPosition() + m_buttonControl.GetWidth() - m_width - m_buttonControl.GetLabelInfo().offsetX;
float sliderPosY = m_buttonControl.GetYPosition() + (m_buttonControl.GetHeight() - m_height) * 0.5f;
CGUISliderControl::SetPosition(sliderPosX, sliderPosY);
}
m_buttonControl.SetFocus(HasFocus());
m_buttonControl.SetPulseOnSelect(m_pulseOnSelect);
m_buttonControl.SetEnabled(m_enabled);
m_buttonControl.DoProcess(currentTime, dirtyregions);
ProcessText();
CGUISliderControl::Process(currentTime, dirtyregions);
}
void CGUISettingsSliderControl::Render()
{
m_buttonControl.Render();
CGUISliderControl::Render();
m_label.Render();
}
void CGUISettingsSliderControl::ProcessText()
{
bool changed = false;
changed |= m_label.SetMaxRect(m_buttonControl.GetXPosition(), m_buttonControl.GetYPosition(), m_posX - m_buttonControl.GetXPosition(), m_buttonControl.GetHeight());
changed |= m_label.SetText(CGUISliderControl::GetDescription());
if (IsDisabled())
changed |= m_label.SetColor(CGUILabel::COLOR_DISABLED);
else if (HasFocus())
changed |= m_label.SetColor(CGUILabel::COLOR_FOCUSED);
else
changed |= m_label.SetColor(CGUILabel::COLOR_TEXT);
if (changed)
MarkDirtyRegion();
}
bool CGUISettingsSliderControl::OnAction(const CAction &action)
{
return CGUISliderControl::OnAction(action);
}
void CGUISettingsSliderControl::FreeResources(bool immediately)
{
CGUISliderControl::FreeResources(immediately);
m_buttonControl.FreeResources(immediately);
}
void CGUISettingsSliderControl::DynamicResourceAlloc(bool bOnOff)
{
CGUISliderControl::DynamicResourceAlloc(bOnOff);
m_buttonControl.DynamicResourceAlloc(bOnOff);
}
void CGUISettingsSliderControl::AllocResources()
{
CGUISliderControl::AllocResources();
m_buttonControl.AllocResources();
}
void CGUISettingsSliderControl::SetInvalid()
{
CGUISliderControl::SetInvalid();
m_buttonControl.SetInvalid();
}
void CGUISettingsSliderControl::SetPosition(float posX, float posY)
{
m_buttonControl.SetPosition(posX, posY);
CGUISliderControl::SetInvalid();
}
void CGUISettingsSliderControl::SetWidth(float width)
{
m_buttonControl.SetWidth(width);
CGUISliderControl::SetInvalid();
}
void CGUISettingsSliderControl::SetHeight(float height)
{
m_buttonControl.SetHeight(height);
CGUISliderControl::SetInvalid();
}
void CGUISettingsSliderControl::SetEnabled(bool bEnable)
{
CGUISliderControl::SetEnabled(bEnable);
m_buttonControl.SetEnabled(bEnable);
}
std::string CGUISettingsSliderControl::GetDescription() const
{
return m_buttonControl.GetDescription() + " " + CGUISliderControl::GetDescription();
}
bool CGUISettingsSliderControl::UpdateColors()
{
bool changed = CGUISliderControl::UpdateColors();
changed |= m_buttonControl.SetColorDiffuse(m_diffuseColor);
changed |= m_buttonControl.UpdateColors();
changed |= m_label.UpdateColors();
return changed;
}
| 33.027972 | 389 | 0.775778 | [
"render"
] |
7672049fe6e28023e7d01cbcfc2527d7ae8fc74d | 7,887 | cc | C++ | CondFormats/HcalObjects/src/HcalElectronicsMap.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | CondFormats/HcalObjects/src/HcalElectronicsMap.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | CondFormats/HcalObjects/src/HcalElectronicsMap.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | /**
\class HcalElectronicsMap
\author Fedor Ratnikov (UMd)
POOL object to store mapping for Hcal channels
$Author: ratnikov
$Date: 2007/09/18 06:48:38 $
$Revision: 1.22 $
*/
#include <iostream>
#include <set>
#include "CondFormats/HcalObjects/interface/HcalElectronicsMap.h"
#include "CondFormats/HcalObjects/interface/HcalObjectAddons.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
HcalElectronicsMap::HcalElectronicsMap(const HcalElectronicsMapAddons::Helper& helper)
: mPItems(helper.mPItems), mTItems(helper.mTItems) {
initialize();
}
HcalElectronicsMap::~HcalElectronicsMap() {}
// copy-ctor
HcalElectronicsMap::HcalElectronicsMap(const HcalElectronicsMap& src)
: mPItems(src.mPItems), mTItems(src.mTItems), mPItemsById(src.mPItemsById), mTItemsByTrigId(src.mTItemsByTrigId) {}
// copy assignment operator
HcalElectronicsMap& HcalElectronicsMap::operator=(const HcalElectronicsMap& rhs) {
HcalElectronicsMap temp(rhs);
temp.swap(*this);
return *this;
}
// public swap function
void HcalElectronicsMap::swap(HcalElectronicsMap& other) {
std::swap(mPItems, other.mPItems);
std::swap(mTItems, other.mTItems);
std::swap(mPItemsById, other.mPItemsById);
std::swap(mTItemsByTrigId, other.mTItemsByTrigId);
}
// move constructor
HcalElectronicsMap::HcalElectronicsMap(HcalElectronicsMap&& other) { other.swap(*this); }
const HcalElectronicsMap::PrecisionItem* HcalElectronicsMap::findById(unsigned long fId) const {
PrecisionItem target(fId, 0);
return HcalObjectAddons::findByT<PrecisionItem, HcalElectronicsMapAddons::LessById>(&target, mPItemsById);
}
const HcalElectronicsMap::PrecisionItem* HcalElectronicsMap::findPByElId(unsigned long fElId) const {
HcalElectronicsId eid(fElId);
const PrecisionItem* i = &(mPItems[eid.linearIndex()]);
if (i != nullptr && i->mElId != fElId)
i = nullptr;
return i;
}
const HcalElectronicsMap::TriggerItem* HcalElectronicsMap::findTByElId(unsigned long fElId) const {
HcalElectronicsId eid(fElId);
const TriggerItem* i = &(mTItems[eid.linearIndex()]);
if (i != nullptr && i->mElId != fElId)
i = nullptr;
return i;
}
const HcalElectronicsMap::TriggerItem* HcalElectronicsMap::findByTrigId(unsigned long fTrigId) const {
TriggerItem target(fTrigId, 0);
return HcalObjectAddons::findByT<TriggerItem, HcalElectronicsMapAddons::LessByTrigId>(&target, mTItemsByTrigId);
}
const DetId HcalElectronicsMap::lookup(HcalElectronicsId fId) const {
const PrecisionItem* item = findPByElId(fId.rawId());
return DetId(item ? item->mId : 0);
}
const HcalElectronicsId HcalElectronicsMap::lookup(DetId fId) const {
const PrecisionItem* item = findById(fId.rawId());
return HcalElectronicsId(item ? item->mElId : 0);
}
const DetId HcalElectronicsMap::lookupTrigger(HcalElectronicsId fId) const {
const TriggerItem* item = findTByElId(fId.rawId());
return DetId(item ? item->mTrigId : 0);
}
const HcalElectronicsId HcalElectronicsMap::lookupTrigger(DetId fId) const {
const TriggerItem* item = findByTrigId(fId.rawId());
return HcalElectronicsId(item ? item->mElId : 0);
}
bool HcalElectronicsMap::lookup(const HcalElectronicsId pid, HcalElectronicsId& eid, HcalGenericDetId& did) const {
const PrecisionItem* i = &(mPItems[pid.linearIndex()]);
if (i != nullptr && i->mId != 0) {
eid = HcalElectronicsId(i->mElId);
did = HcalGenericDetId(i->mId);
return true;
} else
return false;
}
bool HcalElectronicsMap::lookup(const HcalElectronicsId pid, HcalElectronicsId& eid, HcalTrigTowerDetId& did) const {
const TriggerItem* i = &(mTItems[pid.linearIndex()]);
if (i != nullptr && i->mTrigId != 0) {
eid = HcalElectronicsId(i->mElId);
did = HcalGenericDetId(i->mTrigId);
return true;
} else
return false;
}
std::vector<HcalElectronicsId> HcalElectronicsMap::allElectronicsId() const {
std::vector<HcalElectronicsId> result;
for (std::vector<PrecisionItem>::const_iterator item = mPItems.begin(); item != mPItems.end(); item++)
if (item->mElId)
result.push_back(HcalElectronicsId(item->mElId));
for (std::vector<TriggerItem>::const_iterator item = mTItems.begin(); item != mTItems.end(); item++)
if (item->mElId)
result.push_back(HcalElectronicsId(item->mElId));
return result;
}
std::vector<HcalElectronicsId> HcalElectronicsMap::allElectronicsIdPrecision() const {
std::vector<HcalElectronicsId> result;
for (std::vector<PrecisionItem>::const_iterator item = mPItems.begin(); item != mPItems.end(); item++)
if (item->mElId)
result.push_back(HcalElectronicsId(item->mElId));
return result;
}
std::vector<HcalElectronicsId> HcalElectronicsMap::allElectronicsIdTrigger() const {
std::vector<HcalElectronicsId> result;
for (std::vector<TriggerItem>::const_iterator item = mTItems.begin(); item != mTItems.end(); item++)
if (item->mElId)
result.push_back(HcalElectronicsId(item->mElId));
return result;
}
std::vector<HcalGenericDetId> HcalElectronicsMap::allPrecisionId() const {
std::vector<HcalGenericDetId> result;
std::set<unsigned long> allIds;
for (std::vector<PrecisionItem>::const_iterator item = mPItems.begin(); item != mPItems.end(); item++)
if (item->mId)
allIds.insert(item->mId);
for (std::set<unsigned long>::const_iterator channel = allIds.begin(); channel != allIds.end(); channel++) {
result.push_back(HcalGenericDetId(*channel));
}
return result;
}
std::vector<HcalTrigTowerDetId> HcalElectronicsMap::allTriggerId() const {
std::vector<HcalTrigTowerDetId> result;
std::set<unsigned long> allIds;
for (std::vector<TriggerItem>::const_iterator item = mTItems.begin(); item != mTItems.end(); item++)
if (item->mTrigId)
allIds.insert(item->mTrigId);
for (std::set<unsigned long>::const_iterator channel = allIds.begin(); channel != allIds.end(); channel++)
result.push_back(HcalTrigTowerDetId(*channel));
return result;
}
//use helper to do mapping
HcalElectronicsMapAddons::Helper::Helper()
: mPItems(HcalElectronicsId::maxLinearIndex + 1), mTItems(HcalElectronicsId::maxLinearIndex + 1) {}
bool HcalElectronicsMapAddons::Helper::mapEId2tId(HcalElectronicsId fElectronicsId, HcalTrigTowerDetId fTriggerId) {
HcalElectronicsMap::TriggerItem& item = mTItems[fElectronicsId.linearIndex()];
if (item.mElId == 0)
item.mElId = fElectronicsId.rawId();
if (item.mTrigId == 0) {
item.mTrigId = fTriggerId.rawId(); // just cast avoiding long machinery
} else if (item.mTrigId != fTriggerId.rawId()) {
edm::LogWarning("HCAL") << "HcalElectronicsMap::Helper::mapEId2tId-> Electronics channel " << fElectronicsId
<< " already mapped to trigger channel " << (HcalTrigTowerDetId(item.mTrigId))
<< ". New value " << fTriggerId << " is ignored";
return false;
}
return true;
}
bool HcalElectronicsMapAddons::Helper::mapEId2chId(HcalElectronicsId fElectronicsId, DetId fId) {
HcalElectronicsMap::PrecisionItem& item = mPItems[fElectronicsId.linearIndex()];
if (item.mElId == 0)
item.mElId = fElectronicsId.rawId();
if (item.mId == 0) {
item.mId = fId.rawId();
} else if (item.mId != fId.rawId()) {
edm::LogWarning("HCAL") << "HcalElectronicsMap::Helper::mapEId2tId-> Electronics channel " << fElectronicsId
<< " already mapped to channel " << HcalGenericDetId(item.mId) << ". New value "
<< HcalGenericDetId(fId) << " is ignored";
return false;
}
return true;
}
void HcalElectronicsMap::sortById() {
HcalObjectAddons::sortByT<PrecisionItem, HcalElectronicsMapAddons::LessById>(mPItems, mPItemsById);
}
void HcalElectronicsMap::sortByTriggerId() {
HcalObjectAddons::sortByT<TriggerItem, HcalElectronicsMapAddons::LessByTrigId>(mTItems, mTItemsByTrigId);
}
void HcalElectronicsMap::initialize() {
sortById();
sortByTriggerId();
}
| 37.557143 | 119 | 0.725244 | [
"object",
"vector"
] |
7683172193bb93e49b046af8ca25ebff34d01f59 | 278 | cc | C++ | atcoder/abc/164/c_gacha.cc | boobam0618/competitive-programming | 0341bd8bb240b1ed0d84cc60db91508242fc867b | [
"MIT"
] | null | null | null | atcoder/abc/164/c_gacha.cc | boobam0618/competitive-programming | 0341bd8bb240b1ed0d84cc60db91508242fc867b | [
"MIT"
] | 32 | 2019-08-15T09:16:48.000Z | 2020-02-09T16:23:30.000Z | atcoder/abc/164/c_gacha.cc | boobam0618/competitive-programming | 0341bd8bb240b1ed0d84cc60db91508242fc867b | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
#include <vector>
int main() {
int n;
std::cin >> n;
std::set<std::string> prizes;
for (int i = 0; i < n; ++i) {
std::string prize;
std::cin >> prize;
prizes.insert(prize);
}
std::cout << prizes.size() << std::endl;
}
| 17.375 | 42 | 0.553957 | [
"vector"
] |
7688e402ea5c50bd075a6a7844e55492b4c55354 | 4,281 | hpp | C++ | src/benchmarks/SignalBenchmarks.hpp | koplyarov/wigwag | d5646c610b324c9252ec7ac807f883f88e7442eb | [
"0BSD"
] | 103 | 2016-02-26T14:39:03.000Z | 2021-02-13T10:15:52.000Z | src/benchmarks/SignalBenchmarks.hpp | koplyarov/wigwag | d5646c610b324c9252ec7ac807f883f88e7442eb | [
"0BSD"
] | 1 | 2018-05-07T06:00:19.000Z | 2018-05-07T19:57:20.000Z | src/benchmarks/SignalBenchmarks.hpp | koplyarov/wigwag | d5646c610b324c9252ec7ac807f883f88e7442eb | [
"0BSD"
] | 9 | 2016-03-17T11:56:33.000Z | 2020-08-06T10:11:50.000Z | #ifndef SRC_BENCHMARKS_SIGNALSBENCHMARKS_HPP
#define SRC_BENCHMARKS_SIGNALSBENCHMARKS_HPP
// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <benchmarks/BenchmarkClass.hpp>
#include <benchmarks/utils/Storage.hpp>
namespace benchmarks
{
template < typename SignalsDesc_ >
class SignalBenchmarks : public BenchmarksClass
{
using SignalType = typename SignalsDesc_::SignalType;
using HandlerType = typename SignalsDesc_::HandlerType;
using ConnectionType = typename SignalsDesc_::ConnectionType;
public:
SignalBenchmarks()
: BenchmarksClass("signal")
{
AddBenchmark<>("createEmpty", &SignalBenchmarks::CreateEmpty);
AddBenchmark<>("create", &SignalBenchmarks::Create);
AddBenchmark<>("handlerSize", &SignalBenchmarks::HandlerSize);
AddBenchmark<int64_t>("invoke", &SignalBenchmarks::Invoke, {"numSlots"});
AddBenchmark<int64_t>("connect", &SignalBenchmarks::Connect, {"numSlots"});
}
private:
static void CreateEmpty(BenchmarkContext& context)
{
const auto n = context.GetIterationsCount();
StorageArray<SignalType> s(n);
context.Profile("create", n, [&]{ s.Construct(); });
context.MeasureMemory("signal", n);
context.Profile("destroy", n, [&]{ s.Destruct(); });
}
static void Create(BenchmarkContext& context)
{
const auto n = context.GetIterationsCount();
StorageArray<SignalType> s(n);
s.Construct();
s.ForEach([](SignalType& s){ ConnectionType(s.connect(SignalsDesc_::MakeHandler())); s(); });
context.MeasureMemory("signal", n);
context.Profile("destroy", n, [&]{ s.Destruct(); });
}
static void HandlerSize(BenchmarkContext& context)
{
HandlerType handler = SignalsDesc_::MakeHandler();
SignalType s;
StorageArray<ConnectionType> c(context.GetIterationsCount());
c.Construct([&]{ return s.connect(handler); });
context.MeasureMemory("handler", context.GetIterationsCount());
context.Profile("disconnect", context.GetIterationsCount(), [&]{ c.Destruct(); });
}
static void Invoke(BenchmarkContext& context, int64_t numSlots)
{
const auto n = context.GetIterationsCount();
HandlerType handler = SignalsDesc_::MakeHandler();
SignalType s;
StorageArray<ConnectionType> c(numSlots);
c.Construct([&]{ return s.connect(handler); });
{
auto op = context.Profile("invoke", numSlots * n);
for (int64_t i = 0; i < n; ++i)
s();
}
c.Destruct();
}
static void Connect(BenchmarkContext& context, int64_t numSlots)
{
const auto n = context.GetIterationsCount();
HandlerType handler = SignalsDesc_::MakeHandler();
std::vector<SignalType> s(n);
StorageArray<ConnectionType> c(numSlots * n);
{
auto op = context.Profile("connect", numSlots * n);
for (int64_t j = 0; j < n; ++j)
for (int64_t i = 0; i < numSlots; ++i)
c[i + j * numSlots].Construct(s[j].connect(handler));
}
context.Profile("disconnect", numSlots * n, [&]{ c.Destruct(); });
}
};
}
#endif
| 37.226087 | 172 | 0.613174 | [
"vector"
] |
7689494d6fce83797e2ffccd862925985d9d7824 | 470 | cpp | C++ | contests/Codeforces Round #552 Div 3/Restoring_three_numbers.cpp | Razdeep/Codeforces-Solutions | e808575219ec15bc07720d6abafe3c4c8df036f4 | [
"MIT"
] | 2 | 2020-08-27T18:21:04.000Z | 2020-08-30T13:24:39.000Z | contests/Codeforces Round #552 Div 3/Restoring_three_numbers.cpp | Razdeep/Codeforces-Solutions | e808575219ec15bc07720d6abafe3c4c8df036f4 | [
"MIT"
] | null | null | null | contests/Codeforces Round #552 Div 3/Restoring_three_numbers.cpp | Razdeep/Codeforces-Solutions | e808575219ec15bc07720d6abafe3c4c8df036f4 | [
"MIT"
] | null | null | null | // https://codeforces.com/contest/1154/problem/A
#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
vector<int> arr(4);
for (int i = 0; i < 4; i++)
cin >> arr[i];
sort(all(arr));
int last = arr[arr.size() - 1];
for (int i = 0; i <= 2; i++)
cout << last - arr[i] << " ";
cout << endl;
return 0;
} | 22.380952 | 48 | 0.529787 | [
"vector"
] |
768ac5e8741febfb07e0b312756744e9dcadc3b4 | 9,173 | cpp | C++ | MetaheuristicsCPP.Evaluations/BinaryBiObjectiveEvaluations.cpp | kommar/metaheuristics-lab | 6fce305b1f347eae44ac615a474d96b497264141 | [
"MIT"
] | null | null | null | MetaheuristicsCPP.Evaluations/BinaryBiObjectiveEvaluations.cpp | kommar/metaheuristics-lab | 6fce305b1f347eae44ac615a474d96b497264141 | [
"MIT"
] | null | null | null | MetaheuristicsCPP.Evaluations/BinaryBiObjectiveEvaluations.cpp | kommar/metaheuristics-lab | 6fce305b1f347eae44ac615a474d96b497264141 | [
"MIT"
] | null | null | null | #include "BinaryBiObjectiveEvaluations.h"
using namespace Evaluations;
CBinaryBiObjectiveEvaluation::CBinaryBiObjectiveEvaluation(IEvaluation<bool, double> *pcEvaluation0, IEvaluation<bool, double> *pcEvaluation1)
: CBiObjectiveEvaluation<bool>(pcEvaluation0, pcEvaluation1)
{
}//CBinaryBiObjectiveEvaluation::CBinaryBiObjectiveEvaluation(IEvaluation<bool, double> *pcEvaluation0, IEvaluation<bool, double> *pcEvaluation1)
CBinaryZeroMaxOneMaxEvaluation::CBinaryZeroMaxOneMaxEvaluation(int iSize)
: CBinaryBiObjectiveEvaluation(new CBinaryZeroMaxEvaluation(iSize), new CBinaryOneMaxEvaluation(iSize))
{
v_fill_optimal_pareto_front();
}//CBinaryZeroMaxOneMaxEvaluation::CBinaryZeroMaxOneMaxEvaluation(int iSize)
void CBinaryZeroMaxOneMaxEvaluation::v_fill_optimal_pareto_front()
{
for (int i = 0; i <= iGetSize(); i++)
{
v_optimal_pareto_front.push_back(new pair<double, double>(i, iGetSize() - i));
}//for (int i = 0; i <= iGetSize(); i++)
}//void CBinaryZeroMaxOneMaxEvaluation::v_fill_optimal_pareto_front()
CBinaryTrapInvTrapEvaluation::CBinaryTrapInvTrapEvaluation(int iBlockSize, int iNumberOfBlocks)
: CBinaryBiObjectiveEvaluation(new CBinaryStandardDeceptiveConcatenationEvaluation(iBlockSize, iNumberOfBlocks), new CBinaryInverseStandardDeceptiveConcatenationEvaluation(iBlockSize, iNumberOfBlocks))
{
pc_trap = dynamic_cast<CBinaryStandardDeceptiveConcatenationEvaluation*>(pc_evaluation_0);
v_fill_optimal_pareto_front();
}//CBinaryTrapInvTrapEvaluation::CBinaryTrapInvTrapEvaluation(int iBlockSize, int iNumberOfBlocks)
void CBinaryTrapInvTrapEvaluation::v_fill_optimal_pareto_front()
{
for (int i = 0; i <= pc_trap->iGetNumberOfBlocks(); i++)
{
double d_objective_0 = (pc_trap->iGetNumberOfBlocks() - i) * (pc_trap->iGetBlockSize() - 1) + i * pc_trap->iGetBlockSize();
double d_objective_1 = (pc_trap->iGetNumberOfBlocks() - i) * pc_trap->iGetBlockSize() + i * (pc_trap->iGetBlockSize() - i);
v_optimal_pareto_front.push_back(new pair<double, double>(d_objective_0, d_objective_1));
}//for (int i = 0; i <= pc_trap->iGetNumberOfBlocks(); i++)
}//void CBinaryTrapInvTrapEvaluation::v_fill_optimal_pareto_front()
CBinaryLOTZEvaluation::CBinaryLOTZEvaluation(int iSize)
: CBinaryBiObjectiveEvaluation(new CBinaryLeadingOnesEvaluation(iSize), new CBinaryTrailingZerosEvaluation(iSize))
{
v_fill_optimal_pareto_front();
}//CBinaryLOTZEvaluation::CBinaryLOTZEvaluation(int iSize)
void CBinaryLOTZEvaluation::v_fill_optimal_pareto_front()
{
for (int i = 0; i <= iGetSize(); i++)
{
v_optimal_pareto_front.push_back(new pair<double, double>(i, iGetSize() - i));
}//for (int i = 0; i <= iGetSize(); i++)
}//void CBinaryLOTZEvaluation::v_fill_optimal_pareto_front()
CBinaryMOKnapsackEvaluation::CBinaryMOKnapsackEvaluation(EBinaryBiObjectiveKnapsackInstance eInstance)
: CBinaryBiObjectiveEvaluation(new CBinaryKnapsackEvaluation(eInstance, 0), new CBinaryKnapsackEvaluation(eInstance, 1))
{
pc_knapsack_0 = dynamic_cast<CBinaryKnapsackEvaluation*>(pc_evaluation_0);
pc_knapsack_1 = dynamic_cast<CBinaryKnapsackEvaluation*>(pc_evaluation_1);
v_load_optimal_pareto_front(eInstance);
v_fill_repairing_order();
}//CBinaryMOKnapsackEvaluation::CBinaryMOKnapsackEvaluation(EBinaryBiObjectiveKnapsackInstance eInstance)
pair<double, double> CBinaryMOKnapsackEvaluation::t_evaluate(vector<bool> &vSolution)
{
v_repaired_solution = vSolution;
v_repair(*pc_knapsack_0);
v_repair(*pc_knapsack_1);
return CBinaryBiObjectiveEvaluation::t_evaluate(v_repaired_solution);
}//pair<double, double> CBinaryMOKnapsackEvaluation::t_evaluate(vector<bool> &vSolution)
void CBinaryMOKnapsackEvaluation::v_load_optimal_pareto_front(EBinaryBiObjectiveKnapsackInstance eInstance)
{
string s_optimal_pareto_front_file_path = s_get_optimal_pareto_front_file_path(eInstance);
ifstream f_optimal_pareto_front_file(s_optimal_pareto_front_file_path);
if (!f_optimal_pareto_front_file)
{
throw invalid_argument(s_optimal_pareto_front_file_path + " not found");
}//if (!f_optimal_pareto_front_file)
double d_objective_value_0, d_objective_value_1;
while (!f_optimal_pareto_front_file.eof())
{
f_optimal_pareto_front_file >> d_objective_value_0;
f_optimal_pareto_front_file >> d_objective_value_1;
v_optimal_pareto_front.push_back(new pair<double, double>(d_objective_value_0, d_objective_value_1));
}//while (!f_optimal_pareto_front_file.eof())
f_optimal_pareto_front_file.close();
}//void CBinaryMOKnapsackEvaluation::v_load_optimal_pareto_front(EBinaryBiObjectiveKnapsackInstance eInstance)
string CBinaryMOKnapsackEvaluation::s_get_optimal_pareto_front_file_path(EBinaryBiObjectiveKnapsackInstance eInstance)
{
switch (eInstance)
{
case EBinaryBiObjectiveKnapsackInstance::knapsack_100:
return "EvaluationsInputs\\instances_BO_KP\\knapsack.100.2.pareto.txt";
case EBinaryBiObjectiveKnapsackInstance::knapsack_250:
return "EvaluationsInputs\\instances_BO_KP\\knapsack.250.2.pareto.txt";
case EBinaryBiObjectiveKnapsackInstance::knapsack_500:
return "EvaluationsInputs\\instances_BO_KP\\knapsack.500.2.pareto.txt";
case EBinaryBiObjectiveKnapsackInstance::knapsack_750:
return "EvaluationsInputs\\instances_BO_KP\\knapsack.750.2.pareto.txt";
default:
return "unknown";
}//switch (eInstance)
}//string CBinaryMOKnapsackEvaluation::s_get_optimal_pareto_front_file_path(EBinaryBiObjectiveKnapsackInstance eInstance)
void CBinaryMOKnapsackEvaluation::v_fill_repairing_order()
{
v_repairing_order.resize((size_t)iGetSize());
iota(v_repairing_order.begin(), v_repairing_order.end(), 0);
vector<double> v_ratios(v_repairing_order.size());
for (size_t i = 0; i < v_ratios.size(); i++)
{
v_ratios[i] = pc_knapsack_0->vGetProfits()[i] / pc_knapsack_0->vGetWeights()[i] + pc_knapsack_1->vGetProfits()[i] / pc_knapsack_1->vGetWeights()[i];
}//for (size_t i = 0; i < v_ratios.size(); i++)
sort(v_repairing_order.begin(), v_repairing_order.end(), [&v_ratios](int iIndex0, int iIndex1)
{
return v_ratios[iIndex0] < v_ratios[iIndex1];
});//sort(v_repairing_order.begin(), v_repairing_order.end(), [&v_ratios](int iIndex0, int iIndex1)
}//void CBinaryMOKnapsackEvaluation::v_fill_repairing_order()
void CBinaryMOKnapsackEvaluation::v_repair(CBinaryKnapsackEvaluation &cKnapsack)
{
double d_capacity = cKnapsack.dGetCapacity();
double d_weight_sum = cKnapsack.dCalculateWeight(v_repaired_solution);
int i_index;
for (size_t i = 0; i < v_repairing_order.size() && d_weight_sum > d_capacity; i++)
{
i_index = v_repairing_order[i];
if (v_repaired_solution[i_index])
{
v_repaired_solution[i_index] = false;
d_weight_sum -= cKnapsack.vGetWeights()[i_index];
}//if (v_repaired_solution[i_index])
}//for (size_t i = 0; i < v_repairing_order.size() && d_weight_sum > d_capacity; i++)
}//void CBinaryMOKnapsackEvaluation::v_repair(CBinaryKnapsackEvaluation &cKnapsack)
CBinaryMOMaxCutEvaluation::CBinaryMOMaxCutEvaluation(EBinaryBiObjectiveMaxCutInstance eInstance)
: CBinaryBiObjectiveEvaluation(new CBinaryMaxCutEvaluation(eInstance, 0), new CBinaryMaxCutEvaluation(eInstance, 1))
{
v_load_optimal_pareto_front(eInstance);
}//CBinaryMOMaxCutEvaluation::CBinaryMOMaxCut(EBinaryBiObjectiveMaxCutInstance eInstance)
void CBinaryMOMaxCutEvaluation::v_load_optimal_pareto_front(EBinaryBiObjectiveMaxCutInstance eInstance)
{
string s_optimal_pareto_front_file_path = s_get_optimal_pareto_front_file_path(eInstance);
ifstream f_optimal_pareto_front_file(s_optimal_pareto_front_file_path);
if (!f_optimal_pareto_front_file)
{
throw invalid_argument(s_optimal_pareto_front_file_path + " not found");
}//if (!f_optimal_pareto_front_file)
int i_size;
f_optimal_pareto_front_file >> i_size;
double d_objective_value_0, d_objective_value_1;
for (int i = 0; i < i_size; i++)
{
f_optimal_pareto_front_file >> d_objective_value_0;
f_optimal_pareto_front_file >> d_objective_value_1;
v_optimal_pareto_front.push_back(new pair<double, double>(d_objective_value_0, d_objective_value_1));
}//for (int i = 0; i < i_size; i++)
f_optimal_pareto_front_file.close();
}//void CBinaryMOMaxCutEvaluation::v_load_optimal_pareto_front(EBinaryBiObjectiveMaxCutInstance eInstance)
string CBinaryMOMaxCutEvaluation::s_get_optimal_pareto_front_file_path(EBinaryBiObjectiveMaxCutInstance eInstance)
{
switch (eInstance)
{
case EBinaryBiObjectiveMaxCutInstance::maxcut_instance_6:
return "EvaluationsInputs\\instances_BO_MaxCut\\maxcut_pareto_front_6.txt";
case EBinaryBiObjectiveMaxCutInstance::maxcut_instance_12:
return "EvaluationsInputs\\instances_BO_MaxCut\\maxcut_pareto_front_12.txt";
case EBinaryBiObjectiveMaxCutInstance::maxcut_instance_25:
return "EvaluationsInputs\\instances_BO_MaxCut\\maxcut_pareto_front_25.txt";
case EBinaryBiObjectiveMaxCutInstance::maxcut_instance_50:
return "EvaluationsInputs\\instances_BO_MaxCut\\maxcut_pareto_front_50.txt";
case EBinaryBiObjectiveMaxCutInstance::maxcut_instance_100:
return "EvaluationsInputs\\instances_BO_MaxCut\\maxcut_pareto_front_100.txt";
default:
return "unknown";
}//switch (eInstance)
}//string CBinaryMOMaxCutEvaluation::s_get_optimal_pareto_front_file_path(EBinaryBiObjectiveMaxCutInstance eInstance) | 43.065728 | 202 | 0.817726 | [
"vector"
] |
768e3dea992593bb35e60307e000b1d6fdbccfaf | 394 | hpp | C++ | src/indep_res.hpp | JLRipley314/spherically-symmetric-Z2-edgb | c2311a79d2ec08073541c98f6b06b6f54fbb58e4 | [
"MIT"
] | null | null | null | src/indep_res.hpp | JLRipley314/spherically-symmetric-Z2-edgb | c2311a79d2ec08073541c98f6b06b6f54fbb58e4 | [
"MIT"
] | null | null | null | src/indep_res.hpp | JLRipley314/spherically-symmetric-Z2-edgb | c2311a79d2ec08073541c98f6b06b6f54fbb58e4 | [
"MIT"
] | 2 | 2021-07-06T01:45:19.000Z | 2021-07-30T18:35:09.000Z | #ifndef _INDEP_RES_HPP_
#define _INDEP_RES_HPP_
#include <vector>
/*===========================================================================*/
void compute_indep_res_q(
const int exc_i,
const int nx, const double dx, const double cl,
const std::vector<double> &r_v,
const std::vector<double> &phi_f, const std::vector<double> &phi_q,
std::vector<double> &res_q
);
#endif
| 24.625 | 79 | 0.571066 | [
"vector"
] |
7691f370649ab09fddb70a45a29d95292ce0a22b | 4,112 | hpp | C++ | include/http/Url.hpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 19 | 2017-03-28T02:17:42.000Z | 2021-02-12T03:26:58.000Z | include/http/Url.hpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 3 | 2016-07-14T10:15:06.000Z | 2016-11-22T21:04:01.000Z | include/http/Url.hpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 9 | 2017-10-19T07:15:42.000Z | 2019-09-17T07:08:25.000Z | #pragma once
#include <cstdint>
#include <string>
#include <unordered_map>
#include <stdexcept>
#include <ostream>
#include <vector>
namespace http
{
/**Errors for invalid URL's being parsed or built.*/
class UrlError : public std::runtime_error
{
public:
/**Report a descriptive error about a specific URL string.*/
UrlError(const std::string &url, const std::string &msg)
: std::runtime_error(msg + ": " + url)
{}
};
/**Percent decode a URL fragement.*/
std::string url_decode(const std::string &str);
/**Percent decode a URL query string element, additionally converting '+' to ' '.*/
std::string url_decode_query(const std::string &str);
/**Percent encode a URL path segment.*/
std::string url_encode_path(const std::string &str);
/**Percent encode a URL query string element, additionally converting ' ' to '+'.*/
std::string url_encode_query(const std::string &str);
/**A URL split into its components.*/
class Url
{
public:
/**Container of query parameter values for a specific named parameter.*/
typedef std::vector<std::string> QueryParamList;
/**Map container of query parameters.*/
typedef std::unordered_map<std::string, QueryParamList> QueryParams;
/**HTTP request string does not include protocol, host, port, or hash. */
static Url parse_request(const std::string &str);
/**Connection protocol to use. e.g. "http" or "https".*/
std::string protocol;
/**Host name or IP address.*/
std::string host;
/**Port number (e.g. 80 or 443).
* If no port number is explicitly specified, the value is zero.
* To get a port number accounting for default protocol ports, use port_or_default.
*/
uint16_t port;
/**Percent encoded URL path.*/
std::string path;
/**Percent decoded query parameters.
* There may be multiple parameters with the same name. No special meaning is given to
* such parameters.
*/
QueryParams query_params;
Url();
/**True if there is at least one query parameter with a given case sensitive name.*/
bool has_query_param(const std::string &name)const;
/**Get a query parameter value.
* - If there are multiple parameters with the same name, then the first (left-most) one
* is returned.
*
* If it is required to handle multiple parameters use query_param_list.
* - If there is no parameter with the name, then an empty string is returned.
*
* If it is required to tell existance or valuelessness apart, use has_query_param
* or query_param_list.
*/
const std::string &query_param(const std::string &name)const;
/**Gets the list of query parameters with a given name in order (left to right in the URL).
* If there are no parameters with the name, then an empty list is returned.
*/
const QueryParamList& query_param_list(const std::string &name)const;
/**Encodes the path onwards for use in a HTTP request message.*/
std::string encode_request()const;
/**Write encode_request to the stream.*/
void encode_request(std::ostream &os)const;
/**Write the full URL string to a stream.*/
void encode(std::ostream &os)const;
/**Get the full URL string.*/
std::string encode()const;
/**If port is non-zero, else return the default port for protocol if known, else throw.*/
uint16_t port_or_default()const
{
if (port) return port;
if (protocol == "http") return 80;
if (protocol == "https") return 443;
throw std::runtime_error("No known default port for " + protocol);
}
};
inline std::string to_string(const Url &url) { return url.encode(); }
inline std::ostream& operator << (std::ostream &os, const Url &url)
{
url.encode(os);
return os;
}
}
| 38.792453 | 99 | 0.620136 | [
"vector"
] |
7698bb13cea19cf4d180f818ceeff9e89a808d6b | 100,991 | cpp | C++ | ABY/src/abycore/circuit/booleancircuits.cpp | encryptogroup/VASA | 828a6a7e07e5089b9185b677d6c5ae7fb97c7ec2 | [
"MIT"
] | 1 | 2021-12-19T08:54:53.000Z | 2021-12-19T08:54:53.000Z | ABY/src/abycore/circuit/booleancircuits.cpp | encryptogroup/VASA | 828a6a7e07e5089b9185b677d6c5ae7fb97c7ec2 | [
"MIT"
] | null | null | null | ABY/src/abycore/circuit/booleancircuits.cpp | encryptogroup/VASA | 828a6a7e07e5089b9185b677d6c5ae7fb97c7ec2 | [
"MIT"
] | null | null | null | /**
\file booleancircuits.cpp
\author michael.zohner@ec-spride.de
\copyright ABY - A Framework for Efficient Mixed-protocol Secure Two-party Computation
Copyright (C) 2019 Engineering Cryptographic Protocols Group, TU Darmstadt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ABY is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
\brief A collection of boolean circuits for boolean and yao sharing in the ABY framework
*/
#include "booleancircuits.h"
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#ifdef HW_DEBUG
#include <memory>
#endif
void BooleanCircuit::Init() {
m_nShareBitLen = 1;
m_nNumANDSizes = 1;
m_vANDs = (non_lin_vec_ctx*) malloc(sizeof(non_lin_vec_ctx) * m_nNumANDSizes);
m_vANDs[0].bitlen = 1;
m_vANDs[0].numgates = 0;
//Instantiate with regular 1 output AND gate
m_vTTlens.resize(1);
m_vTTlens[0].resize(1);
m_vTTlens[0][0].resize(1);
m_vTTlens[0][0][0].tt_len = 4;
m_vTTlens[0][0][0].numgates = 0;
m_vTTlens[0][0][0].out_bits = 1;
//m_vTTlens = (non_lin_vec_ctx*) malloc(sizeof(tt_lens_ctx) * m_nNumTTSizes);
m_nGates = 0;
if (m_eContext == S_BOOL) {
m_nRoundsAND = 1;
m_nRoundsXOR = 0;
m_nRoundsIN.resize(2, 1);
m_nRoundsOUT.resize(3, 1);
} else if(m_eContext == S_SPLUT) {
m_nRoundsAND = 1;
m_nRoundsXOR = 0;
m_nRoundsIN.resize(2, 1);
m_nRoundsOUT.resize(3, 1);
} else if (m_eContext == S_YAO || m_eContext == S_YAO_REV) {
m_nRoundsAND = 0;
m_nRoundsXOR = 0;
m_nRoundsIN.resize(2);
m_nRoundsIN[0] = 1;
m_nRoundsIN[1] = 2;
m_nRoundsOUT.resize(3, 1);
m_nRoundsOUT[1] = 0; //the client already holds the output bits from the start
} else {
std::cerr << "Sharing type not implemented for Boolean circuit" << std::endl;
std::exit(EXIT_FAILURE);
}
m_nB2YGates = 0;
m_nA2YGates = 0;
m_nNumXORVals = 0;
m_nNumXORGates = 0;
m_nYSwitchGates = 0;
m_nUNIVGates = 0;
}
/*void BooleanCircuit::UpdateANDsOnLayers() {
}*/
void BooleanCircuit::Cleanup() {
//TODO implement completely
free(m_vANDs);
// should not be necessary:
// m_vTTlens[0][0].clear();
// m_vTTlens[0].clear();
// m_vTTlens.clear();
// m_nRoundsIN.clear();
// m_nRoundsOUT.clear();
}
uint32_t BooleanCircuit::PutANDGate(uint32_t inleft, uint32_t inright) {
uint32_t gateid;
if(m_eContext != S_SPLUT) {
gateid = m_cCircuit->PutPrimitiveGate(G_NON_LIN, inleft, inright, m_nRoundsAND);
if (m_eContext == S_BOOL) {
UpdateInteractiveQueue(gateid);
} else if (m_eContext == S_YAO || m_eContext == S_YAO_REV) {
//if context == YAO, no communication round is required
UpdateLocalQueue(gateid);
} else {
std::cerr << "Context not recognized" << std::endl;
}
if (m_vGates[gateid].nvals != INT_MAX) {
m_vANDs[0].numgates += m_vGates[gateid].nvals;
} else {
std::cerr << "INT_MAX not allowed as nvals" << std::endl;
}
} else {
std::vector<uint32_t> in(2);
uint64_t andttable=8;
in[0] = inleft;
in[1] = inright;
gateid = PutTruthTableGate(in, 1, &andttable);
}
return gateid;
}
std::vector<uint32_t> BooleanCircuit::PutANDGate(std::vector<uint32_t> inleft, std::vector<uint32_t> inright) {
PadWithLeadingZeros(inleft, inright);
uint32_t resultbitlen = inleft.size();
std::vector<uint32_t> out(resultbitlen);
for (uint32_t i = 0; i < resultbitlen; i++){
out[i] = PutANDGate(inleft[i], inright[i]);
}
return out;
}
share* BooleanCircuit::PutANDGate(share* ina, share* inb) {
return new boolshare(PutANDGate(ina->get_wires(), inb->get_wires()), this);
}
uint32_t BooleanCircuit::PutVectorANDGate(uint32_t choiceinput, uint32_t vectorinput) {
if (m_eContext != S_BOOL) {
std::cerr << "Building a vector AND gate is currently only possible for GMW!" << std::endl;
//TODO: prevent error by putting repeater gate on choiceinput and an AND gate between choiceinput and vectorinput
return 0;
}
uint32_t gateid = m_cCircuit->PutNonLinearVectorGate(G_NON_LIN_VEC, choiceinput, vectorinput, m_nRoundsAND);
UpdateInteractiveQueue(gateid);
//std::cout << "Putting a vector and gate between a gate with " << m_vGates[choiceinput].nvals << " and " <<
// m_vGates[vectorinput].nvals << ", res gate has nvals = " << m_vGates[gateid].nvals << std::endl;
if (m_vGates[gateid].nvals != INT_MAX) {
//Update vector AND sizes
//find location of vector AND bitlength
//int pos = FindBitLenPositionInVec(m_vGates[gateid].nvals, m_vANDs, m_nNumANDSizes);
int pos = FindBitLenPositionInVec(m_vGates[gateid].gs.avs.bitlen, m_vANDs, m_nNumANDSizes);
if (pos == -1) {
//Create new entry for the bit-length
m_nNumANDSizes++;
non_lin_vec_ctx* temp = (non_lin_vec_ctx*) malloc(sizeof(non_lin_vec_ctx) * m_nNumANDSizes);
memcpy(temp, m_vANDs, (m_nNumANDSizes - 1) * sizeof(non_lin_vec_ctx));
free(m_vANDs);
m_vANDs = temp;
//m_vANDs[m_nNumANDSizes - 1].bitlen = m_vGates[gateid].nvals;
m_vANDs[m_nNumANDSizes - 1].bitlen = m_vGates[gateid].gs.avs.bitlen;
m_vANDs[m_nNumANDSizes - 1].numgates = m_vGates[choiceinput].nvals; //1
} else {
//increase number of vector ANDs for this bitlength by one
m_vANDs[pos].numgates+=m_vGates[choiceinput].nvals;
}
}
return gateid;
}
share* BooleanCircuit::PutXORGate(share* ina, share* inb) {
return new boolshare(PutXORGate(ina->get_wires(), inb->get_wires()), this);
}
uint32_t BooleanCircuit::PutXORGate(uint32_t inleft, uint32_t inright) {
//std::cout << "inleft = " << inleft << ", inright = " << inright << std::endl;
uint32_t gateid = m_cCircuit->PutPrimitiveGate(G_LIN, inleft, inright, m_nRoundsXOR);
UpdateLocalQueue(gateid);
m_nNumXORVals += m_vGates[gateid].nvals;
m_nNumXORGates += 1;
return gateid;
}
std::vector<uint32_t> BooleanCircuit::PutXORGate(std::vector<uint32_t> inleft, std::vector<uint32_t> inright) {
PadWithLeadingZeros(inleft, inright);
uint32_t resultbitlen = inleft.size();
std::vector<uint32_t> out(resultbitlen);
for (uint32_t i = 0; i < resultbitlen; i++){
out[i] = PutXORGate(inleft[i], inright[i]);
}
return out;
}
uint32_t BooleanCircuit::PutINGate(e_role src) {
uint32_t gateid = m_cCircuit->PutINGate(m_eContext, 1, m_nShareBitLen, src, m_nRoundsIN[src]);
UpdateInteractiveQueue(gateid);
switch (src) {
case SERVER:
m_vInputGates[0].push_back(gateid);
m_vInputBits[0] += m_vGates[gateid].nvals;
break;
case CLIENT:
m_vInputGates[1].push_back(gateid);
m_vInputBits[1] += m_vGates[gateid].nvals;
break;
case ALL:
m_vInputGates[0].push_back(gateid);
m_vInputGates[1].push_back(gateid);
m_vInputBits[0] += m_vGates[gateid].nvals;
m_vInputBits[1] += m_vGates[gateid].nvals;
break;
default:
std::cerr << "Role not recognized" << std::endl;
break;
}
return gateid;
}
uint32_t BooleanCircuit::PutSIMDINGate(uint32_t ninvals, e_role src) {
uint32_t gateid = m_cCircuit->PutINGate(m_eContext, ninvals, m_nShareBitLen, src, m_nRoundsIN[src]);
UpdateInteractiveQueue(gateid);
switch (src) {
case SERVER:
m_vInputGates[0].push_back(gateid);
m_vInputBits[0] += m_vGates[gateid].nvals;
break;
case CLIENT:
m_vInputGates[1].push_back(gateid);
m_vInputBits[1] += m_vGates[gateid].nvals;
break;
case ALL:
m_vInputGates[0].push_back(gateid);
m_vInputGates[1].push_back(gateid);
m_vInputBits[0] += m_vGates[gateid].nvals;
m_vInputBits[1] += m_vGates[gateid].nvals;
break;
default:
std::cerr << "Role not recognized" << std::endl;
break;
}
return gateid;
}
share* BooleanCircuit::PutDummyINGate(uint32_t bitlen) {
std::vector<uint32_t> wires(bitlen);
for(uint32_t i = 0; i < bitlen; i++) {
wires[i] = PutINGate((e_role) !m_eMyRole);
}
return new boolshare(wires, this);
}
share* BooleanCircuit::PutDummySIMDINGate(uint32_t nvals, uint32_t bitlen) {
std::vector<uint32_t> wires(bitlen);
for(uint32_t i = 0; i < bitlen; i++) {
wires[i] = PutSIMDINGate(nvals, (e_role) !m_eMyRole);
}
return new boolshare(wires, this);
}
uint32_t BooleanCircuit::PutSharedINGate() {
uint32_t gateid = m_cCircuit->PutSharedINGate(m_eContext, 1, m_nShareBitLen);
UpdateLocalQueue(gateid);
return gateid;
}
uint32_t BooleanCircuit::PutSharedSIMDINGate(uint32_t ninvals) {
uint32_t gateid = m_cCircuit->PutSharedINGate(m_eContext, ninvals, m_nShareBitLen);
UpdateLocalQueue(gateid);
return gateid;
}
uint32_t BooleanCircuit::PutINGate(uint64_t val, e_role role) {
//return PutINGate(nvals, &val, role);
uint32_t gateid = PutINGate(role);
if (role == m_eMyRole) {
//assign value
GATE* gate = &(m_vGates[gateid]);
gate->gs.ishare.inval = (UGATE_T*) calloc(ceil_divide(1 * m_nShareBitLen, sizeof(UGATE_T) * 8), sizeof(UGATE_T));
memcpy(gate->gs.ishare.inval, &val, ceil_divide(1 * m_nShareBitLen, 8));
gate->instantiated = true;
}
return gateid;
}
uint32_t BooleanCircuit::PutSharedINGate(uint64_t val) {
uint32_t gateid = PutSharedINGate();
//assign value
GATE* gate = &(m_vGates[gateid]);
gate->gs.val = (UGATE_T*) calloc(ceil_divide(1 * m_nShareBitLen, sizeof(UGATE_T) * 8), sizeof(UGATE_T));
memcpy(gate->gs.val, &val, ceil_divide(1 * m_nShareBitLen, 8));
gate->instantiated = true;
return gateid;
}
uint32_t BooleanCircuit::PutSIMDINGate(uint32_t nvals, uint64_t val, e_role role) {
//return PutINGate(nvals, &val, role);
uint32_t gateid = PutSIMDINGate(nvals, role);
if (role == m_eMyRole) {
//assign value
GATE* gate = &(m_vGates[gateid]);
gate->gs.ishare.inval = (UGATE_T*) calloc(ceil_divide(nvals * m_nShareBitLen, sizeof(UGATE_T) * 8), sizeof(UGATE_T));
memcpy(gate->gs.ishare.inval, &val, ceil_divide(nvals * m_nShareBitLen, 8));
gate->instantiated = true;
}
return gateid;
}
uint32_t BooleanCircuit::PutSharedSIMDINGate(uint32_t nvals, uint64_t val) {
//return PutINGate(nvals, &val, role);
uint32_t gateid = PutSharedSIMDINGate(nvals);
//assign value
GATE* gate = &(m_vGates[gateid]);
gate->gs.val = (UGATE_T*) calloc(ceil_divide(nvals * m_nShareBitLen, sizeof(UGATE_T) * 8), sizeof(UGATE_T));
memcpy(gate->gs.val, &val, ceil_divide(nvals * m_nShareBitLen, 8));
gate->instantiated = true;
return gateid;
}
uint32_t BooleanCircuit::PutYaoSharedSIMDINGate(uint32_t nvals, yao_fields keys) {
uint32_t gateid = PutSharedSIMDINGate(nvals);
//assign value
GATE* gate = &(m_vGates[gateid]);
//TODO: fixed to 128-bit security atm. CHANGE
uint8_t keybytelen = ceil_divide(128, 8);
if(m_eMyRole == SERVER) {
gate->gs.yinput.outKey[0] = (uint8_t*) malloc(keybytelen * nvals);
gate->gs.yinput.outKey[1] = (uint8_t*) malloc(keybytelen * nvals);
memcpy(gate->gs.yinput.outKey[0], keys.outKey[0], keybytelen * nvals);
memcpy(gate->gs.yinput.outKey[1], keys.outKey[1], keybytelen * nvals);
gate->gs.yinput.pi = (uint8_t*) malloc(nvals);
memcpy(gate->gs.yinput.pi, keys.pi, nvals);
} else {
gate->gs.yval = (uint8_t*) malloc(keybytelen * nvals);
memcpy(gate->gs.yval, keys.outKey[0], keybytelen * nvals);
}
gate->instantiated = true;
return gateid;
}
share* BooleanCircuit::PutYaoSharedSIMDINGate(uint32_t nvals, yao_fields* keys, uint32_t bitlen) {
share* shr = new boolshare(bitlen, this);
for(uint32_t i = 0; i < bitlen; i++) {
shr->set_wire_id(i, PutYaoSharedSIMDINGate(nvals, keys[i]));
}
return shr;
}
uint32_t BooleanCircuit::PutOUTGate(uint32_t parentid, e_role dst) {
uint32_t gateid = m_cCircuit->PutOUTGate(parentid, dst, m_nRoundsOUT[dst]);
UpdateInteractiveQueue(gateid);
switch (dst) {
case SERVER:
m_vOutputGates[0].push_back(gateid);
m_vOutputBits[0] += m_vGates[gateid].nvals;
break;
case CLIENT:
m_vOutputGates[1].push_back(gateid);
m_vOutputBits[1] += m_vGates[gateid].nvals;
break;
case ALL:
m_vOutputGates[0].push_back(gateid);
m_vOutputGates[1].push_back(gateid);
m_vOutputBits[0] += m_vGates[gateid].nvals;
m_vOutputBits[1] += m_vGates[gateid].nvals;
break;
default:
std::cerr << "Role not recognized" << std::endl;
break;
}
return gateid;
}
share* BooleanCircuit::PutOUTGate(share* parent, e_role dst) {
return new boolshare(PutOUTGate(parent->get_wires(), dst), this);
}
std::vector<uint32_t> BooleanCircuit::PutOUTGate(std::vector<uint32_t> parentids, e_role dst) {
std::vector<uint32_t> gateid = m_cCircuit->PutOUTGate(parentids, dst, m_nRoundsOUT[dst]);
//TODO: optimize
for (uint32_t i = 0; i < gateid.size(); i++) {
UpdateInteractiveQueue(gateid[i]);
switch (dst) {
case SERVER:
m_vOutputGates[0].push_back(gateid[i]);
m_vOutputBits[0] += m_vGates[gateid[i]].nvals;
break;
case CLIENT:
m_vOutputGates[1].push_back(gateid[i]);
m_vOutputBits[1] += m_vGates[gateid[i]].nvals;
break;
case ALL:
m_vOutputGates[0].push_back(gateid[i]);
m_vOutputGates[1].push_back(gateid[i]);
m_vOutputBits[0] += m_vGates[gateid[i]].nvals;
m_vOutputBits[1] += m_vGates[gateid[i]].nvals;
break;
default:
std::cerr << "Role not recognized" << std::endl;
break;
}
}
return gateid;
}
std::vector<uint32_t> BooleanCircuit::PutSharedOUTGate(std::vector<uint32_t> parentids) {
std::vector<uint32_t> out = m_cCircuit->PutSharedOUTGate(parentids);
for(uint32_t i = 0; i < out.size(); i++) {
UpdateLocalQueue(out[i]);
}
return out;
}
share* BooleanCircuit::PutSharedOUTGate(share* parent) {
return new boolshare(PutSharedOUTGate(parent->get_wires()), this);
}
share* BooleanCircuit::PutCONSGate(UGATE_T val, uint32_t bitlen) {
return PutSIMDCONSGate(1, val, bitlen);
}
share* BooleanCircuit::PutCONSGate(uint8_t* val, uint32_t bitlen) {
return PutSIMDCONSGate(1, val, bitlen);
}
share* BooleanCircuit::PutCONSGate(uint32_t* val, uint32_t bitlen) {
return PutSIMDCONSGate(1, val, bitlen);
}
share* BooleanCircuit::PutSIMDCONSGate(uint32_t nvals, UGATE_T val, uint32_t bitlen) {
share* shr = new boolshare(bitlen, this);
for(uint32_t i = 0; i < bitlen; ++i) {
shr->set_wire_id(i, PutConstantGate((val >> i) & 1, nvals));
}
return shr;
}
share* BooleanCircuit::PutSIMDCONSGate(uint32_t nvals, uint8_t* val, uint32_t bitlen) {
share* shr = new boolshare(bitlen, this);
for(uint32_t i = 0; i < bitlen; ++i) {
uint32_t shift = i % 8;
shr->set_wire_id(i, PutConstantGate((val[(i / 8)] & (1 << shift)) >> shift, nvals));
}
return shr;
}
share* BooleanCircuit::PutSIMDCONSGate(uint32_t nvals, uint32_t* val, uint32_t bitlen) {
share* shr = new boolshare(bitlen, this);
for(uint32_t i = 0; i < bitlen; ++i) {
uint32_t shift = i % 32;
shr->set_wire_id(i, PutConstantGate((val[(i / 32)] & (1 << shift)) >> shift, nvals));
}
return shr;
}
uint32_t BooleanCircuit::PutConstantGate(UGATE_T val, uint32_t nvals) {
uint32_t gateid = m_cCircuit->PutConstantGate(m_eContext, val, nvals, m_nShareBitLen);
UpdateLocalQueue(gateid);
return gateid;
}
uint32_t BooleanCircuit::PutINVGate(uint32_t parentid) {
uint32_t gateid = m_cCircuit->PutINVGate(parentid);
UpdateLocalQueue(gateid);
return gateid;
}
std::vector<uint32_t> BooleanCircuit::PutINVGate(std::vector<uint32_t> parentid) {
std::vector<uint32_t> out(parentid.size());
for (uint32_t i = 0; i < out.size(); i++)
out[i] = PutINVGate(parentid[i]);
return out;
}
share* BooleanCircuit::PutINVGate(share* parent) {
return new boolshare(PutINVGate(parent->get_wires()), this);
}
uint32_t BooleanCircuit::PutY2BCONVGate(uint32_t parentid) {
std::vector<uint32_t> in(1, parentid);
uint32_t gateid = m_cCircuit->PutCONVGate(in, 1, S_BOOL, m_nShareBitLen);
m_vGates[gateid].depth++;
UpdateLocalQueue(gateid);
//a Y input gate cannot be parent to a Y2B gate. Alternatively, put a Boolean input gate
assert(m_vGates[parentid].type != G_IN);
return gateid;
}
uint32_t BooleanCircuit::PutB2YCONVGate(uint32_t parentid) {
std::vector<uint32_t> in(1, parentid);
uint32_t gateid = m_cCircuit->PutCONVGate(in, 2, S_YAO, m_nShareBitLen);
UpdateInteractiveQueue(gateid);
//treat similar to input gate of client and server
m_nB2YGates += m_vGates[gateid].nvals;
return gateid;
}
uint32_t BooleanCircuit::PutYSwitchRolesGate(uint32_t parentid) {
std::vector<uint32_t> in(1, parentid);
assert(m_eContext == S_YAO || m_eContext == S_YAO_REV);
assert(m_vGates[in[0]].context != m_eContext);
uint32_t gateid = m_cCircuit->PutCONVGate(in, 2, m_eContext, m_nShareBitLen);
UpdateInteractiveQueue(gateid);
//treat similar to input gate of client and server
m_nYSwitchGates += m_vGates[gateid].nvals;
return gateid;
}
std::vector<uint32_t> BooleanCircuit::PutYSwitchRolesGate(std::vector<uint32_t> parentid) {
std::vector<uint32_t> out(parentid.size());
for (uint32_t i = 0; i < parentid.size(); i++) {
out[i] = PutYSwitchRolesGate(parentid[i]);
}
return out;
}
std::vector<uint32_t> BooleanCircuit::PutY2BCONVGate(std::vector<uint32_t> parentid) {
std::vector<uint32_t> out(parentid.size());
for (uint32_t i = 0; i < parentid.size(); i++) {
out[i] = PutY2BCONVGate(parentid[i]);
}
return out;
}
std::vector<uint32_t> BooleanCircuit::PutB2YCONVGate(std::vector<uint32_t> parentid) {
std::vector<uint32_t> out(parentid.size());
for (uint32_t i = 0; i < parentid.size(); i++) {
out[i] = PutB2YCONVGate(parentid[i]);
}
return out;
}
share* BooleanCircuit::PutY2BGate(share* ina) {
return new boolshare(PutY2BCONVGate(ina->get_wires()), this);
}
share* BooleanCircuit::PutB2YGate(share* ina) {
return new boolshare(PutB2YCONVGate(ina->get_wires()), this);
}
share* BooleanCircuit::PutYSwitchRolesGate(share* ina) {
return new boolshare(PutYSwitchRolesGate(ina->get_wires()), this);
}
std::vector<uint32_t> BooleanCircuit::PutA2YCONVGate(std::vector<uint32_t> parentid) {
std::vector<uint32_t> srvshares(m_vGates[parentid[0]].sharebitlen);
std::vector<uint32_t> clishares(m_vGates[parentid[0]].sharebitlen);
for (uint32_t i = 0; i < m_vGates[parentid[0]].sharebitlen; i++) {
srvshares[i] = m_cCircuit->PutCONVGate(parentid, 1, S_YAO, m_nShareBitLen);
m_vGates[srvshares[i]].gs.pos = 2 * i;
m_vGates[srvshares[i]].depth++; //increase depth by 1 since yao is evaluated before arith
UpdateInteractiveQueue(srvshares[i]);
clishares[i] = m_cCircuit->PutCONVGate(parentid, 2, S_YAO, m_nShareBitLen);
m_vGates[clishares[i]].gs.pos = 2 * i + 1;
m_vGates[clishares[i]].depth++; //increase depth by 1 since yao is evaluated before arith
UpdateInteractiveQueue(clishares[i]);
}
m_nA2YGates += m_vGates[parentid[0]].nvals * m_vGates[parentid[0]].sharebitlen;
return PutAddGate(srvshares, clishares);
}
share* BooleanCircuit::PutA2YGate(share* ina) {
return new boolshare(PutA2YCONVGate(ina->get_wires()), this);
}
uint32_t BooleanCircuit::PutStructurizedCombinerGate(std::vector<uint32_t> input, uint32_t pos_start,
uint32_t pos_incr, uint32_t nvals) {
uint32_t gateid = m_cCircuit->PutStructurizedCombinerGate(input, pos_start, pos_incr, nvals);
UpdateLocalQueue(gateid);
return gateid;
}
share* BooleanCircuit::PutStructurizedCombinerGate(share* input, uint32_t pos_start,
uint32_t pos_incr, uint32_t nvals) {
share* out= new boolshare(1, this);
nstructcombgates++;
out->set_wire_id(0, PutStructurizedCombinerGate(input->get_wires(), pos_start, pos_incr, nvals));
return out;
}
uint32_t BooleanCircuit::PutUniversalGate(uint32_t a, uint32_t b, uint32_t op_id) {
uint32_t gateid;
if(m_eContext == S_YAO) { //In case of Yao, put universal gate
gateid = m_cCircuit->PutUniversalGate(a, b, op_id, m_nRoundsAND);
UpdateLocalQueue(gateid);
m_nUNIVGates+=m_vGates[gateid].nvals;
} else if (m_eContext == S_BOOL) { //In case of GMW, replace universal gate by sub-circuit
gateid = PutUniversalGateCircuit(a, b, op_id);
} else {
std::cerr << "Context not recognized in PutUniversalGate" << std::endl;
std::exit(EXIT_FAILURE);
}
return gateid;
}
std::vector<uint32_t> BooleanCircuit::PutUniversalGate(std::vector<uint32_t> a, std::vector<uint32_t> b, uint32_t op_id) {
uint32_t niters = std::min(a.size(), b.size());
std::vector<uint32_t> output(niters);
for(uint32_t i = 0; i < niters; i++) {
output[i] = PutUniversalGate(a[i], b[i], op_id);
}
return output;
}
share* BooleanCircuit::PutUniversalGate(share* a, share* b, uint32_t op_id) {
return new boolshare(PutUniversalGate(a->get_wires(), b->get_wires(), op_id), this);
}
uint32_t BooleanCircuit::PutCallbackGate(std::vector<uint32_t> in, uint32_t rounds, void (*callback)(GATE*, void*),
void* infos, uint32_t nvals) {
uint32_t gateid = m_cCircuit->PutCallbackGate(in, rounds, callback, infos, nvals);
if(rounds > 0) {
UpdateInteractiveQueue(gateid);
} else {
UpdateLocalQueue(gateid);
}
return gateid;
}
share* BooleanCircuit::PutCallbackGate(share* in, uint32_t rounds, void (*callback)(GATE*, void*),
void* infos, uint32_t nvals) {
return new boolshare(PutCallbackGate(in->get_wires(), rounds, callback, infos, nvals), this);
}
/*uint64_t* transposeTT(uint32_t dima, uint32_t dimb, uint64_t* ttable) {
uint32_t longbits = sizeof(uint64_t) * 8;
uint64_t* newtt = (uint64_t*) calloc(bits_in_bytes(dima * dimb), sizeof(uint8_t));
std::cout << "dima = " << dima << ", dimb = " << dimb << std::endl;
std::cout << "Before Transposing: " << (hex) << std::endl;
for(uint32_t i = 0; i < ceil_divide(dima * dimb, longbits); i++) {
std::cout << ttable[i] << " ";
}
std::cout << (dec) << std::endl;
for(uint32_t i = 0; i < dima; i++) {
for(uint32_t j = 0; j < dimb; j++) {
uint32_t idxsrc = (i * dimb + j);
uint32_t idxdst = (j * dima + i);
newtt[idxdst / longbits] |= (((ttable[idxsrc / longbits] >> (idxsrc % longbits)) & 0x01) << (idxdst % longbits));
}
}
std::cout << "After Transposing: " << (hex) << std::endl;
for(uint32_t i = 0; i < ceil_divide(dima * dimb, longbits); i++) {
std::cout << newtt[i] << " ";
}
std::cout << (dec) << std::endl;
return newtt;
}*/
std::vector<uint32_t> BooleanCircuit::PutTruthTableMultiOutputGate(std::vector<uint32_t> in, uint32_t out_bits,
uint64_t* ttable) {
//assert(m_eContext == S_BOOL_NO_MT);
//uint32_t tmpgate = m_cCircuit->PutTruthTableGate(in, 1, out_bits, ttable);
//UpdateInteractiveQueue(tmpgate);
//Transpose truth table
//ttable = transposeTT(1<<in.size(), out_bits, ttable);
uint32_t tmpgate = PutTruthTableGate(in, out_bits, ttable);
std::vector<uint32_t> bitlens(out_bits, m_vGates[in[0]].nvals);
//assert(out_bits <= 8);
std::vector<uint32_t> output = m_cCircuit->PutSplitterGate(tmpgate, bitlens);
for(uint32_t i = 0; i < output.size(); i++) {
UpdateLocalQueue(output[i]);
}
return output;
}
share* BooleanCircuit::PutTruthTableMultiOutputGate(share* in, uint32_t output_bitlen, uint64_t* ttable) {
return new boolshare(PutTruthTableMultiOutputGate(in->get_wires(), output_bitlen, ttable), this);
}
uint32_t BooleanCircuit::PutTruthTableGate(std::vector<uint32_t> in, uint32_t out_bits, uint64_t* ttable) {
assert(m_eContext == S_SPLUT || m_eContext == S_BOOL);
uint32_t gateid = m_cCircuit->PutTruthTableGate(in, 1, out_bits, ttable);
UpdateTruthTableSizes(1<<in.size(), gateid, out_bits);
UpdateInteractiveQueue(gateid);
return gateid;
}
share* BooleanCircuit::PutTruthTableGate(share* in, uint64_t* ttable) {
boolshare* out = new boolshare(1, this);
out->set_wire_id(0, PutTruthTableGate(in->get_wires(), 1, ttable));
return out;
}
//check if the len exists, otherwise allocate new and update
void BooleanCircuit::UpdateTruthTableSizes(uint32_t len, uint32_t gateid, uint32_t out_bits) {
//check depth and resize if required
uint32_t depth = m_vGates[gateid].depth;
uint32_t nvals = m_vGates[gateid].nvals/out_bits;
if(depth >= m_vTTlens.size()) {
uint32_t old_depth = m_vTTlens.size();
uint32_t nlens = m_vTTlens[0].size();
m_vTTlens.resize(depth+1);
//copy old values from 0-pos
for(uint32_t i = old_depth; i < m_vTTlens.size(); i++) {
m_vTTlens[i].resize(nlens);
for(uint32_t j = 0; j < nlens; j++) {
uint32_t nouts = m_vTTlens[0][j].size();
m_vTTlens[i][j].resize(nouts);
for(uint32_t k = 0; k < nouts; k++) {
m_vTTlens[i][j][k].numgates = 0;
m_vTTlens[i][j][k].tt_len = m_vTTlens[0][j][k].tt_len;
m_vTTlens[i][j][k].out_bits = m_vTTlens[0][j][k].out_bits;
}
}
}
}
//check whether the address for the input sizes already exist
bool ins_exist = false;
bool outs_exist = false;
uint32_t id;
for(uint32_t i = 0; i < m_vTTlens[0].size() && !ins_exist; i++) {
if(len == m_vTTlens[depth][i][0].tt_len) {
//check whether the bitlen already exists for the input size
ins_exist = true;
id = i;
for(uint32_t j = 0; j < m_vTTlens[depth][i].size() && !outs_exist; j++) {
if(m_vTTlens[depth][i][j].out_bits == out_bits) {
outs_exist = true;
m_vTTlens[depth][i][j].numgates += nvals;
//In case of OP-LUT, also save the truth table which is needed in the setup phase
if(m_eContext == S_BOOL) {
for(uint32_t n = 0; n < nvals; n++) {
m_vTTlens[depth][i][j].ttable_values.push_back(m_vGates[gateid].gs.tt.table);
}
}
}
}
}
}
//the input size does not exist, create new one!
if(!ins_exist) {
uint32_t old_in_lens = m_vTTlens[0].size();
for(uint32_t i = 0; i < m_vTTlens.size(); i++) {
m_vTTlens[i].resize(old_in_lens+1);
m_vTTlens[i][old_in_lens].resize(1);
m_vTTlens[i][old_in_lens][0].tt_len = len;
m_vTTlens[i][old_in_lens][0].numgates = 0;
m_vTTlens[i][old_in_lens][0].out_bits = out_bits;
}
//m_vTTlens[depth][old_lens].tt_len = len;//should work without this too
m_vTTlens[depth][old_in_lens][0].numgates = nvals;
//In case of OP-LUT, also save the truth table which is needed in the setup phase
if(m_eContext == S_BOOL) {
for(uint32_t n = 0; n < nvals; n++) {
m_vTTlens[depth][old_in_lens][0].ttable_values.push_back(m_vGates[gateid].gs.tt.table);
}
}
outs_exist = true;
}
//the out size do not exist; create new
if(!outs_exist) {
uint32_t old_out_lens = m_vTTlens[0][id].size();
for(uint32_t i = 0; i < m_vTTlens.size(); i++) {
m_vTTlens[i][id].resize(old_out_lens+1);
m_vTTlens[i][id][old_out_lens].tt_len = len;
m_vTTlens[i][id][old_out_lens].numgates = 0;
m_vTTlens[i][id][old_out_lens].out_bits = out_bits;
}
//m_vTTlens[depth][id][old_out_lens].tt_len = len;//should work without this too
m_vTTlens[depth][id][old_out_lens].numgates = nvals;
//In case of OP-LUT, also save the truth table which is needed in the setup phase
if(m_eContext == S_BOOL) {
for(uint32_t n = 0; n < nvals; n++) {
m_vTTlens[depth][id][old_out_lens].ttable_values.push_back(m_vGates[gateid].gs.tt.table);
}
}
outs_exist = true;
}
}
//enqueue interactive gate queue
void BooleanCircuit::UpdateInteractiveQueue(uint32_t gateid) {
if (m_vGates[gateid].depth + 1 > m_vInteractiveQueueOnLvl.size()) {
m_vInteractiveQueueOnLvl.resize(m_vGates[gateid].depth + 1);
if (m_vGates[gateid].depth + 1 > m_nMaxDepth) {
m_nMaxDepth = m_vGates[gateid].depth + 1;
}
}
m_vInteractiveQueueOnLvl[m_vGates[gateid].depth].push_back(gateid);
m_nGates++;
}
//enqueue locally evaluated gate queue
void BooleanCircuit::UpdateLocalQueue(uint32_t gateid) {
if (m_vGates[gateid].depth + 1 > m_vLocalQueueOnLvl.size()) {
//std::cout << "increasing size of local queue" << std::endl;
m_vLocalQueueOnLvl.resize(m_vGates[gateid].depth + 1);
if (m_vGates[gateid].depth + 1 > m_nMaxDepth) {
m_nMaxDepth = m_vGates[gateid].depth + 1;
}
}
m_vLocalQueueOnLvl[m_vGates[gateid].depth].push_back(gateid);
m_nGates++;
}
share* BooleanCircuit::PutLeftShifterGate(share* in, uint32_t pos) {
return new boolshare(PutLeftShifterGate(in->get_wires(), in->get_max_bitlength(), pos, in->get_nvals()), this);
}
//shift val by pos positions to the left and fill lower wires with zeros
std::vector<uint32_t> BooleanCircuit::PutLeftShifterGate(std::vector<uint32_t> val, uint32_t max_bitlen, uint32_t pos, uint32_t nvals) {
assert(pos < max_bitlen); // cannot shift beyond last bit
uint32_t zerogate = PutConstantGate(0, nvals);
std::vector<uint32_t> out(pos, zerogate);
uint32_t newsize = pos + val.size();
uint32_t extra_bits = newsize > max_bitlen ? (newsize - max_bitlen) : 0;
out.reserve(newsize - extra_bits);
out.insert(out.end(), val.cbegin(), val.cend() - extra_bits);
return out;
}
// Builds a universal gate that output op_id depending on the circuit
uint32_t BooleanCircuit::PutUniversalGateCircuit(uint32_t a, uint32_t b, uint32_t op_id) {
uint32_t nvals = std::max(m_vGates[a].nvals, m_vGates[b].nvals);
uint32_t c0 = PutConstantGate(op_id & 0x01, nvals);
uint32_t c1 = PutConstantGate((op_id>>1) & 0x01, nvals);
uint32_t c2 = PutConstantGate((op_id>>2) & 0x01, nvals);
uint32_t c3 = PutConstantGate((op_id>>3) & 0x01, nvals);
uint32_t c0c1 = PutXORGate(c0, c1);
uint32_t c2c3 = PutXORGate(c2, c3);
uint32_t bc0c1 = PutANDGate(b, c0c1);
uint32_t bc2c3 = PutANDGate(b, c2c3);
uint32_t o0 = PutXORGate(c0, bc0c1);
uint32_t o1 = PutXORGate(c2, bc2c3);
uint32_t o0o1 = PutXORGate(o0, o1);
uint32_t ao0o1 = PutANDGate(a, o0o1);
return PutXORGate(o0, ao0o1);
}
share* BooleanCircuit::PutADDGate(share* ina, share* inb) {
//also output the carry of the result as long as the additional carry does not exceed the maximum bit length of the higher of both inputs
bool carry = std::max(ina->get_bitlength(), inb->get_bitlength()) < std::max(ina->get_max_bitlength(), inb->get_max_bitlength());
return new boolshare(PutAddGate(ina->get_wires(), inb->get_wires(), carry), this);
}
std::vector<uint32_t> BooleanCircuit::PutAddGate(std::vector<uint32_t> left, std::vector<uint32_t> right, BOOL bCarry) {
PadWithLeadingZeros(left, right);
if (m_eContext == S_BOOL) {
return PutDepthOptimizedAddGate(left, right, bCarry);
} if (m_eContext == S_SPLUT) {
return PutLUTAddGate(left, right, bCarry);
} else {
return PutSizeOptimizedAddGate(left, right, bCarry);
}
}
//a + b, do we need a carry?
std::vector<uint32_t> BooleanCircuit::PutSizeOptimizedAddGate(std::vector<uint32_t> a, std::vector<uint32_t> b, BOOL bCarry) {
// left + right mod (2^Rep)
// Construct C[i] gates
PadWithLeadingZeros(a, b);
uint32_t inputbitlen = a.size();// + (!!bCarry);
std::vector<uint32_t> C(inputbitlen);
uint32_t axc, bxc, acNbc;
C[0] = PutXORGate(a[0], a[0]);//PutConstantGate(0, m_vGates[a[0]].nvals); //the second parameter stands for the number of vals
uint32_t i = 0;
for (; i < inputbitlen - 1; i++) {
//===================
// New Gates
// a[i] xor c[i]
axc = PutXORGate(a[i], C[i]);
// b[i] xor c[i]
bxc = PutXORGate(b[i], C[i]);
// axc AND bxc
acNbc = PutANDGate(axc, bxc);
// C[i+1]
C[i + 1] = PutXORGate(C[i], acNbc);
}
#ifdef ZDEBUG
std::cout << "Finished carry generation" << std::endl;
#endif
if (bCarry) {
axc = PutXORGate(a[i], C[i]);
// b[i] xor c[i]
bxc = PutXORGate(b[i], C[i]);
// axc AND bxc
acNbc = PutANDGate(axc, bxc);
}
#ifdef ZDEBUG
std::cout << "Finished additional carry generation" << std::endl;
#endif
// Construct a[i] xor b[i] gates
std::vector<uint32_t> AxB(inputbitlen);
for (uint32_t i = 0; i < inputbitlen; i++) {
// a[i] xor b[i]
AxB[i] = PutXORGate(a[i], b[i]);
}
#ifdef ZDEBUG
std::cout << "Finished parity on inputs" << std::endl;
#endif
// Construct Output gates of Addition
std::vector<uint32_t> out(inputbitlen + (!!bCarry));
for (uint32_t i = 0; i < inputbitlen; i++) {
out[i] = PutXORGate(C[i], AxB[i]);
}
#ifdef ZDEBUG
std::cout << "Finished parity on inputs xor carries" << std::endl;
#endif
if (bCarry)
out[inputbitlen] = PutXORGate(C[i], acNbc);
#ifdef ZDEBUG
std::cout << "Finished parity on additional carry and inputs" << std::endl;
#endif
return out;
}
//TODO: there is a bug when adding 3 and 1 as two 2-bit numbers and expecting a carry
std::vector<uint32_t> BooleanCircuit::PutDepthOptimizedAddGate(std::vector<uint32_t> a, std::vector<uint32_t> b, BOOL bCARRY, bool vector_and) {
PadWithLeadingZeros(a, b);
uint32_t id, inputbitlen = std::min(a.size(), b.size());
std::vector<uint32_t> out(a.size() + bCARRY);
std::vector<uint32_t> parity(a.size()), carry(inputbitlen), parity_zero(inputbitlen);
uint32_t zerogate = PutConstantGate(0, m_vGates[a[0]].nvals);
share* zero_share = new boolshare(2, this);
share* ina = new boolshare(2, this);
share* sel = new boolshare(1, this);
share* s_out = new boolshare(2, this);
zero_share->set_wire_id(0, zerogate);
zero_share->set_wire_id(1, zerogate);
for (uint32_t i = 0; i < inputbitlen; i++) { //0-th layer
parity[i] = PutXORGate(a[i], b[i]);
parity_zero[i] = parity[i];
carry[i] = PutANDGate(a[i], b[i]);
}
for (uint32_t i = 1; i <= (uint32_t) ceil(log(inputbitlen) / log(2)); i++) {
for (uint32_t j = 0; j < inputbitlen; j++) {
if (j % (uint32_t) pow(2, i) >= pow(2, (i - 1))) {
id = pow(2, (i - 1)) + pow(2, i) * ((uint32_t) floor(j / (pow(2, i)))) - 1;
if(m_eContext == S_BOOL && vector_and) {
ina->set_wire_id(0, carry[id]);
ina->set_wire_id(1, parity[id]);
sel->set_wire_id(0, parity[j]);
PutMultiMUXGate(&ina, &zero_share, sel, 1, &s_out);
//carry[j] = PutINVGate(PutANDGate(PutINVGate(s_out->get_wire(0)), PutINVGate(carry[j])));
carry[j] = PutXORGate(s_out->get_wire_id(0), carry[j]);
parity[j] = s_out->get_wire_id(1);
} else {
//carry[j] = PutINVGate(PutANDGate(PutINVGate(PutANDGate(parity[j], carry[id])), PutINVGate(carry[j]))); // c = (p and c-1) or c = (((p and c-1) xor 1) and (c xor 1)) xor 1)
carry[j] = PutXORGate(carry[j], PutANDGate(parity[j], carry[id])); // c = c XOR (p and c-1), from ShallowCC
parity[j] = PutANDGate(parity[j], parity[id]);
}
}
}
}
out[0] = parity_zero[0];
for (uint32_t i = 1; i < inputbitlen; i++) {
out[i] = PutXORGate(parity_zero[i], carry[i - 1]);
}
if (bCARRY) //Do I expect a carry in the most significant bit position?
out[inputbitlen] = carry[inputbitlen - 1];
delete zero_share;
delete ina;
delete sel;
delete s_out;
return out;
}
// A carry-save adder
std::vector<std::vector<uint32_t> > BooleanCircuit::PutCarrySaveGate(std::vector<uint32_t> a, std::vector<uint32_t> b, std::vector<uint32_t> c, uint32_t inbitlen, bool carry) {
std::vector<uint32_t> axc(inbitlen);
std::vector<uint32_t> acNbc(inbitlen);
std::vector<std::vector<uint32_t> > out(2);
/*PutPrintValueGate(new boolshare(a, this), "Carry Input A");
PutPrintValueGate(new boolshare(b, this), "Carry Input B");
PutPrintValueGate(new boolshare(c, this), "Carry Input C");*/
for (uint32_t i = 0; i < inbitlen; i++) {
axc[i] = PutXORGate(a[i],c[i]); //i*3 - 2
acNbc[i] = PutANDGate(axc[i], PutXORGate(b[i],c[i])); //2+i*3
}
if(carry) {
out[0].resize(inbitlen+1);
out[0][inbitlen] = PutConstantGate(0, GetNumVals(out[0][0]));
out[1].resize(inbitlen+1);
out[1][inbitlen] = PutXORGate(acNbc[inbitlen-1],c[inbitlen-1]);
} else {
out[0].resize(inbitlen);
out[1].resize(inbitlen);
}
for (uint32_t i = 0; i < inbitlen; i++) {
out[0][i] = PutXORGate(b[i],axc[i]);
}
out[1][0] = PutConstantGate(0, GetNumVals(out[0][0]));
for (uint32_t i = 0; i < inbitlen-1; i++) {
out[1][i+1] = PutXORGate(acNbc[i],c[i]);
}
/*PutPrintValueGate(new boolshare(out[0], this), "Carry Output 0");
PutPrintValueGate(new boolshare(out[1], this), "Carry Output 1");*/
return out;
}
/*
* In implementation of the Brent-Kung adder for the Bool-No-MT sharing. To process the values, 5 LUTs are needed:
* 1) for the inputs, 2) for intermediate carry-forwarding, 3) for critical path on inputs, 4) for the critical path, 5) for the inverse carry tree.
*/
std::vector<uint32_t> BooleanCircuit::PutLUTAddGate(std::vector<uint32_t> a, std::vector<uint32_t> b, BOOL bCARRY) {
uint32_t inputbitlen = std::max(a.size(), b.size());
PadWithLeadingZeros(a, b);
std::vector<uint32_t> out(a.size() + bCARRY);
std::vector<uint32_t> parity(inputbitlen), carry(inputbitlen), parity_zero(inputbitlen), tmp;
std::vector<uint32_t> lut_in(2*inputbitlen);
uint32_t max_ins = 4, processed_ins;
uint32_t n_crit_ins = std::min(inputbitlen, (uint32_t) max_ins);
std::vector<uint32_t> tmpout;
//std::cout << "Building a LUT add gate for " << inputbitlen << " input bits" << std::endl;
//step 1: process the input values and generate carry / parity signals
//compute the parity bits for the zero-th layer. Are needed for the result
for (uint32_t i = 0; i < inputbitlen; i++) { //0-th layer
parity_zero[i] = PutXORGate(a[i], b[i]);
parity[i] = parity_zero[i];
}
lut_in.clear();
lut_in.resize(n_crit_ins*2);
for(uint32_t i = 0; i < n_crit_ins; i++) {
lut_in[2*i] = a[i];
lut_in[2*i+1] = b[i];
}
//process the first bits on the critical path and obtain the carry bits
//std::cout << "building a crit path input gate with nins = " << n_crit_ins << std::endl;
tmp = PutTruthTableMultiOutputGate(lut_in, n_crit_ins, (uint64_t*) m_vLUT_ADD_CRIT_IN[n_crit_ins-1]);
for(uint32_t i = 0; i < tmp.size(); i++) {
carry[i] = tmp[i];
}
//process the remaining input bits to have all carry / parity signals
for(uint32_t i = n_crit_ins; i < inputbitlen; ) {
processed_ins = std::min(inputbitlen - i, max_ins);
//assign values to the LUT
lut_in.clear();
lut_in.resize(2*processed_ins);
//std::cout << "building a standard input gate with nins = " << processed_ins << ", i = " << i << " and first val = " << (hex) << m_vLUT_ADD_IN[processed_ins-1][0] <<(dec)<<
// ", lut_in.size() = " << lut_in.size() << ", expecting nouts = " << m_vLUT_ADD_N_OUTS[processed_ins-1] << std::endl;
//std::cout << "Inputs: ";
for(uint32_t j = 0; j < processed_ins; j++) {
lut_in[2*j] = a[i+j];
lut_in[2*j+1] = b[i+j];
//std::cout << i + j << ", ";
}
//process inputs via LUT and write updated gates into carry / parity vectors
tmp = PutTruthTableMultiOutputGate(lut_in, m_vLUT_ADD_N_OUTS[processed_ins-1], (uint64_t*) m_vLUT_ADD_IN[processed_ins-1]);
//std::cout << ", outputs = " << i;
carry[i] = tmp[0];
if(processed_ins > 1) {
//std::cout << ", " << i+1;
parity[i+1] = tmp[1];
carry[i+1] = tmp[2];
if(processed_ins > 2) {
//std::cout << ", " << i+2;
carry[i+2] = tmp[3];
if(processed_ins > 3) {
//std::cout << ", " << i+3;
parity[i+3] = tmp[4];
carry[i+3] = tmp[5];
}
}
}
//std::cout << std::endl;
i+= processed_ins;
}
//step 2: process the carry / parity signals and forward them in the tree
for(uint32_t d = 1; d < ceil_log2(inputbitlen+1)/2; d++) {
//step 2.1: process the carry signals on the critical path
uint32_t base = 8 * (1<<(2*(d-1)));
uint32_t dist = base/2;
processed_ins = 1+ std::min((inputbitlen - base)/dist, max_ins-2);
//std::cout << "critical intermediate base = " << base << ", dist = " << dist << ", processed_ins = " << processed_ins << std::endl;
lut_in.clear();
lut_in.resize(2*processed_ins+1);
lut_in[0] = carry[(base-1)-dist];
for(uint32_t j = 0; j < processed_ins; j++) {
lut_in[2*j+1] = parity[(base-1)+j*(dist)];
lut_in[2*j+2] = carry[(base-1)+j*(dist)];
}
//std::cout << "building a crit-path lut with " << lut_in.size() << " input wires: " << base-1-dist << ", ";
/*for(uint32_t j = 0; j < processed_ins; j++) {
std::cout << base+j*dist << ", ";
}
std::cout << std::endl;*/
tmp = PutTruthTableMultiOutputGate(lut_in, processed_ins, (uint64_t*) m_vLUT_ADD_CRIT[processed_ins-1]);
for(uint32_t j = 0; j < tmp.size(); j++) {
carry[base-1+j*dist] = tmp[j];
}
//step 2.2: forward carry and parity signals down the tree
for(uint32_t i = (base+3*dist)-1; i+dist < inputbitlen; i+=(4*dist)) {
processed_ins = std::min(ceil_divide((inputbitlen - (i+dist)),2*dist), max_ins-2);
//std::cout << "intermediate base = " << i << ", dist = " << dist << ", processed_ins = " << processed_ins << std::endl;
lut_in.clear();
lut_in.resize(4*processed_ins);
//std::cout << "building an internal lut with " << lut_in.size() << " input wires: ";
for(uint32_t j = 0; j < processed_ins*2; j++) {
lut_in[2*j] = parity[i+j*(dist)];
lut_in[2*j+1] = carry[i+j*(dist)];
//std::cout << i+j*dist << ", ";
}
//std::cout << std::endl;
tmp = PutTruthTableMultiOutputGate(lut_in, processed_ins*2, (uint64_t*) m_vLUT_ADD_INTERNAL[processed_ins-1]);
//std::cout << "Truth table = " << m_vLUT_ADD_INTERNAL[processed_ins-1][0] << std::endl;
for(uint32_t j = 0; j < tmp.size()/2; j++) {
//std::cout << "writing bit " << 2*j << " and " << 2*j+1 << " to parity/carry position " << i+dist+2*j*dist << std::endl;
parity[i+dist+j*2*dist] = tmp[2*j];
carry[i+dist+j*2*dist] = tmp[2*j+1];
}
}
}
//std::cout << "Doing " << (floor_log2(inputbitlen/5)/2)+1 << " iterations on the inverse carry tree, " << floor_log2(inputbitlen/5) << ", " << inputbitlen/5 << std::endl;
//step 3: build the inverse carry tree
//d increases with d = 0: 5, d = 1: 20, d = 2: 80; d = 3: 320, ...
for(int32_t d = (floor_log2(inputbitlen/5)/2); d >= 0; d--) {
//for d = 0: 4, for d = 1: 16, for d = 2: 64
uint32_t start = 4 * (1<<(2*d));
//for start = 4: 1, start = 16: 4, start = 64: 16
uint32_t dist = start/4;
//std::cout << "d = " << d << ", start = " << start << ", dist = " << dist << std::endl;
for(uint32_t i = start; i < inputbitlen; i+=start) {
//processed_ins here needs to be between 1 and 3
//processed_ins = std::min(inputbitlen - i, max_ins-1);
processed_ins = std::min((inputbitlen - i)/dist, max_ins-1);
if(processed_ins > 0) {
//assign values to the LUT
lut_in.clear();
lut_in.resize(2*processed_ins+1);
lut_in[0] = carry[i-1];
for(uint32_t j = 0; j < processed_ins; j++) {
lut_in[2*j+1] = parity[(i-1)+(j+1)*dist];
lut_in[2*j+2] = carry[(i-1)+(j+1)*dist];
}
//std::cout << "wanting to build gate "<< std::endl;
//std::cout << "Building INV gate with " << processed_ins << " inputs: " << i-1;
/*for(uint32_t j = 0; j < processed_ins; j++) {
std::cout << ", " << (i-1)+(j+1)*dist;
}*/
//std::cout << std::endl;
tmp = PutTruthTableMultiOutputGate(lut_in, processed_ins, (uint64_t*) m_vLUT_ADD_INV[processed_ins-1]);
//std::cout << "done" << std::endl;
//copy resulting carry bit into carries
//std::cout << ", and " << tmp.size() << " outputs: ";
for(uint32_t j = 0; j < tmp.size(); j++) {
carry[(i-1)+(j+1)*dist] = tmp[j];
//std::cout << (i-1)+(j+1)*dist << ", ";
}
//std::cout << std::endl;
}
//i+= dist;//(processed_ins+1);
}
}
//step 4: compute the outputs from the carry signals and the parity bits at the zero-th level
out[0] = parity_zero[0];
for (uint32_t i = 1; i < inputbitlen; i++) {
out[i] = PutXORGate(parity_zero[i], carry[i - 1]);
}
if (bCARRY) //Do I expect a carry in the most significant bit position?
out[inputbitlen] = carry[inputbitlen - 1];
return out;
}
std::vector<uint32_t> BooleanCircuit::PutMulGate(std::vector<uint32_t> a, std::vector<uint32_t> b, uint32_t resultbitlen, bool depth_optimized, bool vector_ands) {
PadWithLeadingZeros(a, b);
// std::cout << "a.size() = " << a.size() << ", b.size() = " << b.size() << std::endl;
uint32_t inputbitlen = a.size();
if(inputbitlen == 1) {
return PutANDGate(a, b);
}
std::vector<std::vector<uint32_t> > vAdds(inputbitlen);
uint32_t zerogate = PutConstantGate(0, m_vGates[a[0]].nvals);
resultbitlen = std::min(resultbitlen, 2 * inputbitlen);
if(m_eContext == S_BOOL && vector_ands) {
share *ina, *inb, **mulout, *zero_share;
ina = new boolshare(a, this);
inb = new boolshare(b, this);
zero_share = new boolshare(inputbitlen, this);
mulout = (share**) malloc(sizeof(share*) * inputbitlen);
for(uint32_t i = 0; i < inputbitlen; i++) {
mulout[i] = new boolshare(inputbitlen, this);
zero_share->set_wire_id(i, zerogate);
}
for(uint32_t i = 0; i < inputbitlen; i++) {
PutMultiMUXGate(&ina, &zero_share, inb->get_wire_ids_as_share(i), 1, &(mulout[i]));
}
for (uint32_t i = 0, ctr; i < inputbitlen; i++) {
ctr = 0;
vAdds[i].resize(resultbitlen);
for (uint32_t j = 0; j < i && ctr < resultbitlen; j++, ctr++) {
vAdds[i][ctr] = zerogate;
}
for (uint32_t j = 0; j < inputbitlen && ctr < resultbitlen; j++, ctr++) {
vAdds[i][ctr] = mulout[j]->get_wire_id(i);//(a[j], b[i]);
}
for (uint32_t j = i; j < inputbitlen && ctr < resultbitlen; j++, ctr++) {
vAdds[i][ctr] = zerogate;
}
}
free(mulout);
} else {
// Compute AND between all bits
#ifdef ZDEBUG
std::cout << "Starting to construct multiplication gate for " << inputbitlen << " bits" << std::endl;
#endif
for (uint32_t i = 0, ctr; i < inputbitlen; i++) {
ctr = 0;
vAdds[i].resize(resultbitlen);
#ifdef ZDEBUG
std::cout << "New Iteration with ctr = " << ctr << ", and resultbitlen = " << resultbitlen << std::endl;
#endif
for (uint32_t j = 0; j < i && ctr < resultbitlen; j++, ctr++) {
vAdds[i][ctr] = zerogate;
}
for (uint32_t j = 0; j < inputbitlen && ctr < resultbitlen; j++, ctr++) {
vAdds[i][ctr] = PutANDGate(a[j], b[i]);
}
for (uint32_t j = i; j < inputbitlen && ctr < resultbitlen; j++, ctr++) {
vAdds[i][ctr] = zerogate;
}
}
}
if (depth_optimized) {
std::vector<std::vector<uint32_t> > out = PutCSNNetwork(vAdds);
return PutDepthOptimizedAddGate(out[0], out[1]);
} else {
return PutWideAddGate(vAdds);
}
}
share* BooleanCircuit::PutMULGate(share* ina, share* inb) {
//set the resulting bit length to be the smallest of: 1) bit length of the products or 2) the highest maximum bit length between ina and inb
uint32_t resultbitlen = std::min(ina->get_bitlength() + inb->get_bitlength(), std::max(ina->get_max_bitlength(), inb->get_max_bitlength()));
return new boolshare(PutMulGate(ina->get_wires(), inb->get_wires(), resultbitlen), this);
}
share* BooleanCircuit::PutGTGate(share* ina, share* inb) {
share* shr = new boolshare(1, this);
shr->set_wire_id(0, PutGTGate(ina->get_wires(), inb->get_wires()));
return shr;
}
share* BooleanCircuit::PutEQGate(share* ina, share* inb) {
share* shr = new boolshare(1, this);
shr->set_wire_id(0, PutEQGate(ina->get_wires(), inb->get_wires()));
return shr;
}
share* BooleanCircuit::PutMUXGate(share* ina, share* inb, share* sel) {
return new boolshare(PutMUXGate(ina->get_wires(), inb->get_wires(), sel->get_wire_id(0)), this);
}
std::vector<uint32_t> BooleanCircuit::PutWideAddGate(std::vector<std::vector<uint32_t> > ins) {
// build a balanced binary tree
std::vector<std::vector<uint32_t> >& survivors = ins;
while (survivors.size() > 1) {
unsigned j = 0;
for (unsigned i = 0; i < survivors.size();) {
if (i + 1 >= survivors.size()) {
survivors[j++] = survivors[i++];
} else {
survivors[j++] = PutSizeOptimizedAddGate(survivors[i], survivors[i + 1], false);
i += 2;
}
}
survivors.resize(j);
}
return survivors[0];
}
std::vector<std::vector<uint32_t> > BooleanCircuit::PutCSNNetwork(std::vector<std::vector<uint32_t> > ins) {
// build a balanced carry-save network
uint32_t inputbitlen = ins[0].size();
uint32_t wires = ins.size();
std::vector<std::vector<uint32_t> > survivors(wires * 2);// = ins;
std::vector<std::vector<uint32_t> > carry_lines(wires-2);
std::vector<std::vector<uint32_t> > rem(8);
std::vector<std::vector<uint32_t> > out(2);
int p_head=wires, p_tail = 0, c_head = 0, c_tail = 0;//, temp_gates;
std::vector<uint32_t> dummy(inputbitlen);
for(uint32_t i = 0; i < ins.size(); i++) {
survivors[i] = ins[i];
}
if(ins.size() < 3)
return ins;
while(wires > 2) {
for(; c_tail<c_head-2; c_tail+=3) {
#ifdef ZDEBUG
std::cout << "ctail: " << c_tail << ", c_head: " << c_head << std::endl;
#endif
//temp_gates = m_nFrontier;
out = PutCarrySaveGate(carry_lines[c_tail], carry_lines[c_tail+1], carry_lines[c_tail+2], inputbitlen);
#ifdef ZDEBUG
std::cout << "Computing Carry CSA for gates " << survivors[p_tail] << ", " << survivors[p_tail+1] << ", " << survivors[p_tail+2] << " and bitlen: " << (2*inputbitlen-1) << ", gates before: " << temp_gates << ", gates after: " << m_nFrontier << std::endl;
#endif
survivors[p_head++] = out[0];
carry_lines[c_head++] = out[1];
wires--;
}
for(; p_tail<p_head-2; p_tail+=3) {
#ifdef ZDEBUG
std::cout << "ptail: " << p_tail << ", p_head: " << p_head << std::endl;
#endif
//temp_gates = m_nFrontier;
out = PutCarrySaveGate(survivors[p_tail], survivors[p_tail+1], survivors[p_tail+2], inputbitlen);
#ifdef ZDEBUG
std::cout << "Computing Parity CSA for gates " << survivors[p_tail] << ", " << survivors[p_tail+1] << ", " << survivors[p_tail+2] << " and bitlen: " << (2*inputbitlen-1) << ", gates before: " << temp_gates << ", gates after: " << m_nFrontier << std::endl;
#endif
survivors[p_head++] = out[0];
carry_lines[c_head++] = out[1];
wires--;
}
if((p_head-p_tail) < 3 && (c_head-c_tail) < 3 && wires > 2) {
#ifdef ZDEBUG
std::cout << "Less than 3 in both, Carry and XOR" << std::endl;
#endif
uint32_t left = (p_head-p_tail) + (c_head-c_tail);
rem[0] = survivors[p_tail];
rem[1] = (p_head-p_tail)>1? survivors[p_tail+1] : carry_lines[c_tail];
rem[2] = (p_head-p_tail)>1? carry_lines[c_tail] : carry_lines[c_tail+1];
rem[3] = left > 3? carry_lines[c_tail+1] : dummy;//the dummy value should never be used!
for(uint32_t j = 0; j < left && wires > 2; j+=3) {
#ifdef ZDEBUG
std::cout << "left: " << left << ", j: " << j << std::endl;
#endif
//temp_gates = m_nFrontier;
out = PutCarrySaveGate(rem[j], rem[j+1], rem[j+2], inputbitlen);
#ifdef ZDEBUG
std::cout << "Computing Finish CSA for gates " << rem[j] << ", " << rem[j+1] << ", " << rem[j+2] << " and bitlen: " << (2*inputbitlen-1) << ", wires: " << wires << ", gates before: " << temp_gates << ", gates after: " << m_nFrontier << std::endl;
#endif
rem[left++] = out[0];
rem[left++] = out[1];
wires--;
}
#ifdef ZDEBUG
std::cout << "Computed last CSA gate, wires = " << wires << ", ending " << std::endl;
#endif
}
}
#ifdef ZDEBUG
std::cout << "Returning" << std::endl;
#endif
return out;
}
std::vector<uint32_t> BooleanCircuit::PutSUBGate(std::vector<uint32_t> a, std::vector<uint32_t> b, uint32_t max_bitlength) {
//pad with leading zeros
if(a.size() < max_bitlength) {
uint32_t zerogate = PutConstantGate(0, m_vGates[a[0]].nvals);
a.resize(max_bitlength, zerogate);
}
if(b.size() < max_bitlength) {
uint32_t zerogate = PutConstantGate(0, m_vGates[a[0]].nvals);
b.resize(max_bitlength, zerogate);
}
//PadWithLeadingZeros(a, b);
uint32_t bitlen = a.size();
std::vector<uint32_t> C(bitlen);
uint32_t i, ainvNbxc, ainvxc, bxc;
std::vector<uint32_t> ainv(bitlen);
std::vector<uint32_t> out(bitlen);
for (i = 0; i < bitlen; i++) {
ainv[i] = PutINVGate(a[i]);
}
//C[0] = PutXORGate(a[0], a[0]);
C[0] = PutConstantGate(0, m_vGates[a[0]].nvals);
for (i = 0; i < bitlen - 1; i++) {
//===================
// New Gates
// ainv[i] XOR c[i]
ainvxc = PutXORGate(ainv[i], C[i]);
// b[i] xor c[i]
bxc = PutXORGate(b[i], C[i]);
// (ainv[i] xor c[i]) AND (b[i] xor c[i])
ainvNbxc = PutANDGate(ainvxc, bxc);
// C[i+1] -> c[i] xor (ainv[i] xor c[i]) AND (b[i] xor c[i])
C[i + 1] = PutXORGate(ainvNbxc, C[i]);
}
for (i = 0; i < bitlen; i++) {
// a[i] xor b[i] xor C[i]
bxc = PutXORGate(b[i], C[i]);
out[i] = PutXORGate(bxc, a[i]);
}
return out;
}
share* BooleanCircuit::PutSUBGate(share* ina, share* inb) {
return new boolshare(PutSUBGate(ina->get_wires(), inb->get_wires(), std::max(ina->get_max_bitlength(), inb->get_max_bitlength())), this);
}
//computes: ci = a > b ? 1 : 0; but assumes both values to be of equal length!
uint32_t BooleanCircuit::PutGTGate(std::vector<uint32_t> a, std::vector<uint32_t> b) {
PadWithLeadingZeros(a, b);
if (m_eContext == S_YAO) {
return PutSizeOptimizedGTGate(a, b);
} else if(m_eContext == S_BOOL) {
return PutDepthOptimizedGTGate(a, b);
} else {
return PutLUTGTGate(a, b);
}
}
//computes: ci = a > b ? 1 : 0; but assumes both values to be of equal length!
uint32_t BooleanCircuit::PutSizeOptimizedGTGate(std::vector<uint32_t> a, std::vector<uint32_t> b) {
PadWithLeadingZeros(a, b);
uint32_t ci = 0, ci1, ac, bc, acNbc;
ci = PutConstantGate((UGATE_T) 0, m_vGates[a[0]].nvals);
for (uint32_t i = 0; i < a.size(); i++, ci = ci1) {
ac = PutXORGate(a[i], ci);
bc = PutXORGate(b[i], ci);
acNbc = PutANDGate(ac, bc);
ci1 = PutXORGate(a[i], acNbc);
}
return ci;
}
uint32_t BooleanCircuit::PutDepthOptimizedGTGate(std::vector<uint32_t> a, std::vector<uint32_t> b) {
PadWithLeadingZeros(a, b);
uint32_t i, rem;
uint32_t inputbitlen = std::min(a.size(), b.size());
std::vector<uint32_t> agtb(inputbitlen);
std::vector<uint32_t> eq(inputbitlen);
//Put the leaf comparison nodes from which the tree is built
for (i = 0; i < inputbitlen; i++) {
agtb[i] = PutANDGate(a[i], PutINVGate(b[i])); //PutBitGreaterThanGate(a[i], b[i]);
}
//compute the pairwise bit equality from bits 1 to bit inputbitlen
for (i = 1; i < inputbitlen; i++) {
eq[i] = PutINVGate(PutXORGate(a[i], b[i]));
}
rem = inputbitlen;
while (rem > 1) {
uint32_t j = 0;
//std::cout << "New iter with " << size << " element remaining"<< std::endl;
for (i = 0; i < rem;) {
if (i + 1 >= rem) {
agtb[j] = agtb[i];
eq[j] = eq[i];
i++;
j++;
} else {
//std::cout << j << " = GT" << i+1 << " XOR " << " ( EQ" << i+1 << " AND GT" << i << ")" << std::endl;
agtb[j] = PutXORGate(agtb[i+1], PutANDGate(eq[i+1], agtb[i]));
if(j > 0) {
eq[j] = PutANDGate(eq[i], eq[i+1]);
}
i += 2;
j++;
}
}
rem = j;
}
#ifdef ZDEBUG
std::cout << "Finished greater than tree with adress: " << agtb[0] << ", and bitlength: " << a.size() << std::endl;
#endif
return agtb[0];
}
uint32_t BooleanCircuit::PutLUTGTGate(std::vector<uint32_t> a, std::vector<uint32_t> b) {
// build a balanced 8-wise tree
uint32_t nins, maxins = 8, minins = 0, j = 0;
std::vector<uint32_t> lut_ins, tmp;
//copy a and b into an internal state
assert(a.size() == b.size());
std::vector<uint32_t> state(a.size() + b.size());
for(uint32_t i = 0; i < a.size(); i++) {
state[2*i] = a[i];
state[2*i+1] = b[i];
}
//build the leaf nodes for the tree
for(uint32_t i = 0; i < state.size(); ) {
//assign inputs for this node
nins = std::min(maxins, (uint32_t) state.size() - i);
//nins should always be a multiple of two
assert((nins & 0x01) == 0);
lut_ins.clear();
lut_ins.assign(state.begin() + i, state.begin() + i + nins);
tmp = PutTruthTableMultiOutputGate(lut_ins, 2, (uint64_t*) m_vLUT_GT_IN[(nins/2)-1]);
//std::cout << "using lut " << (hex) << m_vLUT_GT_IN[(nins/2)-1][0] << (dec) << std::endl;
//assign gt bit and eq bit to state
state[j] = tmp[0];
state[j+1] = tmp[1];
i+=nins;
j+=2;
}
//resize the state since we processed input bits
state.resize(j);
//build the tree for the remaining bits
while (state.size() > 2) {
j = 0;
for (uint32_t i = 0; i < state.size();) {
nins = std::min(maxins, (uint32_t) state.size()-i);
//it is not efficient to build a gate here so copy the wires to the next level
if(nins <= minins && state.size() > minins) {
for(; i < state.size();) {
state[j++] = state[i++];
}
} else {
lut_ins.clear();
lut_ins.assign(state.begin() + i, state.begin() + i + nins);
tmp = PutTruthTableMultiOutputGate(lut_ins, 2, (uint64_t*) m_vLUT_GT_INTERNAL[nins/2-2]);
state[j] = tmp[0];
state[j+1] = tmp[1];
i += nins;
j += 2;
}
}
state.resize(j);
}
return state[0];
}
uint32_t BooleanCircuit::PutEQGate(std::vector<uint32_t> a, std::vector<uint32_t> b) {
PadWithLeadingZeros(a, b);
uint32_t inputbitlen = a.size(), temp;
std::vector<uint32_t> xors(inputbitlen);
for (uint32_t i = 0; i < inputbitlen; i++) {
temp = PutXORGate(a[i], b[i]);
xors[i] = PutINVGate(temp);
}
// AND of all xor's
if(m_eContext == S_SPLUT) {
return PutLUTWideANDGate(xors);
} else {
return PutWideGate(G_NON_LIN, xors);
}
}
uint32_t BooleanCircuit::PutORGate(uint32_t a, uint32_t b) {
return PutINVGate(PutANDGate(PutINVGate(a), PutINVGate(b)));
}
std::vector<uint32_t> BooleanCircuit::PutORGate(std::vector<uint32_t> a, std::vector<uint32_t> b) {
uint32_t reps = std::max(a.size(), b.size());
PadWithLeadingZeros(a, b);
std::vector<uint32_t> out(reps);
for (uint32_t i = 0; i < reps; i++) {
out[i] = PutORGate(a[i], b[i]);
}
return out;
}
share* BooleanCircuit::PutORGate(share* a, share* b) {
return new boolshare(PutORGate(a->get_wires(), b->get_wires()), this);
}
/* if c [0] = s & a[0], c[1] = s & a[1], ...*/
share* BooleanCircuit::PutANDVecGate(share* ina, share* inb) {
uint32_t inputbitlen = ina->get_bitlength();
share* out = new boolshare(inputbitlen, this);
if (m_eContext == S_BOOL) {
for (uint32_t i = 0; i < inputbitlen; i++) {
out->set_wire_id(i, PutVectorANDGate(inb->get_wire_id(i), ina->get_wire_id(i)));
}
} else {
//std::cout << "Putting usual AND gate" << std::endl;
for (uint32_t i = 0; i < inputbitlen; i++) {
uint32_t bvec = PutRepeaterGate(inb->get_wire_id(i), m_vGates[ina->get_wire_id(i)].nvals);
out->set_wire_id(i, PutANDGate(ina->get_wire_id(i), bvec));
}
}
return out;
}
/* if s == 0 ? b : a*/
std::vector<uint32_t> BooleanCircuit::PutMUXGate(std::vector<uint32_t> a, std::vector<uint32_t> b, uint32_t s, BOOL vecand) {
std::vector<uint32_t> out;
uint32_t inputbitlen = std::max(a.size(), b.size());
uint32_t sab, ab;
PadWithLeadingZeros(a, b);
out.resize(inputbitlen);
uint32_t nvals=1;
for(uint32_t i = 0; i < a.size(); i++) {
if(m_vGates[a[i]].nvals > nvals)
nvals = m_vGates[a[i]].nvals;
}
for(uint32_t i = 0; i < b.size(); i++)
if(m_vGates[b[i]].nvals > nvals)
nvals = m_vGates[b[i]].nvals;
if (m_eContext == S_BOOL && vecand && nvals == 1) {
uint32_t avec = PutCombinerGate(a);
uint32_t bvec = PutCombinerGate(b);
out = PutSplitterGate(PutVecANDMUXGate(avec, bvec, s));
} else {
for (uint32_t i = 0; i < inputbitlen; i++) {
ab = PutXORGate(a[i], b[i]);
sab = PutANDGate(s, ab);
out[i] = PutXORGate(b[i], sab);
}
}
return out;
}
share* BooleanCircuit::PutVecANDMUXGate(share* a, share* b, share* s) {
return new boolshare(PutVecANDMUXGate(a->get_wires(), b->get_wires(), s->get_wires()), this);
}
/* if s == 0 ? b : a*/
std::vector<uint32_t> BooleanCircuit::PutVecANDMUXGate(std::vector<uint32_t> a, std::vector<uint32_t> b, std::vector<uint32_t> s) {
uint32_t nmuxes = a.size();
PadWithLeadingZeros(a, b);
std::vector<uint32_t> out(nmuxes);
//std::cout << "Putting Vector AND gate" << std::endl;
for (uint32_t i = 0; i < nmuxes; i++) {
out[i] = PutVecANDMUXGate(a[i], b[i], s[i]);
}
return out;
}
/* if s == 0 ? b : a*/
uint32_t BooleanCircuit::PutVecANDMUXGate(uint32_t a, uint32_t b, uint32_t s) {
uint32_t ab, sab;
ab = PutXORGate(a, b);
if (m_eContext == S_BOOL) {
sab = PutVectorANDGate(s, ab);
} else {
sab = PutANDGate(s, ab);
}
return PutXORGate(b, sab);
}
uint32_t BooleanCircuit::PutWideGate(e_gatetype type, std::vector<uint32_t> ins) {
// build a balanced binary tree
std::vector<uint32_t>& survivors = ins;
while (survivors.size() > 1) {
unsigned j = 0;
for (unsigned i = 0; i < survivors.size();) {
if (i + 1 >= survivors.size()) {
survivors[j++] = survivors[i++];
} else {
if (type == G_NON_LIN)
survivors[j++] = PutANDGate(survivors[i], survivors[i + 1]);
else
survivors[j++] = PutXORGate(survivors[i], survivors[i + 1]);
i += 2;
}
}
survivors.resize(j);
}
return survivors[0];
}
//compute the AND over all inputs
uint32_t BooleanCircuit::PutLUTWideANDGate(std::vector<uint32_t> ins) {
// build a balanced 8-wise tree
std::vector<uint32_t>& survivors = ins;
uint64_t* lut = (uint64_t*) calloc(4, sizeof(uint64_t));
uint32_t nins, maxins = 7, minins = 3;
std::vector<uint32_t> lut_ins;
uint32_t table_bitlen = sizeof(uint64_t) * 8;
/*std::cout << "Building a balanced tree" << std::endl;
std::cout << "Input gates: ";
for(uint32_t i = 0; i < ins.size(); i++) {
std::cout << ins[i] << ", ";
}
std::cout << std::endl;*/
while (survivors.size() > 1) {
uint32_t j = 0;
for (uint32_t i = 0; i < survivors.size();) {
nins = std::min((uint32_t) survivors.size()-i, maxins);
if(nins <= minins && survivors.size() > minins) {
for(; i < survivors.size();) {
survivors[j++] = survivors[i++];
}
} else {
lut_ins.clear();
lut_ins.assign(ins.begin() + i, ins.begin() + i + nins);
/*std::cout << "Combining " << nins << " gates: ";
for(uint32_t k = 0; k < lut_ins.size(); k++) {
std::cout << lut_ins[k] << ", ";
}*/
memset(lut, 0, bits_in_bytes(table_bitlen));
lut[((1L<<nins)-1) / table_bitlen] = 1L << (((1L<<nins)-1) % table_bitlen);
survivors[j++] = PutTruthTableGate(lut_ins, 1, lut);
//std::cout << " to gate " << survivors[j-1] << std::endl;
/*std::cout << "LUT: ";
for(uint32_t k = 0; k < 4; k++) {
std::cout << (hex) << lut[k] << ", " << (dec);
}
std::cout << std::endl;*/
i += nins;
}
}
survivors.resize(j);
}
return survivors[0];
}
//if s == 0: a stays a, else a becomes b, share interface
share** BooleanCircuit::PutCondSwapGate(share* a, share* b, share* s, BOOL vectorized) {
share** s_out = (share**) malloc(sizeof(share*) *2);
std::vector<std::vector<uint32_t> > out = PutCondSwapGate(a->get_wires(), b->get_wires(), s->get_wire_id(0), vectorized);
s_out[0] = new boolshare(out[0], this);
s_out[1] = new boolshare(out[1], this);
return s_out;
}
//if s == 0: a stays a, else a becomes b
std::vector<std::vector<uint32_t> > BooleanCircuit::PutCondSwapGate(std::vector<uint32_t> a, std::vector<uint32_t> b, uint32_t s, BOOL vectorized) {
std::vector<std::vector<uint32_t> > out(2);
uint32_t inputbitlen = std::max(a.size(), b.size());
PadWithLeadingZeros(a, b);
out[0].resize(inputbitlen);
out[1].resize(inputbitlen);
uint32_t ab, snab, svec;
if (m_eContext == S_BOOL && !vectorized) {
//Put combiner and splitter gates
uint32_t avec = PutCombinerGate(a);
uint32_t bvec = PutCombinerGate(b);
ab = PutXORGate(avec, bvec);
snab = PutVectorANDGate(s, ab);
out[0] = PutSplitterGate(PutXORGate(snab, avec));
out[1] = PutSplitterGate(PutXORGate(snab, bvec));
} else {
if (m_vGates[s].nvals < m_vGates[a[0]].nvals)
svec = PutRepeaterGate(s, m_vGates[a[0]].nvals);
else
svec = s;
for (uint32_t i = 0; i < inputbitlen; i++) {
ab = PutXORGate(a[i], b[i]);
snab = PutANDGate(svec, ab);
//swap here to change swap-behavior of condswap
out[0][i] = PutXORGate(snab, a[i]);
out[1][i] = PutXORGate(snab, b[i]);
}
}
return out;
}
//Returns val if b==1 and 0 else
std::vector<uint32_t> BooleanCircuit::PutELM0Gate(std::vector<uint32_t> val, uint32_t b) {
std::vector<uint32_t> out(val.size());
for (uint32_t i = 0; i < val.size(); i++) {
out[i] = PutANDGate(val[i], b);
}
return out;
}
share* BooleanCircuit::PutMaxGate(const std::vector<share*>& a) {
std::vector<std::vector<uint32_t>> max(a.size());
std::transform(a.cbegin(), a.cend(), max.begin(),
[](share* s){return s->get_wires();});
return new boolshare(PutMaxGate(max), this);
}
share* BooleanCircuit::PutMaxGate(share** a, uint32_t size) {
std::vector<share*> v(a, a+size);
return PutMaxGate(v);
}
std::vector<uint32_t> BooleanCircuit::PutMaxGate(const std::vector<std::vector<uint32_t>>& ws) {
BinaryOp_v_uint32_t op = [this](auto a, auto b) {
uint32_t cmp = (m_eContext == S_YAO) ?
this->PutSizeOptimizedGTGate(a, b) :
this->PutDepthOptimizedGTGate(a, b);
return this->PutMUXGate(a, b, cmp);
};
return binary_accumulate(ws, op);
}
share* BooleanCircuit::PutMinGate(share** a, uint32_t nvals) {
std::vector<std::vector<uint32_t> > min(nvals);
uint32_t i;
for (i = 0; i < nvals; i++) {
min[i] = a[i]->get_wires();
}
return new boolshare(PutMinGate(min), this);
}
std::vector<uint32_t> BooleanCircuit::PutMinGate(std::vector<std::vector<uint32_t> > a) {
// build a balanced binary tree
uint32_t cmp;
std::vector<std::vector<uint32_t> > m_vELMs = a;
while (m_vELMs.size() > 1) {
unsigned j = 0;
for (unsigned i = 0; i < m_vELMs.size();) {
if (i + 1 >= m_vELMs.size()) {
m_vELMs[j] = m_vELMs[i];
i++;
j++;
} else {
// cmp = bc->PutGTTree(m_vELMs[i], m_vELMs[i+1]);
if (m_eContext == S_YAO) {
cmp = PutSizeOptimizedGTGate(m_vELMs[i], m_vELMs[i + 1]);
m_vELMs[j] = PutMUXGate(m_vELMs[i + 1], m_vELMs[i], cmp);
} else {
cmp = PutDepthOptimizedGTGate(m_vELMs[i], m_vELMs[i + 1]);
m_vELMs[j] = PutMUXGate(m_vELMs[i + 1], m_vELMs[i], cmp);
}
i += 2;
j++;
}
}
m_vELMs.resize(j);
}
return m_vELMs[0];
}
// vals = values, ids = indicies of each value, n = size of vals and ids
void BooleanCircuit::PutMinIdxGate(share** vals, share** ids, uint32_t nvals, share** minval_shr, share** minid_shr) {
std::vector<std::vector<uint32_t> > val(nvals);
std::vector<std::vector<uint32_t> > id(nvals);
std::vector<uint32_t> minval(1);
std::vector<uint32_t> minid(1);
for (uint32_t i = 0; i < nvals; i++) {
/*val[i].resize(a[i]->size());
for(uint32_t j = 0; j < a[i]->size(); j++) {
val[i][j] = a[i]->get_wire(j);//->get_wires();
}
ids[i].resize(b[i]->size());
for(uint32_t j = 0; j < b[i]->size(); j++) {
ids[i][j] = b[i]->get_wire(j);
}*/
val[i] = vals[i]->get_wires();
id[i] = ids[i]->get_wires();
}
PutMinIdxGate(val, id, minval, minid);
*minval_shr = new boolshare(minval, this);
*minid_shr = new boolshare(minid, this);
}
// vals = values, ids = indicies of each value, n = size of vals and ids
void BooleanCircuit::PutMinIdxGate(std::vector<std::vector<uint32_t> > vals, std::vector<std::vector<uint32_t> > ids,
std::vector<uint32_t>& minval, std::vector<uint32_t>& minid) {
// build a balanced binary tree
uint32_t cmp;
std::vector<std::vector<uint32_t> > m_vELMs = vals;
#ifdef USE_MULTI_MUX_GATES
uint32_t nvariables = 2;
share **vala, **valb, **valout, *tmpval, *tmpidx, *cond;
if(m_eContext == S_BOOL) {
vala = (share**) malloc(sizeof(share*) * nvariables);
valb = (share**) malloc(sizeof(share*) * nvariables);
valout = (share**) malloc(sizeof(share*) * nvariables);
tmpval = new boolshare(vals[0].size(), this);
tmpidx = new boolshare(ids[0].size(), this);
cond = new boolshare(1, this);
}
#endif
while (m_vELMs.size() > 1) {
unsigned j = 0;
for (unsigned i = 0; i < m_vELMs.size();) {
if (i + 1 >= m_vELMs.size()) {
m_vELMs[j] = m_vELMs[i];
ids[j] = ids[i];
i++;
j++;
} else {
// cmp = bc->PutGTTree(m_vELMs[i], m_vELMs[i+1]);
if (m_eContext == S_BOOL) {
cmp = PutDepthOptimizedGTGate(m_vELMs[i], m_vELMs[i + 1]);
#ifdef USE_MULTI_MUX_GATES
//Multimux
cond->set_wire_id(0, cmp);
vala[0] = new boolshare(m_vELMs[i+1], this);
vala[1] = new boolshare(ids[i+1], this);
valb[0] = new boolshare(m_vELMs[i], this);
valb[1] = new boolshare(ids[i], this);
valout[0] = tmpval;
valout[1] = tmpidx;
PutMultiMUXGate(vala, valb, cond, nvariables, valout);
m_vELMs[j] = tmpval->get_wires();
ids[j] = tmpidx->get_wires();
#else
m_vELMs[j] = PutMUXGate(m_vELMs[i + 1], m_vELMs[i], cmp, false);
ids[j] = PutMUXGate(ids[i + 1], ids[i], cmp, false);
#endif
} else {
cmp = PutSizeOptimizedGTGate(m_vELMs[i], m_vELMs[i + 1]);
m_vELMs[j] = PutMUXGate(m_vELMs[i + 1], m_vELMs[i], cmp);
ids[j] = PutMUXGate(ids[i + 1], ids[i], cmp);
}
i += 2;
j++;
}
}
m_vELMs.resize(j);
ids.resize(j);
}
minval = m_vELMs[0];
minid = ids[0];
#ifdef USE_MULTI_MUX_GATES
if(m_eContext == S_BOOL) {
free(vala);
free(valb);
free(valout);
delete tmpval;
delete tmpidx;
delete cond;
}
#endif
}
/**Max....*/
// vals = values, ids = indicies of each value, n = size of vals and ids
void BooleanCircuit::PutMaxIdxGate(share** vals, share** ids, uint32_t nvals, share** maxval_shr, share** maxid_shr) {
std::vector<std::vector<uint32_t> > val(nvals);
std::vector<std::vector<uint32_t> > id(nvals);
std::vector<uint32_t> maxval(1);
std::vector<uint32_t> maxid(1);
for (uint32_t i = 0; i < nvals; i++) {
/*val[i].resize(a[i]->size());
for(uint32_t j = 0; j < a[i]->size(); j++) {
val[i][j] = a[i]->get_wire(j);//->get_wires();
}
ids[i].resize(b[i]->size());
for(uint32_t j = 0; j < b[i]->size(); j++) {
ids[i][j] = b[i]->get_wire(j);
}*/
val[i] = vals[i]->get_wires();
id[i] = ids[i]->get_wires();
}
//std::cout<<"Size: "<<val.size()<<std::endl;
PutMaxIdxGate(val, id, maxval, maxid);
*maxval_shr = new boolshare(maxval, this);
*maxid_shr = new boolshare(maxid, this);
}
// vals = values, ids = indicies of each value, n = size of vals and ids
void BooleanCircuit::PutMaxIdxGate(std::vector<std::vector<uint32_t> > vals, std::vector<std::vector<uint32_t> > ids,
std::vector<uint32_t>& maxval, std::vector<uint32_t>& maxid) {
// build a balanced binary tree
uint32_t cmp;
std::vector<std::vector<uint32_t> > m_vELMs = vals;
#ifdef USE_MULTI_MUX_GATES
uint32_t nvariables = 2;
share **vala, **valb, **valout, *tmpval, *tmpidx, *cond;
if(m_eContext == S_BOOL) {
vala = (share**) malloc(sizeof(share*) * nvariables);
valb = (share**) malloc(sizeof(share*) * nvariables);
valout = (share**) malloc(sizeof(share*) * nvariables);
tmpval = new boolshare(vals[0].size(), this);
tmpidx = new boolshare(ids[0].size(), this);
cond = new boolshare(1, this);
}
#endif
while (m_vELMs.size() > 1) {
unsigned j = 0;
for (unsigned i = 0; i < m_vELMs.size();) {
if (i + 1 >= m_vELMs.size()) {
m_vELMs[j] = m_vELMs[i];
ids[j] = ids[i];
i++;
j++;
} else {
if (m_eContext == S_BOOL) {
cmp = PutDepthOptimizedGTGate(m_vELMs[i+1], m_vELMs[i]);
#ifdef USE_MULTI_MUX_GATES
//Multimux
cond->set_wire_id(0, cmp);
vala[0] = new boolshare(m_vELMs[i+1], this);
vala[1] = new boolshare(ids[i+1], this);
valb[0] = new boolshare(m_vELMs[i], this);
valb[1] = new boolshare(ids[i], this);
valout[0] = tmpval;
valout[1] = tmpidx;
PutMultiMUXGate(vala, valb, cond, nvariables, valout);
m_vELMs[j] = tmpval->get_wires();
ids[j] = tmpidx->get_wires();
#else
m_vELMs[j] = PutMUXGate(m_vELMs[i + 1], m_vELMs[i], cmp);
ids[j] = PutMUXGate(ids[i + 1], ids[i], cmp);
#endif
} else {
cmp = PutSizeOptimizedGTGate(m_vELMs[i + 1], m_vELMs[i]);
m_vELMs[j] = PutMUXGate(m_vELMs[i + 1], m_vELMs[i], cmp);
ids[j] = PutMUXGate(ids[i + 1], ids[i], cmp);
}
i += 2;
j++;
}
}
m_vELMs.resize(j);
ids.resize(j);
}
maxval = m_vELMs[0];
maxid = ids[0];
#ifdef USE_MULTI_MUX_GATES
if(m_eContext == S_BOOL) {
free(vala);
free(valb);
free(valout);
delete tmpval;
delete tmpidx;
delete cond;
}
#endif
}
std::vector<uint32_t> BooleanCircuit::PutFPGate(const std::string func, std::vector<uint32_t> inputs, uint8_t bitsize, uint32_t nvals){
std::string fn = m_cCircuitFileDir;
//if there is no "/" at the end, append it
if ((fn.size() > 0) && (fn.compare(fn.size()-1, 1, "/") != 0)) {
fn += "/";
}
fn += "fp_";
fn += func;
fn += "_";
//std::cout << "bs = " << (uint32_t) bitsize << std::endl;
fn += std::to_string(bitsize);
fn += ".aby";
//std::cout << "opening " << fn.c_str() << std::endl;
return PutGateFromFile(fn.c_str(), inputs, nvals);
}
std::vector<uint32_t> BooleanCircuit::PutFPGate(const std::string func, std::vector<uint32_t> ina, std::vector<uint32_t> inb, uint8_t bitsize, uint32_t nvals){
ina.insert(ina.end(), inb.begin(), inb.end());
return PutFPGate(func, ina, bitsize, nvals);
}
std::vector<uint32_t> BooleanCircuit::PutGateFromFile(const std::string filename, std::vector<uint32_t> inputs, uint32_t nvals){
std::string line;
std::vector<uint32_t> tokens, outputs;
std::map<uint32_t, uint32_t> wires;
std::ifstream myfile;
//std::cout << "opening " << filename << std::endl;
myfile.open(filename.c_str());
uint32_t file_input_size = 0;
if (myfile.is_open()) {
while (getline(myfile, line)) {
if (line != "") {
tokenize_verilog(line, tokens);
switch (line.at(0)) {
case 'S': // Server input wire ids
assert(inputs.size() >= tokens.size() + file_input_size);
for (uint32_t i = 0; i < tokens.size(); i++) {
wires[tokens[i]] = inputs[i + file_input_size];
}
file_input_size += tokens.size();
break;
case 'C': // Client input wire ids
assert(inputs.size() >= tokens.size() + file_input_size);
for (uint32_t i = 0; i < tokens.size(); i++) {
wires[tokens[i]] = inputs[i + file_input_size];
}
file_input_size += tokens.size();
break;
case '0': // Constant Zero Gate
wires[tokens[0]] = PutConstantGate(0, nvals);
break;
case '1': // Constant One Gate
wires[tokens[0]] = PutConstantGate(1, nvals);
break;
case 'A': // AND Gate
wires[tokens[2]] = PutANDGate(wires[tokens[0]], wires[tokens[1]]);
break;
case 'X': // XOR Gate
wires[tokens[2]] = PutXORGate(wires[tokens[0]], wires[tokens[1]]);
break;
case 'V': // OR Gate
wires[tokens[2]] = PutORGate(wires[tokens[0]], wires[tokens[1]]);
break;
case 'M': // MUX Gate
wires[tokens[3]] = PutVecANDMUXGate(wires[tokens[1]], wires[tokens[0]], wires[tokens[2]]);
break;
case 'I': // INV Gate
wires[tokens[1]] = PutINVGate(wires[tokens[0]]);
break;
case 'O': // List of output wires
for (uint32_t i = 0; i < tokens.size(); i++) {
outputs.push_back(wires[tokens[i]]);
}
break;
}
}
}
myfile.close();
if (file_input_size < inputs.size()) {
std::cerr << "Warning: Input sizes didn't match! Less inputs read from circuit file than passed to it!" << std::endl;
}
}
else {
std::cerr << "Error: Unable to open circuit file " << filename << std::endl;
std::exit(EXIT_FAILURE);
}
wires.clear();
tokens.clear();
return outputs;
}
std::vector<uint32_t> BooleanCircuit::PutUniversalCircuitFromFile(const std::string filename, const std::string p1filename, std::vector<uint32_t> p2inputs, uint32_t nvals){
std::string line;
std::string p1line;
std::vector<uint32_t> tokens, outputs, p1tokens;
std::map<uint32_t, uint32_t> wires;
std::vector<std::vector<uint32_t> > tmp;
std::vector<uint32_t> tmp_wire1;
std::vector<uint32_t> tmp_wire2;
std::vector<uint32_t> p1inputs, p1inputsgate;
std::ifstream p1file;
p1file.open(p1filename);
uint32_t p1file_input_size = 0;
if(!p1file.is_open()) {
std::cerr << "Error: Unable to open programming file " << p1filename << std::endl;
std::exit(EXIT_FAILURE);
}
#ifdef DEBUG_UC
std::cout << "Server Input Control Bits " ;
#endif
while (getline(p1file, p1line)){
if (p1line != "") {
tokenize(p1line, p1tokens);
p1inputs.push_back(this->PutSIMDINGate(nvals, p1tokens[0], SERVER));
if(m_eMyRole == SERVER) {
p1inputsgate.push_back(p1tokens[0]);
}
else{
p1inputsgate.push_back(0);
}
#ifdef DEBUG_UC
std::cout << p1tokens[0] << std::endl;
#endif
p1file_input_size += 1;
}
}
#ifdef DEBUG_UC
std::cout << std::endl;
#endif
p1file.close();
#ifdef DEBUG_UC
std::cout << "P1file input size: " << p1file_input_size << std::endl;
#endif
if (p1file_input_size != p1inputs.size()) {
std::cerr << "Warning: Input sizes didn't match! Less inputs read from circuit file than passed to it!" << std::endl;
}
std::ifstream myfile;
myfile.open(filename);
uint32_t file_input_size = 0;
uint32_t p1_counter = 0;
if (!myfile.is_open()) {
std::cerr << "Error: Unable to open circuit file " << filename << std::endl;
std::exit(EXIT_FAILURE);
}
while (getline(myfile, line)) {
if (line != "") {
tokenize_verilog(line, tokens);
switch (line.at(0)) {
case 'C': // Client input wire ids
assert(p2inputs.size() >= tokens.size() + file_input_size - 1);
#ifdef DEBUG_UC
std::cout << "Client Input Wire IDs " ;
#endif
for (uint32_t i = 0; i < tokens.size(); i++) {
wires[tokens[i]] = p2inputs[i + file_input_size];
#ifdef DEBUG_UC
std::cout << tokens[i] << " ";
#endif
}
file_input_size += tokens.size();
#ifdef DEBUG_UC
std::cout << "number of inputs" << file_input_size << std::endl;
#endif
break;
case 'Y': // MUX Gate
#ifdef DEBUG_UC
std::cout << "Y Gate " << tokens[2] << " = Y(" << tokens[0]
<< " , " << tokens[1] << ") c = " << p1inputs[p1_counter] << std::endl;
#endif
wires[tokens[2]] = PutVecANDMUXGate(wires[tokens[0]], wires[tokens[1]], p1inputs[p1_counter]);
p1_counter++;
break;
case 'U': // Universal Gate
#ifdef DEBUG_UC
std::cout << "Universal Gate " << tokens[2] << " = U(" << tokens[0]
<< " , " << tokens[1] << ") op = " << p1inputs[p1_counter] << std::endl;
#endif
wires[tokens[2]] =
PutUniversalGate(wires[tokens[0]], wires[tokens[1]], p1inputsgate[p1_counter]);
p1_counter++;
break;
case 'X': // X Gate
#ifdef DEBUG_UC
std::cout << "X Gate (" << tokens[2] << " , " << tokens[3] << ")"
<< "= X(" << tokens[0] << " , " << tokens[1] << ") c = "
<< p1inputs[p1_counter] << std::endl;
#endif
tmp_wire1.clear();
tmp_wire2.clear();
tmp_wire1.push_back(wires[tokens[0]]);
tmp_wire2.push_back(wires[tokens[1]]);
tmp = PutCondSwapGate( tmp_wire1, tmp_wire2, p1inputs[p1_counter], true );
wires[tokens[2]] = tmp[0][0];
wires[tokens[3]] = tmp[1][0];
p1_counter++;
break;
case 'O': // List of output wires
#ifdef DEBUG_UC
std::cout << "Output Wires ";
#endif
for (uint32_t i = 0; i < tokens.size(); i++) {
outputs.push_back(wires[tokens[i]]);
#ifdef DEBUG_UC
std::cout << tokens[i] << " ";
#endif
}
#ifdef DEBUG_UC
std::cout << std::endl;
#endif
break;
}
}
}
myfile.close();
if (file_input_size < p2inputs.size()) {
std::cerr << "Warning: Input sizes didn't match! Less inputs read from circuit file than passed to it! " << file_input_size << " " << p2inputs.size() << std::endl;
}
return outputs;
}
void BooleanCircuit::GetInputLengthFromFile(const std::string filename, uint32_t& client_input, uint32_t& server_input){
std::string line;
std::vector<uint32_t> tokens;
std::ifstream myfile;
//std::cout << "opening " << filename << std::endl;
myfile.open(filename.c_str());
client_input = 0;
server_input = 0;
if (!myfile.is_open()) {
std::cerr << "Error: Unable to open circuit file " << filename << std::endl;
std::exit(EXIT_FAILURE);
}
while (getline(myfile, line)) {
if (line != "") {
tokenize_verilog(line, tokens);
switch (line.at(0)) {
case 'C': // Client input wire ids
client_input += tokens.size();
#ifdef DEBUG_UC
std::cout << line << std::endl;
std::cout << client_input << std::endl;
#endif
break;
case 'X': // Server input wire ids
server_input += 1;
break;
case 'Y': // Server input wire ids
server_input += 1;
break;
case 'U': // Server input wire ids
server_input += 1;
break;
}
}
}
myfile.close();
}
share* BooleanCircuit::PutLUTGateFromFile(const std::string filename, share* input) {
return new boolshare(PutLUTGateFromFile(filename, input->get_wires()), this);
}
std::vector<uint32_t> BooleanCircuit::PutLUTGateFromFile(const std::string filename, std::vector<uint32_t> inputs){
std::string line;
std::vector<uint32_t> tokens, outputs;
std::map<uint32_t, uint32_t> wires;
std::vector<uint32_t> lut_inputs, lut_outputs, token_outputs;
uint32_t n_inputs, n_outputs, ttable_vals, ctr;
std::ifstream myfile;
uint32_t* ttable;
//std::cout << "opening " << filename << std::endl;
myfile.open(filename.c_str());
if (myfile.is_open()) {
while (getline(myfile, line)) {
if (line != "") {
tokenize_verilog(line, tokens);
switch (line.at(0)) {
case 'I': // map the input wires to the gate
assert(inputs.size() == tokens.size());
//std::cout << "Input wires to Gate: ";
for (uint32_t i = 0; i < tokens.size(); i++) {
wires[tokens[i]] = inputs[i];
//std::cout << wires[tokens[i]] << ", ";
}
//std::cout << std::endl;
break;
case 'X': // XOR Gate
wires[tokens[2]] = PutXORGate(wires[tokens[0]], wires[tokens[1]]);
break;
case 'A': // Assign Operation
wires[tokens[1]] = wires[tokens[0]];
break;
case 'N': // Logical NOT Operation
wires[tokens[1]] = PutINVGate(wires[tokens[0]]);
break;
case 'L': // Parse LUT
ctr = 0;
//First value specifies the number of input wires
n_inputs = tokens[ctr++];
//Second value specifies the number of output wires
n_outputs = tokens[ctr++];
//std::cout << "n_inputs: " << n_inputs << ", n_outputs = " << n_outputs << std::endl;
//next will follow n_inputs input wires. Prepare to assign them to a temporary vector for later use
lut_inputs.resize(n_inputs);
//std::cout << "Inputs to LUT: ";
for(uint32_t i = 0; i < n_inputs; i++) {
lut_inputs[i] = wires[tokens[ctr++]];
//std::cout << tokens[ctr-1] << "(" << wires[tokens[ctr-1]] << "), ";
}
//std::cout << std::endl;
//next up are the contents of the LUT for each output wire, which is broken into ceil(2^{n_inputs} / 32) 32-bit values.
//For each output wire, we first have the content, followed by the id of the output wire.
token_outputs.resize(n_outputs);
ttable_vals = ceil_divide(1<<n_inputs, sizeof(uint32_t) * 8);
ttable = (uint32_t*) malloc(ceil_divide(1<<n_inputs, sizeof(UGATE_T) * 8) * n_outputs * sizeof(UGATE_T));
//std::cout << "(" << ttable_vals << ") TTable values : " << std::endl;;
for(uint32_t i = 0; i < n_outputs; i++) {
//std::cout << "Output wire " << i << ": ";
token_outputs[i] = tokens[ctr++];
//std::cout << "(" << token_outputs[i] << ")" << std::endl;
}
for(uint32_t i = 0; i < n_outputs; i++) {
for(uint32_t j = 0; j < ttable_vals; j++) {
ttable[i*ttable_vals + j] = tokens[ctr++];
//std::cout << ttable[i*ttable_vals+j] << " ";
}
}
//Build the LUT gate
lut_outputs = PutTruthTableMultiOutputGate(lut_inputs, n_outputs, (uint64_t*) ttable);
//do the mapping for all output gates
//std::cout << "Outputs from LUT: ";
for(uint32_t i = 0; i < n_outputs; i++) {
wires[token_outputs[i]] = lut_outputs[i];
//std::cout << wires[token_outputs[i]] <<", ";
}
//std::cout << std::endl;
break;
case 'O': // map the output wires from the gate to the output of this function
//std::cout << std::endl << "Setting output wires: ";
for (uint32_t i = 0; i < tokens.size(); i++) {
outputs.push_back(wires[tokens[i]]);
//std::cout << tokens[i] << "(" << wires[tokens[i]] << "), ";
}
//std::cout << std::endl;
break;
}
}
}
myfile.close();
}
else {
std::cerr << "Error: Unable to open circuit file " << filename << std::endl;
std::exit(EXIT_FAILURE);
}
wires.clear();
tokens.clear();
return outputs;
}
uint32_t BooleanCircuit::GetInputLengthFromFile(const std::string filename){
std::string line;
std::vector<uint32_t> tokens;
std::ifstream myfile;
//std::cout << "opening " << filename << std::endl;
myfile.open(filename.c_str());
uint32_t file_input_size = 0;
if (myfile.is_open()) {
while (getline(myfile, line)) {
if (line != "") {
tokenize_verilog(line, tokens);
switch (line.at(0)) {
case 'S': // Server input wire ids
file_input_size += tokens.size();
break;
case 'C': // Client input wire ids
file_input_size += tokens.size();
break;
}
}
}
myfile.close();
}
else {
std::cerr << "Error: Unable to open circuit file " << filename << std::endl;
std::exit(EXIT_FAILURE);
}
tokens.clear();
return file_input_size;
}
uint32_t BooleanCircuit::PutIdxGate(uint32_t r, uint32_t maxidx) {
if (r > maxidx) {
r = maxidx;
std::cout << "Warning: Index bigger than maxidx for IndexGate" << std::endl;
}
uint32_t digit, limit = ceil_log2(maxidx);
std::vector<uint32_t> temp(limit); // = m_nFrontier;
#ifdef ZDEBUG
std::cout << "index for r = " << r << std::endl;
#endif
for (uint32_t j = 0; j < limit; j++) {
digit = (r >> j) & 1;
temp[j] = PutConstantGate((UGATE_T) digit, 1);
//std::cout << "gate: " << out[j] << ": " << digit << std::endl;
}
return PutCombinerGate(temp);
}
void BooleanCircuit::PutMultiMUXGate(share** Sa, share** Sb, share* sel, uint32_t nshares, share** Sout) {
std::vector<uint32_t> inputsa, inputsb;
uint32_t bitlen = 0;
uint32_t nvals = m_vGates[sel->get_wire_id(0)].nvals;
//Yao not allowed, if so just put standard muxes
assert(m_eContext == S_BOOL);
for(uint32_t i = 0; i < nshares; i++) {
bitlen += Sa[i]->get_bitlength();
}
uint32_t total_nvals = bitlen * nvals;
share* vala = new boolshare(bitlen, this);
share* valb = new boolshare(bitlen, this);
//std::cout << "setting gate" << std::endl;
for(uint32_t i = 0, idx; i < bitlen; i++) {
for(uint32_t j = 0, ctr = 0; j < nshares && (i >= ctr || j == 0); j++) {
if(i < (ctr+Sa[j]->get_bitlength())) {
idx = i - ctr;
//std::cout << "for i = " << i << " taking j = " << j << " and ctr = " << ctr << std::endl;
vala->set_wire_id(i, Sa[j]->get_wire_id(idx));
valb->set_wire_id(i, Sb[j]->get_wire_id(idx));
}
ctr+=Sa[j]->get_bitlength();
}
}
share* avec = PutStructurizedCombinerGate(vala, 0, 1, total_nvals);
share* bvec = PutStructurizedCombinerGate(valb, 0, 1, total_nvals);
share* out = PutVecANDMUXGate(avec, bvec, sel);
//std::cout << "Setting out gates " << std::endl;
for(uint32_t i = 0, idx; i < bitlen; i++) {
for(uint32_t j = 0, ctr = 0; j < nshares && (i >= ctr || j == 0); j++) {
if(i < (ctr+Sa[j]->get_bitlength())) {
idx = i - ctr;
Sout[j]->set_wire_id(idx, PutStructurizedCombinerGate(out, i, bitlen, nvals)->get_wire_id(0));
}
ctr+=Sa[j]->get_bitlength();
}
}
}
void BooleanCircuit::Reset() {
Circuit::Reset();
free(m_vANDs);
m_nNumANDSizes = 1;
m_vANDs = (non_lin_vec_ctx*) malloc(sizeof(non_lin_vec_ctx) * m_nNumANDSizes);
m_vANDs[0].bitlen = 1;
m_vANDs[0].numgates = 0;
m_nB2YGates = 0;
m_nA2YGates = 0;
m_nYSwitchGates = 0;
m_nNumXORVals = 0;
m_nNumXORGates = 0;
m_nUNIVGates = 0;
m_vTTlens.resize(1);
m_vTTlens[0].resize(1);
m_vTTlens[0][0].resize(1);
m_vTTlens[0][0][0].tt_len = 4;
m_vTTlens[0][0][0].numgates = 0;
m_vTTlens[0][0][0].out_bits = 1;
m_vTTlens[0][0][0].ttable_values.clear();
}
void BooleanCircuit::PadWithLeadingZeros(std::vector<uint32_t> &a, std::vector<uint32_t> &b) {
uint32_t maxlen = std::max(a.size(), b.size());
if(a.size() != b.size()) {
uint32_t zerogate = PutConstantGate(0, m_vGates[a[0]].nvals);
a.resize(maxlen, zerogate);
b.resize(maxlen, zerogate);
}
}
share* BooleanCircuit::PutFullAdderGate(uint32_t a, uint32_t b, uint32_t carry_in) {
std::vector<uint32_t> out(2);
#ifdef FA_DEBUG
std::vector<uint32_t> v_a(1); v_a[0]=a;
std::vector<uint32_t> v_b(1); v_b[0]=b;
std::vector<uint32_t> v_c_in(1); v_c_in[0]=carry_in;
share * s_a = new boolshare(v_a, this);
share * s_b = new boolshare(v_b, this);
share * s_c_in = new boolshare(v_c_in, this);
PutPrintValueGate(s_a, "a");
PutPrintValueGate(s_b, "b");
PutPrintValueGate(s_c_in, "carry_in");
share * s_a_xor_b = PutXORGate(s_a, s_b);
share * s_b_xor_c_in = PutXORGate(s_b, s_c_in);
share * s_and = PutANDGate(s_a_xor_b, s_b_xor_c_in);
PutPrintValueGate(s_a_xor_b, "a^b");
PutPrintValueGate(s_b_xor_c_in, "b^c_in");
PutPrintValueGate(s_and, "(a^b)&(b^c_in)");
#endif
uint32_t a_xor_b = PutXORGate(a,b);
out[1] = PutXORGate(PutANDGate(a_xor_b, PutXORGate(b, carry_in)),b);
out[0] = PutXORGate(a_xor_b, carry_in);
share* s_out = new boolshare(out, this);
#ifdef FA_DEBUG
std::vector<uint32_t> in(3);
in[2] = a;
in[1] = b;
in[0] = carry_in;
share* s_in = new boolshare(in, this);
PutPrintValueGate(s_in, "Full Adder Input");
PutPrintValueGate(s_out, "Full Adder Output");
#endif
return s_out;
}
share* BooleanCircuit::PutADDChainGate(std::vector<uint32_t> a, std::vector<uint32_t> b, uint32_t carry_in) {
PadWithLeadingZeros(a, b);
std::vector<uint32_t> out(a.size());
std::vector<uint32_t> v_c_in(1); v_c_in[0] = carry_in;
share * last = PutFullAdderGate(a[0], b[0], carry_in);
out[0] = last->get_wires()[0];
#ifdef AC_DEBUG
share * s_c_in = new boolshare(v_c_in, this);
PutPrintValueGate(s_c_in, "carry in");
PutPrintValueGate(last, "last");
#endif
for (size_t i = 1; i < out.size(); ++i) {
share * tmp = PutFullAdderGate(a[i], b[i], last->get_wires()[1]);
out[i] = tmp->get_wires()[0];
last = tmp;
#ifdef AC_DEBUG
PutPrintValueGate(new boolshare(std::vector<uint32_t>(&a[i], &a[i+1]), this), "a i");
PutPrintValueGate(new boolshare(std::vector<uint32_t>(&b[i], &b[i+1]), this), "b i");
PutPrintValueGate(tmp, "tmp");
#endif
}
std::vector<uint32_t> l = last->get_wires();
if (last->get_wires()[1] && out.size() < last->get_max_bitlength())
out.insert(out.end(), &l[1], &l[2]);
#ifdef AC_DEBUG
PutPrintValueGate(last, "last last");
PutPrintValueGate(new boolshare(out, this), "out");
#endif
return new boolshare(out, this);
}
share* BooleanCircuit::PutHammingWeightGate(share* s_in) {
return PutHammingWeightGate(s_in, s_in->get_bitlength());
}
share* BooleanCircuit::PutHammingWeightGate(share* s_in, uint32_t bitlen) {
#ifdef HW_DEBUG
PutPrintValueGate(s_in, "INPUT_BUILD");
#endif
// force all nvals equal assert
s_in->get_nvals();
std::vector<uint32_t> wires = s_in->get_wires();
return PutHammingWeightGateRec(wires.data(), bitlen);
}
share* BooleanCircuit::PutHammingWeightGateRec(uint32_t * wires, uint32_t bitlen) {
share* out;
uint32_t nvals = GetNumVals(wires[0]);
UGATE_T zero = 0u;
share* zero_share = PutSIMDCONSGate(nvals, zero, 1);
uint32_t zero_wire = zero_share->get_wire_id(0);
#ifdef HW_DEBUG
std::vector<uint32_t> in(wires, wires + bitlen);
share * s = new boolshare(in, this);
PutPrintValueGate(s, "INPUT3");
delete s;
#endif
if (bitlen > 3) {
share *v, *u;
uint32_t i;
size_t bitlen_v = pow(2, (uint) (log(bitlen) / log(2))) - 1;
size_t bitlen_u = bitlen - bitlen_v - 1;
#ifdef HW_DEBUG
std::cout << "Input bitlen: " << bitlen << "\tBitlen v: " << bitlen_v <<
"\tBitlen u: " << bitlen_u << "\tBitlen i: " <<
bitlen - bitlen_v - bitlen_u << std::endl;
#endif
//build v
v = PutHammingWeightGateRec(&wires[bitlen - bitlen_v], bitlen_v);
//build u
if (bitlen_u > 0) {
u = PutHammingWeightGateRec(&wires[1], bitlen_u);
} else {
u = zero_share;
}
//build i
if (bitlen - bitlen_v > 0) {
i = wires[0];
} else {
i = zero_wire;
}
#ifdef HW_DEBUG
PutPrintValueGate(v, "V");
PutPrintValueGate(u, "U");
std::vector<uint32_t> v_i(1, i);
PutPrintValueGate(std::make_unique<boolshare>(v_i, this).get(), "i");
std::cout << std::endl;
#endif
out = PutADDChainGate(v->get_wires(), u->get_wires(), i);
delete v;
if (bitlen_u>0) delete u; // u == zero_share otherwise and deleted later
} else if (bitlen > 2)
out = PutFullAdderGate(wires[2], wires[1], wires[0]);
else if (bitlen > 1) {
out = PutFullAdderGate(wires[1], wires[0], zero_wire);
} else if (bitlen > 0) {
std::vector<uint32_t> out_v(1, wires[0]);
out = new boolshare(out_v, this);
} else {
return zero_share;
}
delete zero_share;
return out;
}
share* BooleanCircuit::PutUint2DoubleGate(share* input){
UINT32 from;
FP64 to;
return PutConvTypeGate(input, &from, &to);
}
share* BooleanCircuit::PutConvTypeGate(share * value, ConvType* from, ConvType* to, uint32_t nvals){
return new boolshare(PutConvTypeGate(value->get_wires(), from, to, nvals), this);
}
std::vector<uint32_t> BooleanCircuit::PutConvTypeGate(std::vector<uint32_t> wires, ConvType* from, ConvType* to, uint32_t nvals){
switch(to->getType()){
case ENUM_FP_TYPE:
return PutUint2FpGate(wires, (UINTType*)from , (FPType*)to, nvals);
// case ENUM_UINT_TYPE:
// return PutFp2UintGate(wires, (FPType*)from , (UINTType*)to);
default:
std::cout <<"Unknown data type in CONVType %zu" << to << std::endl;
std::exit(EXIT_FAILURE);
}
}
//TODO: value is in wires, remove paramter "from"?
std::vector<uint32_t> BooleanCircuit::PutUint2FpGate(std::vector<uint32_t> wires, [[maybe_unused]] UINTType* from, FPType* to, uint32_t nvals){
#ifdef UINT2FP_DEBUG
PutPrintValueGate(new boolshare(wires, this), "INPUT");
std::cout << "wires size: " << wires.size() << std::endl;
#endif
//constants
uint64_t zero = 0, one = 1;
uint32_t one_bit_len = 1;
share* zero_gate = PutSIMDCONSGate(nvals, zero, one_bit_len);
share* one_gate = PutSIMDCONSGate(nvals, one, one_bit_len);
//pad to the length of fraction or remove the most significant bits
wires.resize(to->getNumOfDigits(), zero_gate->get_wires()[0]);
share * s_in = new boolshare(wires, this);
//check if input is zero
share* eq_zero = PutEQGate(zero_gate, s_in);
//calculate prefix or
std::vector<uint32_t> prefix_or = PutPreOrGate(wires);
share * s_prefix_or = new boolshare(prefix_or, this);
#ifdef UINT2FP_DEBUG
PutPrintValueGate(s_prefix_or, "PREFIX OR");
#endif
std::vector<uint32_t> reversed_preor;
reversed_preor.insert(reversed_preor.begin(), prefix_or.rbegin(), prefix_or.rend());
share * value = new boolshare(PutINVGate(reversed_preor), this);
value->set_max_bitlength(to->getNumOfDigits()+1);
std::vector<uint32_t> tmp_inv_out = value->get_wires();
std::vector<uint32_t> power_of_2;
power_of_2.insert(power_of_2.begin(), tmp_inv_out.begin(), tmp_inv_out.end());
power_of_2.push_back(one_gate->get_wires()[0]);
share * p2 = new boolshare(power_of_2,this);
value = PutHammingWeightGate(p2, nvals);
value = new boolshare(PutBarrelLeftShifterGate(s_in->get_wires(), value->get_wires(), nvals), this);
std::vector<uint32_t> tmp_fract = value->get_wires();
tmp_fract.resize(to->getNumOfDigits());
value = new boolshare(tmp_fract ,this);
std::vector<uint32_t> value_v = value->get_wires();
#ifdef UINT2FP_DEBUG
PutPrintValueGate(value, "VALUE");
#endif
std::reverse(value_v.begin(), value_v.end());
value_v.resize(to->getNumOfDigits(), zero_gate->get_wires()[0]);
#ifdef UINT2FP_DEBUG
//PutPrintValueGate(new boolshare(value_v, this), "RESIZED");
std::cout << "fraction vector size: " << value_v.size() << std::endl;
#endif
//Calculate number of 1-bits in Prefix OR output
share* pre_or_for_exp = PutHammingWeightGate(s_prefix_or, nvals);
#ifdef UINT2FP_DEBUG
std::cout << "HW out size: " << pre_or_for_exp->get_wires().size() << std::endl;
PutPrintValueGate(pre_or_for_exp, "pre or for exp");
#endif
share * exp = PutSIMDCONSGate(nvals, (uint64_t)(to->getExpBias()-1), to->getExpBits());
#ifdef UINT2FP_DEBUG
PutPrintValueGate(exp, "exp initialized with bias");
std::cout << "bias bit length: " << exp->get_wires().size() << std::endl;
#endif
exp = PutADDGate(exp, pre_or_for_exp);
std::vector<uint32_t> tmp_exp = exp->get_wires();
//exp = PutXORGate(exp, PutMUXGate(zero_gate,exp,eq_zero));
exp = PutMUXGate(exp, zero_gate, eq_zero);
tmp_exp.resize(to->getExpBits(), zero_gate->get_wires()[0]);
std::vector<uint32_t> v_out(1);
v_out[0]=zero_gate->get_wires()[0];
std::vector<uint32_t> exp_v(&tmp_exp[0], &tmp_exp[to->getExpBits()]);
v_out.insert(v_out.end() ,exp_v.rbegin(), exp_v.rend());
#ifdef UINT2FP_DEBUG
std::cout << "out+exp size: " << v_out.size() << std::endl;
#endif
v_out.insert(v_out.end(), value_v.begin(), value_v.end());
#ifdef UINT2FP_DEBUG
PutPrintValueGate(new boolshare(exp_v, this), "exponent");
PutPrintValueGate(new boolshare(value_v, this), "fraction");
#endif
std::reverse(v_out.begin(), v_out.end());
#ifdef UINT2FP_DEBUG
std::cout << "Num of gates, end:" << GetNumGates() << std::endl;
//PutPrintValueGate(new boolshare(v_out, this), "RESULT");
#endif
return v_out;
}
/*
// TODO implement PutFP2INTGate
std::vector<uint32_t> BooleanCircuit::PutFp2UintGate(std::vector<uint32_t> wires, FPType* from, UINTType* to){
std::vector<uint32_t> out;
std::cout << "PutFP2INTGate is not implemented yet" << std::endl;
std::exit(EXIT_FAILURE);
return out;
}
*/
share * BooleanCircuit::PutPreOrGate(share * input){
return new boolshare(PutPreOrGate(input->get_wires()), this);
}
std::vector<uint32_t> BooleanCircuit::PutPreOrGate(std::vector<uint32_t> wires){
//TODO optimize circuit
if(!wires.size()){
std::cout << "PreORGate wires of size 0. Exitting." << std::endl;
std::exit(EXIT_FAILURE);
}
std::vector <uint32_t> out(wires.size());
out[wires.size()-1] = wires[wires.size()-1];
if(wires.size()==1)
return out;
uint32_t tmp = PutORGate(wires[wires.size()-1], wires[wires.size()-2]);
out[wires.size()-2] = tmp;
if(wires.size()==2)
return out;
for(size_t i = 2; i < wires.size(); i++){
tmp = PutORGate(tmp, wires[wires.size()-i-1]);
out[wires.size()-i-1]= tmp;
}
return out;
}
share * BooleanCircuit::PutBarrelLeftShifterGate(share * input, share * n){
return new boolshare(PutBarrelLeftShifterGate(input->get_wires(), n->get_wires()), this);
}
std::vector<uint32_t> BooleanCircuit::PutBarrelLeftShifterGate(std::vector<uint32_t> wires,
std::vector<uint32_t> n, uint32_t nvals){
uint n_size = (uint)(log(wires.size())/log(2));
auto step = pow(2, (double)n_size);
auto out_size = step*2;
std::vector<uint32_t> res(out_size);
std::vector<uint32_t> last;
uint64_t zero = 0;
share* zero_gate = PutSIMDCONSGate(nvals, zero, 1);
n.resize(n_size, zero_gate->get_wires()[0]);
wires.resize(out_size, zero_gate->get_wires()[0]);
for(int i = n_size; i >=0 ; i--, step/=2){
for(auto j = 0; j < out_size; j++){
std::vector<uint32_t> tmp_right(1);
std::vector<uint32_t> tmp_left(1);
if(step == out_size/2){
tmp_right[0] = wires[j];
tmp_left[0] = j < step ? zero_gate->get_wires()[0] : wires[j-step];
}
else{
tmp_right[0] = last[j];
tmp_left[0] = j < step ? zero_gate->get_wires()[0] : last[j-step];
}
res[j] = PutMUXGate(tmp_left, tmp_right, n[i])[0];
}
last.clear();
last.insert(last.begin(), res.begin(), res.end());
}
return res;
}
share * BooleanCircuit::PutBarrelRightShifterGate(share * input, share * n){
return new boolshare(PutBarrelRightShifterGate(input->get_wires(), n->get_wires()), this);
}
std::vector<uint32_t> BooleanCircuit::PutBarrelRightShifterGate(std::vector<uint32_t> wires, std::vector<uint32_t> n){
std::reverse(wires.begin(), wires.end());
std::vector<uint32_t> res = PutBarrelLeftShifterGate(wires, n);
std::reverse(res.begin(), res.end());
res.erase(res.begin(), res.begin() + wires.size());
return res;
}
share * BooleanCircuit::PutFPGate(share * in, op_t op, uint8_t bitlen, uint32_t nvals, fp_op_setting s){
// if bitlen/nvals were not set manually, use values from input
if (bitlen == 0) {
bitlen = in->get_bitlength();
}
if (nvals == 0) {
nvals = in->get_nvals();
}
const char * o;
switch(op){
case COS:
o = "ieee_cos";
break;
case EXP:
o = "nostatus_exp";
break;
case EXP2:
o = "nostatus_exp2";
break;
case LN:
o = "nostatus_ln";
break;
case LOG2:
o = "nostatus_log2";
break;
case SIN:
o = "ieee_sin";
break;
case SQR:
o = s==no_status ? "nostatus_sqr" : "ieee_sqr";
break;
case SQRT:
o = s==no_status ? "nostatus_sqrt" : "ieee_sqrt";
break;
default:
std::cerr << "Wrong operation in floating point gate with one input.";
std::exit(EXIT_FAILURE);
}
return new boolshare(PutFPGate(o, in->get_wires(), bitlen, nvals), this);
}
share * BooleanCircuit::PutFPGate(share * in_a, share * in_b, op_t op, uint8_t bitlen, uint32_t nvals, fp_op_setting s){
// if bitlen/nvals were not set manually, use values from input
if (bitlen == 0) {
bitlen = in_a->get_bitlength();
}
if (nvals == 0) {
nvals = in_a->get_nvals();
}
const char * o;
switch(op){
case ADD:
o = s==no_status ? "nostatus_add" : "ieee_add";
break;
case CMP:
o = "nostatus_cmp";
break;
case DIV:
o = s==no_status ? "nostatus_div" : "ieee_div";
break;
case MUL:
o = s==no_status ? "nostatus_mult" : "ieee_mult";
break;
case SUB:
o = s==no_status ? "nostatus_sub" : "ieee_sub";
break;
default:
std::cerr << "Wrong operation in floating point gate with two inputs.";
std::exit(EXIT_FAILURE);
}
return new boolshare(PutFPGate(o, in_a->get_wires(), in_b->get_wires(), bitlen, nvals), this);
}
| 30.969335 | 257 | 0.65291 | [
"vector",
"transform"
] |
76992ab210e2a3c233b11ab8d6e7c7fafd760212 | 5,585 | cpp | C++ | src/Scene/CubeSphere.cpp | mtheory101/hybrid-rendering-thesis | 314a200726450e27982e1a95eec3702ad5c9d320 | [
"MIT"
] | 1 | 2019-06-14T20:22:21.000Z | 2019-06-14T20:22:21.000Z | src/Scene/CubeSphere.cpp | ptrefall/hybrid-rendering-thesis | 72be3b3f6b457741737cd83cefb90f2bdbaa46dc | [
"MIT"
] | null | null | null | src/Scene/CubeSphere.cpp | ptrefall/hybrid-rendering-thesis | 72be3b3f6b457741737cd83cefb90f2bdbaa46dc | [
"MIT"
] | null | null | null | #include "CubeSphere.h"
#include "proto_camera.h"
#include "../Render/ATTRIB.h"
#include "../Render/ShaderConstants.h"
#include <glm/ext.hpp>
#include <vector>
using namespace Scene;
using namespace glm;
CubeSphere::CubeSphere(unsigned int cell_count, float spacing)
{
std::vector<unsigned int> indices;
std::vector<float> vertices;
std::vector<float> texCoords;
unsigned int width = cell_count;
unsigned int height = cell_count;
unsigned int step = 1;
unsigned int base_alloc = (width/step)*(height/step);
vertices.reserve( base_alloc * 3 );
texCoords.reserve( base_alloc * 2 );
for(unsigned int y = 0; y < height; y += step)
for(unsigned int x = 0; x < width; x += step)
{
float z = 1.0f;
buildIndices(indices, x,y,z, width, height);
buildVertices(vertices, x,y,z, spacing, 1.0f);
buildTexCoords(texCoords, x,y,z, width, height);
}
unsigned int buffer_size = sizeof(float) * (vertices.size() + texCoords.size());
vao = std::make_shared<Render::VAO>();
vbo = std::make_shared<Render::VBO>(buffer_size, GL_STATIC_DRAW);
ibo = std::make_shared<Render::IBO>(indices, GL_STATIC_DRAW);
auto v_offset = vbo->buffer<float>(vertices);
auto t_offset = vbo->buffer<float>(texCoords);
Render::ATTRIB::bind(Render::ShaderConstants::Position(), 3, GL_FLOAT, false, 0, v_offset);
Render::ATTRIB::bind(Render::ShaderConstants::TexCoord(), 2, GL_FLOAT, false, 0, t_offset);
vao->unbind();
vbo->unbind();
ibo->unbind();
}
void CubeSphere::render(const Render::ShaderPtr &active_program)
{
object_to_world = glm::translate( position);
auto &world_to_view = FirstPersonCamera::getSingleton()->getWorldToViewMatrix();
auto &view_to_clip = FirstPersonCamera::getSingleton()->getViewToClipMatrix();
auto normal_to_view = transpose(inverse(mat3(world_to_view * object_to_world)));
uni_object_to_world-> bind(object_to_world);
uni_world_to_view-> bind(world_to_view);
uni_view_to_clip-> bind(view_to_clip);
uni_normal_to_view-> bind(normal_to_view);
for(auto it=textures.begin(); it!=textures.end(); ++it)
{
glActiveTexture(GL_TEXTURE0+it->first);
it->second.first->bind();
it->second.second->bind((int)it->first);
}
if(material)
material->bind_id(active_program->getFS());
vao->bind();
glDrawElements(GL_TRIANGLE_STRIP, ibo->size(), GL_UNSIGNED_INT, BUFFER_OFFSET(0));
for(auto it=textures.begin(); it!=textures.end(); ++it)
{
glActiveTexture(GL_TEXTURE0+it->first);
it->second.first->unbind();
}
}
void CubeSphere::buildIndices(std::vector<unsigned int> &indices, unsigned int x, unsigned int y, float z, unsigned int width, unsigned int height)
{
// 0 1 2 3
// 4 5 6 7
// 8 9 10 c
// n 13 14 u
// 16 17 18 19
//convert the (x,y) to a single index value which represents the "current" index in the triangle strip
//represented by "c" in the figure above
unsigned int current_index = y*width+x;
//find the vertex index in the grid directly under the current index
//represented by "u" in the figure above
unsigned int under_index = 0;
if(y < height-1)
under_index = (y+1)*width+x;
else
return; //This is the last row, which has already been covered in the previous row with triangle strips in mind
indices.push_back(current_index);
indices.push_back(under_index);
//degenerate triangle technique at end of each row, so that we only have one dip call for the entire grid
//otherwise we'd need one triangle strip per row. We only want one triangle strip for the entire grid!
if(x < width-1)
return;
if(y >= height-2)
return;
//find the next vertex index in the grid from the current index
//represented by "n" in the figure above
//We already know that the current index is the last in the current row and that it's not the last row in the grid,
//so no need to make any if-checks here.
unsigned int next_index = (y+1)*width;
//Add an invisible degeneration here to bind with next row in triangle strip
indices.push_back(under_index);
indices.push_back(next_index);
}
void CubeSphere::buildVertices(std::vector<float> &vertices, unsigned int x, unsigned int y, float z, float spacing, float height_mod)
{
float temp_x = (float)x*spacing*2.0f - 1.0f;
float temp_y = (float)y*spacing*2.0f - 1.0f;
float temp_z = z*height_mod;
float new_x = cube_to_sphere(temp_x, temp_y, temp_z);
float new_y = cube_to_sphere(temp_y, temp_z, temp_x);
float new_z = cube_to_sphere(temp_z, temp_x, temp_y);
//Add one x,y,z vertex for each x,y in the grid
vertices.push_back(new_x);
vertices.push_back(new_y);
vertices.push_back(new_z);
}
void CubeSphere::buildTexCoords(std::vector<float> &texCoords, unsigned int x, unsigned int y, float z, unsigned int width, unsigned int height)
{
//Add one u,v texCoord for each x,y in the grid
float s = ((float)x/(float)width);//*2.0f - 1.0f;
float t = ((float)y/(float)height);//*2.0f - 1.0f;
//s = cube_to_sphere(s,t) * 0.5f + 0.5f;
//t = cube_to_sphere(t,s) * 0.5f + 0.5f;
texCoords.push_back(s);
texCoords.push_back(t);
}
float CubeSphere::cube_to_sphere(float a, float b)
{
float b_sq = b*b;
//http://mathproofs.blogspot.no/2005/07/mapping-cube-to-sphere.html
return a * glm::sqrt(1.0f - (b_sq/2.0f));
}
float CubeSphere::cube_to_sphere(float a, float b, float c)
{
float b_sq = b*b;
float c_sq = c*c;
//http://mathproofs.blogspot.no/2005/07/mapping-cube-to-sphere.html
return a * glm::sqrt(1.0f - (b_sq/2.0f) - (c_sq/2.0f) + ((b_sq*c_sq)/3.0f));
}
| 31.914286 | 148 | 0.692032 | [
"render",
"vector"
] |
371d1c0048a65351d2cfbcffe48b084f27ac4f53 | 34,253 | inl | C++ | Engine/Source/Runtime/Core/Public/Delegates/DelegateInstancesImpl.inl | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Core/Public/Delegates/DelegateInstancesImpl.inl | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Core/Public/Delegates/DelegateInstancesImpl.inl | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*================================================================================
DelegateInstancesImpl.inl: Inline implementation of delegate bindings.
This file in re-included in DelegateCombinations.h for EVERY supported delegate signature.
Every combination of parameter count, return value presence or other function modifier will
include this file to generate a delegate interface type and implementation type for that signature.
The types declared in this file are for internal use only.
================================================================================*/
#if !defined(__Delegate_h__) || !defined(FUNC_INCLUDING_INLINE_IMPL)
#error "This inline header must only be included by Delegate.h"
#endif
/* Class names for supported delegate bindings.
*****************************************************************************/
#define DELEGATE_INSTANCE_INTERFACE_CLASS FUNC_COMBINE(IBaseDelegateInstance_, FUNC_SUFFIX)
#define SP_METHOD_DELEGATE_INSTANCE_CLASS FUNC_COMBINE(TBaseSPMethodDelegateInstance_, FUNC_COMBINE(FUNC_PAYLOAD_SUFFIX, FUNC_CONST_SUFFIX))
#define RAW_METHOD_DELEGATE_INSTANCE_CLASS FUNC_COMBINE(TBaseRawMethodDelegateInstance_, FUNC_COMBINE(FUNC_PAYLOAD_SUFFIX, FUNC_CONST_SUFFIX))
#define UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS FUNC_COMBINE(TBaseUObjectMethodDelegateInstance_, FUNC_COMBINE(FUNC_PAYLOAD_SUFFIX, FUNC_CONST_SUFFIX))
#define STATIC_DELEGATE_INSTANCE_CLASS FUNC_COMBINE(TBaseStaticDelegateInstance_, FUNC_COMBINE(FUNC_PAYLOAD_SUFFIX, FUNC_CONST_SUFFIX))
#define FUNCTOR_DELEGATE_INSTANCE_CLASS FUNC_COMBINE(TBaseFunctorDelegateInstance_, FUNC_COMBINE(FUNC_PAYLOAD_SUFFIX, FUNC_CONST_SUFFIX))
#define UFUNCTION_DELEGATE_INSTANCE_CLASS FUNC_COMBINE(TBaseUFunctionDelegateInstance_, FUNC_COMBINE(FUNC_PAYLOAD_SUFFIX, FUNC_CONST_SUFFIX))
#if FUNC_IS_CONST
#define DELEGATE_QUALIFIER const
#else
#define DELEGATE_QUALIFIER
#endif
/* Macros for function parameter and delegate payload lists
*****************************************************************************/
#if FUNC_HAS_PAYLOAD
#define DELEGATE_COMMA_PAYLOAD_LIST , FUNC_PAYLOAD_LIST
#define DELEGATE_COMMA_PAYLOAD_PASSTHRU , FUNC_PAYLOAD_PASSTHRU
#define DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST , FUNC_PAYLOAD_INITIALIZER_LIST
#define DELEGATE_COMMA_PAYLOAD_PASSIN , FUNC_PAYLOAD_PASSIN
#if FUNC_HAS_PARAMS
#define DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN FUNC_PARAM_PASSTHRU, FUNC_PAYLOAD_PASSIN
#define DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST FUNC_PARAM_LIST, FUNC_PAYLOAD_LIST
#define DELEGATE_PARMS_COLON_INITIALIZER_LIST : FUNC_PARAM_INITIALIZER_LIST, FUNC_PAYLOAD_INITIALIZER_LIST
#else
#define DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN FUNC_PAYLOAD_PASSIN
#define DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST FUNC_PAYLOAD_LIST
#define DELEGATE_PARMS_COLON_INITIALIZER_LIST : FUNC_PAYLOAD_INITIALIZER_LIST
#endif
#else
#define DELEGATE_COMMA_PAYLOAD_LIST
#define DELEGATE_COMMA_PAYLOAD_PASSTHRU
#define DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
#define DELEGATE_COMMA_PAYLOAD_PASSIN
#define DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN FUNC_PARAM_PASSTHRU
#define DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST FUNC_PARAM_LIST
#if FUNC_HAS_PARAMS
#define DELEGATE_PARMS_COLON_INITIALIZER_LIST : FUNC_PARAM_INITIALIZER_LIST
#else
#define DELEGATE_PARMS_COLON_INITIALIZER_LIST
#endif
#endif
/* Delegate binding types
*****************************************************************************/
template<class UserClass, FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME> class UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS;
template<class UserClass, FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME> class RAW_METHOD_DELEGATE_INSTANCE_CLASS;
/**
* Implements a delegate binding for shared pointer member functions.
*/
template<class UserClass, FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME, ESPMode SPMode>
class SP_METHOD_DELEGATE_INSTANCE_CLASS
: public DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>
{
public:
/** Type definition for member function pointers. */
typedef RetValType (UserClass::*FMethodPtr)( DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST ) DELEGATE_QUALIFIER;
/**
* Creates and initializes a new instance.
*
* @param InUserObject A shared reference to an arbitrary object (templated) that hosts the member function.
* @param InMethodPtr C++ member function pointer for the method to bind.
*/
SP_METHOD_DELEGATE_INSTANCE_CLASS( const TSharedPtr<UserClass, SPMode>& InUserObject, FMethodPtr InMethodPtr DELEGATE_COMMA_PAYLOAD_LIST )
: UserObject(InUserObject)
, MethodPtr(InMethodPtr)
DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
, Handle(FDelegateHandle::GenerateNewHandle)
{
// NOTE: Shared pointer delegates are allowed to have a null incoming object pointer. Weak pointers can expire,
// an it is possible for a copy of a delegate instance to end up with a null pointer.
checkSlow(MethodPtr != nullptr);
}
public:
// IDelegateInstance interface
virtual FName GetFunctionName( ) const override
{
return NAME_None;
}
virtual const void* GetRawMethodPtr( ) const override
{
return GetRawMethodPtrInternal();
}
virtual const void* GetRawUserObject( ) const override
{
return GetRawUserObjectInternal();
}
virtual EDelegateInstanceType::Type GetType( ) const override
{
return SPMode == ESPMode::ThreadSafe ? EDelegateInstanceType::ThreadSafeSharedPointerMethod : EDelegateInstanceType::SharedPointerMethod;
}
virtual bool HasSameObject( const void* InUserObject ) const override
{
return UserObject.HasSameObject(InUserObject);
}
virtual bool IsSafeToExecute( ) const override
{
return UserObject.IsValid();
}
public:
// DELEGATE_INSTANCE_INTERFACE_CLASS interface
virtual DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* CreateCopy() override
{
return new SP_METHOD_DELEGATE_INSTANCE_CLASS(*this);
}
virtual RetValType Execute( FUNC_PARAM_LIST ) const override
{
// Verify that the user object is still valid. We only have a weak reference to it.
TSharedPtr<UserClass, SPMode> SharedUserObject( UserObject.Pin());
checkSlow(SharedUserObject.IsValid());
// Safely remove const to work around a compiler issue with instantiating template permutations for
// overloaded functions that take a function pointer typedef as a member of a templated class. In
// all cases where this code is actually invoked, the UserClass will already be a const pointer.
typedef typename TRemoveConst<UserClass>::Type MutableUserClass;
MutableUserClass* MutableUserObject = const_cast<MutableUserClass*>(SharedUserObject.Get());
// Call the member function on the user's object. And yes, this is the correct C++ syntax for calling a
// pointer-to-member function.
checkSlow(MethodPtr != nullptr);
return (MutableUserObject->*MethodPtr)(DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN);
}
virtual FDelegateHandle GetHandle() const override
{
return Handle;
}
#if FUNC_IS_VOID
virtual bool ExecuteIfSafe( FUNC_PARAM_LIST ) const override
{
// Verify that the user object is still valid. We only have a weak reference to it.
TSharedPtr<UserClass, SPMode> SharedUserObject(UserObject.Pin());
if (SharedUserObject.IsValid())
{
Execute(FUNC_PARAM_PASSTHRU);
return true;
}
return false;
}
#endif
virtual bool IsSameFunction( const DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>& InOtherDelegate ) const override
{
// NOTE: Payload data is not currently considered when comparing delegate instances.
// See the comment in multi-cast delegate's Remove() method for more information.
if ((InOtherDelegate.GetType() == EDelegateInstanceType::SharedPointerMethod) ||
(InOtherDelegate.GetType() == EDelegateInstanceType::ThreadSafeSharedPointerMethod) ||
(InOtherDelegate.GetType() == EDelegateInstanceType::RawMethod))
{
return (GetRawMethodPtrInternal() == InOtherDelegate.GetRawMethodPtr() && UserObject.HasSameObject(InOtherDelegate.GetRawUserObject()));
}
return false;
}
public:
/**
* Creates a new shared pointer delegate binding for the given user object and method pointer.
*
* @param InUserObjectRef Shared reference to the user's object that contains the class method.
* @param InFunc Member function pointer to your class method.
* @return The new delegate.
*/
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create( const TSharedPtr<UserClass, SPMode>& InUserObjectRef, FMethodPtr InFunc DELEGATE_COMMA_PAYLOAD_LIST )
{
return new SP_METHOD_DELEGATE_INSTANCE_CLASS(InUserObjectRef, InFunc DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
/**
* Creates a new shared pointer delegate binding for the given user object and method pointer.
*
* This overload requires that the supplied object derives from TSharedFromThis.
*
* @param InUserObject The user's object that contains the class method. Must derive from TSharedFromThis.
* @param InFunc Member function pointer to your class method.
* @return The new delegate.
*/
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create( UserClass* InUserObject, FMethodPtr InFunc DELEGATE_COMMA_PAYLOAD_LIST )
{
// We expect the incoming InUserObject to derived from TSharedFromThis.
TSharedRef<UserClass> UserObjectRef(StaticCastSharedRef<UserClass>(InUserObject->AsShared()));
return Create(UserObjectRef, InFunc DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
protected:
/**
* Internal, inlined and non-virtual version of GetRawUserObject interface.
*/
FORCEINLINE const void* GetRawUserObjectInternal( ) const
{
return UserObject.Pin().Get();
}
/**
* Internal, inlined and non-virtual version of GetRawMethod interface.
*/
FORCEINLINE const void* GetRawMethodPtrInternal( ) const
{
return *(const void**)&MethodPtr;
}
private:
// Declare ourselves as a friend so we can access other template permutations in IsSameFunction().
template<class UserClassNoShadow, FUNC_PAYLOAD_TEMPLATE_DECL_NO_SHADOW, ESPMode SPModeNoShadow> friend class SP_METHOD_DELEGATE_INSTANCE_CLASS;
// Declare other pointer-based delegates as a friend so IsSameFunction() can compare members.
template<class UserClassNoShadow, FUNC_PAYLOAD_TEMPLATE_DECL_NO_SHADOW> friend class UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS;
template<class UserClassNoShadow, FUNC_PAYLOAD_TEMPLATE_DECL_NO_SHADOW> friend class RAW_METHOD_DELEGATE_INSTANCE_CLASS;
// Weak reference to an instance of the user's class which contains a method we would like to call.
TWeakPtr<UserClass, SPMode> UserObject;
// C++ member function pointer.
FMethodPtr MethodPtr;
// Payload member variables, if any.
FUNC_PAYLOAD_MEMBERS
// The handle of this delegate
FDelegateHandle Handle;
};
/**
* Implements a delegate binding for C++ member functions.
*/
template<class UserClass, FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME>
class RAW_METHOD_DELEGATE_INSTANCE_CLASS
: public DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>
{
static_assert(!TPointerIsConvertibleFromTo<UserClass, const UObjectBase>::Value, "You cannot use raw method delegates with UObjects.");
public:
/** Pointer-to-member typedef */
typedef RetValType ( UserClass::*FMethodPtr )( DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST ) DELEGATE_QUALIFIER;
/**
* Creates and initializes a new instance.
*
* @param InUserObject An arbitrary object (templated) that hosts the member function.
* @param InMethodPtr C++ member function pointer for the method to bind.
*/
RAW_METHOD_DELEGATE_INSTANCE_CLASS( UserClass* InUserObject, FMethodPtr InMethodPtr DELEGATE_COMMA_PAYLOAD_LIST )
: UserObject(InUserObject)
, MethodPtr(InMethodPtr)
DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
, Handle(FDelegateHandle::GenerateNewHandle)
{
// Non-expirable delegates must always have a non-null object pointer on creation (otherwise they could never execute.)
check(InUserObject != nullptr && MethodPtr != nullptr);
}
public:
// IDelegateInstance interface
virtual FName GetFunctionName( ) const override
{
return NAME_None;
}
virtual const void* GetRawMethodPtr( ) const override
{
return GetRawMethodPtrInternal();
}
virtual const void* GetRawUserObject( ) const override
{
return GetRawUserObjectInternal();
}
virtual EDelegateInstanceType::Type GetType( ) const override
{
return EDelegateInstanceType::RawMethod;
}
virtual bool HasSameObject( const void* InUserObject ) const override
{
return UserObject == InUserObject;
}
virtual bool IsSafeToExecute( ) const override
{
// We never know whether or not it is safe to deference a C++ pointer, but we have to
// trust the user in this case. Prefer using a shared-pointer based delegate type instead!
return true;
}
public:
// DELEGATE_INSTANCE_INTERFACE_CLASS interface
virtual DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* CreateCopy( ) override
{
return new RAW_METHOD_DELEGATE_INSTANCE_CLASS(*this);
}
virtual RetValType Execute( FUNC_PARAM_LIST ) const override
{
// Safely remove const to work around a compiler issue with instantiating template permutations for
// overloaded functions that take a function pointer typedef as a member of a templated class. In
// all cases where this code is actually invoked, the UserClass will already be a const pointer.
typedef typename TRemoveConst<UserClass>::Type MutableUserClass;
MutableUserClass* MutableUserObject = const_cast<MutableUserClass*>(UserObject);
// Call the member function on the user's object. And yes, this is the correct C++ syntax for calling a
// pointer-to-member function.
checkSlow(MethodPtr != nullptr);
return (MutableUserObject->*MethodPtr)(DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN);
}
virtual FDelegateHandle GetHandle() const override
{
return Handle;
}
#if FUNC_IS_VOID
virtual bool ExecuteIfSafe( FUNC_PARAM_LIST ) const override
{
// We never know whether or not it is safe to deference a C++ pointer, but we have to
// trust the user in this case. Prefer using a shared-pointer based delegate type instead!
Execute(FUNC_PARAM_PASSTHRU);
return true;
}
#endif
virtual bool IsSameFunction( const DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>& InOtherDelegate ) const override
{
// NOTE: Payload data is not currently considered when comparing delegate instances.
// See the comment in multi-cast delegate's Remove() method for more information.
if ((InOtherDelegate.GetType() == EDelegateInstanceType::RawMethod) ||
(InOtherDelegate.GetType() == EDelegateInstanceType::UObjectMethod) ||
(InOtherDelegate.GetType() == EDelegateInstanceType::SharedPointerMethod) ||
(InOtherDelegate.GetType() == EDelegateInstanceType::ThreadSafeSharedPointerMethod))
{
return (GetRawMethodPtrInternal() == InOtherDelegate.GetRawMethodPtr()) && (UserObject == InOtherDelegate.GetRawUserObject());
}
return false;
}
public:
/**
* Creates a new raw method delegate binding for the given user object and function pointer.
*
* @param InUserObject User's object that contains the class method.
* @param InFunc Member function pointer to your class method.
* @return The new delegate.
*/
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create( UserClass* InUserObject, FMethodPtr InFunc DELEGATE_COMMA_PAYLOAD_LIST )
{
return new RAW_METHOD_DELEGATE_INSTANCE_CLASS(InUserObject, InFunc DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
protected:
/**
* Internal, inlined and non-virtual version of GetRawUserObject interface.
*/
FORCEINLINE const void* GetRawUserObjectInternal( ) const
{
return UserObject;
}
/**
* Internal, inlined and non-virtual version of GetRawMethodPtr interface.
*/
FORCEINLINE const void* GetRawMethodPtrInternal( ) const
{
return *(const void**)&MethodPtr;
}
private:
// Declare other pointer-based delegates as a friend so IsSameFunction() can compare members
template<class UserClassNoShadow, FUNC_PAYLOAD_TEMPLATE_DECL_NO_SHADOW, ESPMode SPModeNoShadow> friend class SP_METHOD_DELEGATE_INSTANCE_CLASS;
template<class UserClassNoShadow, FUNC_PAYLOAD_TEMPLATE_DECL_NO_SHADOW> friend class UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS;
// Pointer to the user's class which contains a method we would like to call.
UserClass* UserObject;
// C++ member function pointer.
FMethodPtr MethodPtr;
// Payload member variables (if any).
FUNC_PAYLOAD_MEMBERS
// The handle of this delegate
FDelegateHandle Handle;
};
/**
* Implements a delegate binding for UObject methods.
*/
template<class UserClass, FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME>
class UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS
: public DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>
{
static_assert(TPointerIsConvertibleFromTo<UserClass, const UObjectBase>::Value, "You cannot use UObject method delegates with raw pointers.");
public:
// Type definition for member function pointers. */
typedef RetValType (UserClass::*FMethodPtr)( DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST ) DELEGATE_QUALIFIER;
/**
* Creates and initializes a new instance.
*
* @param InUserObject An arbitrary object (templated) that hosts the member function.
* @param InMethodPtr C++ member function pointer for the method to bind.
*/
UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS( UserClass* InUserObject, FMethodPtr InMethodPtr DELEGATE_COMMA_PAYLOAD_LIST )
: UserObject(InUserObject)
, MethodPtr(InMethodPtr)
DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
, Handle(FDelegateHandle::GenerateNewHandle)
{
// NOTE: UObject delegates are allowed to have a null incoming object pointer. UObject weak pointers can expire,
// an it is possible for a copy of a delegate instance to end up with a null pointer.
checkSlow(MethodPtr != nullptr);
}
public:
// IDelegateInstance interface
virtual FName GetFunctionName( ) const override
{
return NAME_None;
}
virtual const void* GetRawMethodPtr( ) const override
{
return GetRawMethodPtrInternal();
}
virtual const void* GetRawUserObject( ) const override
{
return GetRawUserObjectInternal();
}
virtual EDelegateInstanceType::Type GetType( ) const override
{
return EDelegateInstanceType::UObjectMethod;
}
virtual bool HasSameObject( const void* InUserObject ) const override
{
return (UserObject.Get() == InUserObject);
}
virtual bool IsCompactable( ) const override
{
return !UserObject.Get(true);
}
virtual bool IsSafeToExecute( ) const override
{
return !!UserObject.Get();
}
public:
// DELEGATE_INSTANCE_INTERFACE_CLASS interface
virtual DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* CreateCopy( ) override
{
return new UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS(*this);
}
virtual RetValType Execute( FUNC_PARAM_LIST ) const override
{
// Verify that the user object is still valid. We only have a weak reference to it.
checkSlow(UserObject.IsValid());
// Safely remove const to work around a compiler issue with instantiating template permutations for
// overloaded functions that take a function pointer typedef as a member of a templated class. In
// all cases where this code is actually invoked, the UserClass will already be a const pointer.
typedef typename TRemoveConst<UserClass>::Type MutableUserClass;
MutableUserClass* MutableUserObject = const_cast<MutableUserClass*>(UserObject.Get());
// Call the member function on the user's object. And yes, this is the correct C++ syntax for calling a
// pointer-to-member function.
checkSlow(MethodPtr != nullptr);
return (MutableUserObject->*MethodPtr)(DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN);
}
virtual FDelegateHandle GetHandle() const override
{
return Handle;
}
#if FUNC_IS_VOID
virtual bool ExecuteIfSafe( FUNC_PARAM_LIST ) const override
{
// Verify that the user object is still valid. We only have a weak reference to it.
UserClass* ActualUserObject = UserObject.Get();
if (ActualUserObject != nullptr)
{
Execute(FUNC_PARAM_PASSTHRU);
return true;
}
return false;
}
#endif
virtual bool IsSameFunction( const DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>& InOtherDelegate ) const override
{
// NOTE: Payload data is not currently considered when comparing delegate instances.
// See the comment in multi-cast delegate's Remove() method for more information.
if ((InOtherDelegate.GetType() == EDelegateInstanceType::UObjectMethod) ||
(InOtherDelegate.GetType() == EDelegateInstanceType::RawMethod))
{
return (GetRawMethodPtrInternal() == InOtherDelegate.GetRawMethodPtr()) && (UserObject.Get() == InOtherDelegate.GetRawUserObject());
}
return false;
}
public:
/**
* Creates a new UObject delegate binding for the given user object and method pointer.
*
* @param InUserObject User's object that contains the class method.
* @param InFunc Member function pointer to your class method.
* @return The new delegate.
*/
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create( UserClass* InUserObject, FMethodPtr InFunc DELEGATE_COMMA_PAYLOAD_LIST )
{
return new UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS(InUserObject, InFunc DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
protected:
/**
* Internal, inlined and non-virtual version of GetRawUserObject interface.
*/
FORCEINLINE const void* GetRawUserObjectInternal( ) const
{
return UserObject.Get();
}
/**
* Internal, inlined and non-virtual version of GetRawMethodPtr interface.
*/
FORCEINLINE const void* GetRawMethodPtrInternal( ) const
{
return *(const void**)&MethodPtr;
}
private:
// Declare other pointer-based delegates as a friend so IsSameFunction() can compare members
template<class UserClassNoShadow, FUNC_PAYLOAD_TEMPLATE_DECL_NO_SHADOW,ESPMode SPModeNoShadow> friend class SP_METHOD_DELEGATE_INSTANCE_CLASS;
template<class UserClassNoShadow, FUNC_PAYLOAD_TEMPLATE_DECL_NO_SHADOW> friend class RAW_METHOD_DELEGATE_INSTANCE_CLASS;
// Pointer to the user's class which contains a method we would like to call.
TWeakObjectPtr<UserClass> UserObject;
// C++ member function pointer.
FMethodPtr MethodPtr;
// Payload member variables (if any).
FUNC_PAYLOAD_MEMBERS
// The handle of this delegate
FDelegateHandle Handle;
};
#if !FUNC_IS_CONST
/**
* Implements a delegate binding for regular C++ functions.
*/
template<FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME>
class STATIC_DELEGATE_INSTANCE_CLASS
: public DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>
{
public:
/**
* Type definition for static function pointers.
*
* NOTE: Static C++ functions can never be const, so 'const' is always omitted here. That means there is
* usually an extra static delegate class created with a 'const' name, even though it doesn't use const.
*/
typedef RetValType (*FFuncPtr)( DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST );
/**
* Creates and initializes a new instance.
*
* @param InStaticFuncPtr C++ function pointer.
*/
STATIC_DELEGATE_INSTANCE_CLASS( FFuncPtr InStaticFuncPtr DELEGATE_COMMA_PAYLOAD_LIST )
: StaticFuncPtr(InStaticFuncPtr)
DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
, Handle(FDelegateHandle::GenerateNewHandle)
{
check(StaticFuncPtr != nullptr);
}
public:
// IDelegateInstance interface
virtual FName GetFunctionName( ) const override
{
return NAME_None;
}
virtual const void* GetRawMethodPtr( ) const override
{
return *(const void**)&StaticFuncPtr;
}
virtual const void* GetRawUserObject( ) const override
{
return nullptr;
}
virtual EDelegateInstanceType::Type GetType( ) const override
{
return EDelegateInstanceType::Raw;
}
virtual bool HasSameObject( const void* UserObject ) const override
{
// Raw Delegates aren't bound to an object so they can never match
return false;
}
virtual bool IsSafeToExecute( ) const override
{
// Static functions are always safe to execute!
return true;
}
public:
// DELEGATE_INSTANCE_INTERFACE_CLASS interface
virtual DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* CreateCopy( ) override
{
return new STATIC_DELEGATE_INSTANCE_CLASS(*this);
}
virtual RetValType Execute( FUNC_PARAM_LIST ) const override
{
// Call the static function
checkSlow(StaticFuncPtr != nullptr);
return StaticFuncPtr(DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN);
}
virtual FDelegateHandle GetHandle() const override
{
return Handle;
}
#if FUNC_IS_VOID
virtual bool ExecuteIfSafe( FUNC_PARAM_LIST ) const override
{
Execute(FUNC_PARAM_PASSTHRU);
return true;
}
#endif
virtual bool IsSameFunction( const DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>& InOtherDelegate ) const override
{
// NOTE: Payload data is not currently considered when comparing delegate instances.
// See the comment in multi-cast delegate's Remove() method for more information.
if (InOtherDelegate.GetType() == EDelegateInstanceType::Raw)
{
// Downcast to our delegate type and compare
const STATIC_DELEGATE_INSTANCE_CLASS<FUNC_PAYLOAD_TEMPLATE_ARGS>& OtherStaticDelegate =
static_cast<const STATIC_DELEGATE_INSTANCE_CLASS<FUNC_PAYLOAD_TEMPLATE_ARGS>&>(InOtherDelegate);
return (StaticFuncPtr == OtherStaticDelegate.StaticFuncPtr);
}
return false;
}
public:
/**
* Creates a new static function delegate binding for the given function pointer.
*
* @param InFunc Static function pointer.
* @return The new delegate.
*/
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create( FFuncPtr InFunc DELEGATE_COMMA_PAYLOAD_LIST )
{
return new STATIC_DELEGATE_INSTANCE_CLASS(InFunc DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
private:
// C++ function pointer.
FFuncPtr StaticFuncPtr;
// Payload member variables, if any.
FUNC_PAYLOAD_MEMBERS
// The handle of this delegate
FDelegateHandle Handle;
};
/**
* Implements a delegate binding for C++ functors, e.g. lambdas.
*/
template<typename FunctorType, FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME>
class FUNCTOR_DELEGATE_INSTANCE_CLASS
: public DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>
{
public:
static_assert(TAreTypesEqual<FunctorType, typename TRemoveReference<FunctorType>::Type>::Value, "FunctorType cannot be a reference");
/**
* Creates and initializes a new instance
*
* @param InFunctor C++ functor
*/
FUNCTOR_DELEGATE_INSTANCE_CLASS(const FunctorType& InFunctor DELEGATE_COMMA_PAYLOAD_LIST)
: Functor(InFunctor)
DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
, Handle(FDelegateHandle::GenerateNewHandle)
{
}
FUNCTOR_DELEGATE_INSTANCE_CLASS(FunctorType&& InFunctor DELEGATE_COMMA_PAYLOAD_LIST)
: Functor(MoveTemp(InFunctor))
DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
, Handle(FDelegateHandle::GenerateNewHandle)
{
}
public:
// IDelegateInstance interface
virtual FName GetFunctionName() const override
{
return NAME_None;
}
virtual const void* GetRawMethodPtr() const override
{
// casting operator() to void* is not legal C++ if it's a member function
// and wouldn't necessarily be a useful thing to return anyway
check(0);
return nullptr;
}
virtual const void* GetRawUserObject() const override
{
// returning &Functor wouldn't be particularly useful to the comparison code
// as it would always be unique because we store a copy of the functor
check(0);
return nullptr;
}
virtual EDelegateInstanceType::Type GetType() const override
{
return EDelegateInstanceType::Functor;
}
virtual bool HasSameObject(const void* UserObject) const override
{
// Functor Delegates aren't bound to a user object so they can never match
return false;
}
virtual bool IsSafeToExecute() const override
{
// Functors are always considered safe to execute!
return true;
}
public:
// DELEGATE_INSTANCE_INTERFACE_CLASS interface
virtual DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* CreateCopy() override
{
return new FUNCTOR_DELEGATE_INSTANCE_CLASS(*this);
}
virtual RetValType Execute(FUNC_PARAM_LIST) const override
{
return Functor(DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN);
}
virtual FDelegateHandle GetHandle() const override
{
return Handle;
}
#if FUNC_IS_VOID
virtual bool ExecuteIfSafe(FUNC_PARAM_LIST) const override
{
Execute(FUNC_PARAM_PASSTHRU);
return true;
}
#endif
virtual bool IsSameFunction(const DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>& InOtherDelegate) const override
{
// There's no nice way to implement this (we don't have the type info necessary to compare against OtherDelegate's Functor)
return false;
}
public:
/**
* Creates a new static function delegate binding for the given function pointer.
*
* @param InFunctor C++ functor
* @return The new delegate.
*/
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create(const FunctorType& InFunctor DELEGATE_COMMA_PAYLOAD_LIST)
{
return new FUNCTOR_DELEGATE_INSTANCE_CLASS<FunctorType, FUNC_PAYLOAD_TEMPLATE_ARGS>(InFunctor DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create(FunctorType&& InFunctor DELEGATE_COMMA_PAYLOAD_LIST)
{
return new FUNCTOR_DELEGATE_INSTANCE_CLASS<FunctorType, FUNC_PAYLOAD_TEMPLATE_ARGS>(MoveTemp(InFunctor) DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
private:
FunctorType Functor;
// Payload member variables, if any.
FUNC_PAYLOAD_MEMBERS
// The handle of this delegate
FDelegateHandle Handle;
};
/**
* Implements a delegate binding for UFunctions.
*
* @params UserClass Must be an UObject derived class.
*/
template<class UserClass, FUNC_PAYLOAD_TEMPLATE_DECL_TYPENAME>
class UFUNCTION_DELEGATE_INSTANCE_CLASS
: public DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>
{
static_assert(TPointerIsConvertibleFromTo<UserClass, const UObjectBase>::Value, "You cannot use UFunction delegates with non UObject classes.");
// Structure for UFunction call parameter marshaling.
struct FParmsWithPayload
{
FUNC_PARAM_MEMBERS // (Param1Type Param1; Param2Type Param2; ...)
FUNC_PAYLOAD_MEMBERS // (Var1Type Var1; Var2Type Var2; ...)
#if !FUNC_IS_VOID
RetValType Result; // UFunction return value.
#endif
};
public:
/**
* Creates and initializes a new instance.
*
* @param InUserObject The UObject to call the function on.
* @param InFunctionName The name of the function call.
*/
UFUNCTION_DELEGATE_INSTANCE_CLASS( UserClass* InUserObject, const FName& InFunctionName DELEGATE_COMMA_PAYLOAD_LIST )
: FunctionName(InFunctionName)
, UserObjectPtr(InUserObject)
DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
, Handle(FDelegateHandle::GenerateNewHandle)
{
check(InFunctionName != NAME_None);
if (InUserObject != nullptr)
{
CachedFunction = UserObjectPtr->FindFunctionChecked(InFunctionName);
}
}
public:
// IDelegateInstance interface
virtual FName GetFunctionName( ) const override
{
return FunctionName;
}
virtual const void* GetRawMethodPtr( ) const override
{
return nullptr;
}
virtual const void* GetRawUserObject( ) const override
{
return UserObjectPtr.Get();
}
virtual EDelegateInstanceType::Type GetType() const override
{
return EDelegateInstanceType::UFunction;
}
virtual bool HasSameObject( const void* InUserObject ) const override
{
return (UserObjectPtr.Get() == InUserObject);
}
virtual bool IsCompactable( ) const override
{
return !UserObjectPtr.Get(true);
}
virtual bool IsSafeToExecute( ) const override
{
return UserObjectPtr.IsValid();
}
public:
// DELEGATE_INSTANCE_INTERFACE_CLASS interface
virtual DELEGATE_INSTANCE_INTERFACE_CLASS* CreateCopy( ) override
{
return new UFUNCTION_DELEGATE_INSTANCE_CLASS(*this);
}
virtual RetValType Execute( FUNC_PARAM_LIST ) const override
{
checkSlow(IsSafeToExecute());
FParmsWithPayload Parms = { DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN };
UserObjectPtr->ProcessEvent(CachedFunction, &Parms);
#if !FUNC_IS_VOID
return Parms.Result;
#endif
}
virtual FDelegateHandle GetHandle() const override
{
return Handle;
}
#if FUNC_IS_VOID
virtual bool ExecuteIfSafe( FUNC_PARAM_LIST ) const override
{
if (IsSafeToExecute())
{
Execute(FUNC_PARAM_PASSTHRU);
return true;
}
return false;
}
#endif
virtual bool IsSameFunction( const DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>& Other ) const override
{
// NOTE: Payload data is not currently considered when comparing delegate instances.
// See the comment in multi-cast delegate's Remove() method for more information.
return ((Other.GetType() == EDelegateInstanceType::UFunction) &&
(Other.GetRawUserObject() == GetRawUserObject()) &&
(Other.GetFunctionName() == GetFunctionName()));
}
// End DELEGATE_INSTANCE_INTERFACE_CLASS interface
public:
/**
* Creates a new UFunction delegate binding for the given user object and function name.
*
* @param InObject The user object to call the function on.
* @param InFunctionName The name of the function call.
* @return The new delegate.
*/
FORCEINLINE static DELEGATE_INSTANCE_INTERFACE_CLASS<FUNC_TEMPLATE_ARGS>* Create( UserClass* InUserObject, const FName& InFunctionName DELEGATE_COMMA_PAYLOAD_LIST )
{
return new UFUNCTION_DELEGATE_INSTANCE_CLASS(InUserObject, InFunctionName DELEGATE_COMMA_PAYLOAD_PASSTHRU);
}
public:
// Holds the cached UFunction to call.
UFunction* CachedFunction;
// Holds the name of the function to call.
FName FunctionName;
// The user object to call the function on.
TWeakObjectPtr<UserClass> UserObjectPtr;
// Payload member variables, if any.
FUNC_PAYLOAD_MEMBERS
// The handle of this delegate
FDelegateHandle Handle;
};
#endif // FUNC_IS_CONST
#undef SP_METHOD_DELEGATE_INSTANCE_CLASS
#undef RAW_METHOD_DELEGATE_INSTANCE_CLASS
#undef UOBJECT_METHOD_DELEGATE_INSTANCE_CLASS
#undef STATIC_DELEGATE_INSTANCE_CLASS
#undef UFUNCTION_DELEGATE_INSTANCE_CLASS
#undef DELEGATE_INSTANCE_INTERFACE_CLASS
#undef DELEGATE_QUALIFIER
#undef DELEGATE_COMMA_PAYLOAD_LIST
#undef DELEGATE_COMMA_PAYLOAD_PASSTHRU
#undef DELEGATE_COMMA_PAYLOAD_INITIALIZER_LIST
#undef DELEGATE_COMMA_PAYLOAD_PASSIN
#undef DELEGATE_PARAM_PASSTHRU_COMMA_PAYLOAD_PASSIN
#undef DELEGATE_PARAM_LIST_COMMA_PAYLOAD_LIST
#undef DELEGATE_PARMS_COLON_INITIALIZER_LIST
| 31.657116 | 184 | 0.778355 | [
"object"
] |
37236bde76dc73440f62b780e23bc13c2957fee9 | 6,119 | cpp | C++ | king/ancestry.cpp | statgen/topmed_variant_calling | cfd0242eada5a0c6ddd73695af22fa47af20f010 | [
"Apache-2.0"
] | 14 | 2018-09-06T18:04:33.000Z | 2021-09-17T16:27:27.000Z | king/ancestry.cpp | statgen/topmed_variant_calling | cfd0242eada5a0c6ddd73695af22fa47af20f010 | [
"Apache-2.0"
] | 6 | 2018-10-03T21:37:46.000Z | 2022-01-17T08:43:53.000Z | king/ancestry.cpp | statgen/topmed_variant_calling | cfd0242eada5a0c6ddd73695af22fa47af20f010 | [
"Apache-2.0"
] | 5 | 2019-05-14T18:30:22.000Z | 2021-12-13T22:06:09.000Z | //////////////////////////////////////////////////////////////////////
// ancestry.cpp
// (c) 2010-2019 Wei-Min Chen
//
// This file is distributed as part of the KING source code package
// and may not be redistributed in any form, without prior written
// permission from the author. Permission is granted for you to
// modify this file for your own personal use, but modified versions
// must retain this copyright notice and must not be distributed.
//
// Permission is granted for you to use this file to compile KING.
//
// All computer programs have bugs. Use this file at your own risk.
//
// Feb 22, 2019
#include "analysis.h"
#include <math.h>
#include "Kinship.h"
#include "KinshipX.h"
#include "MathStats.h"
#include "MathSVD.h"
#include "QuickIndex.h"
#include "MathCholesky.h"
#ifdef WITH_LAPACK
extern "C" void dgesdd_(char*, int*, int*, double*, int*, double*, double *, int*, double*, int*, double*, int*, int*, int*);
extern "C" void dgesvd_(char*, char*, int*, int*, double*, int*, double*, double*, int*, double*, int*, double*, int*, int*);
#endif
void Engine::SlidingWindows()
{
double sizeMainWindow = 20;
double sizeOffset = 2;
double mv_start, mv_stop;
Vector ancestry0, tancestry;
Matrix allancestry;
IntArray ancestryOneWindow;
for(int chr = 0; chr < SEXCHR; chr++){
int nW = 10; // (maxPos - sizeOffset) / sizeMainWindow + 1;
// for each window
// mv_start, mv_stop
tancestry = ancestry0;
OneWindowProjection(chr, mv_start, mv_stop, tancestry);
// derive ancestryOneWindow from tancestry
// majority vote here
// allancestry
}
}
void Engine::OneWindowProjection(int mv_chr, double mv_start, double mv_stop, Vector & ancestry)
{
IntArray ID(0), ID_UN(0);
int N = ancestry.Length();
for(int i = 0; i < N; i++){
if(ancestry[i] == 0 || ancestry[i] == 1) ID_UN.Push(i);
ID.Push(i);
}
int dimN = ID_UN.Length();
if(dimN < 2) return;
int dimM = markerCount;
Matrix X(dimM, dimN);
Matrix Z(dimM, ID.Length());
X.Zero(); Z.Zero();
int minorAllele;
int validSNP=0;
int byte, offset;
double p, g, mean, se;
int k, freqCount;
bool flipFlag;
for(int m = 0; m < markerCount; m ++){
if(chromosomes[m]!=mv_chr || bp[m] < mv_start || bp[m] >= mv_stop)
continue;
byte = m/16;
offset = m%16;
p = 0.0;
freqCount = 0;
for(int i = 0; i < dimN; i++){
k = ID_UN[i];
if(GG[1][k][byte] & shortbase[offset]){ // AA or Aa
p ++;
if(GG[0][k][byte] & shortbase[offset]) p ++; // AA
freqCount += 2;
}else if(GG[0][k][byte] & shortbase[offset]) // aa
freqCount += 2;
}
if(freqCount == 0) continue;
p /= freqCount;
flipFlag = false;
if(p > 0.5) {
flipFlag = true;
p = 1-p;
}
if(p < 0.001) continue;
mean = p*2;
se = sqrt(2*p*(1-p));
if(se < 1E-100) continue;
for(int i = 0; i < dimN; i++){
k = ID_UN[i];
g = -1.0;
if(GG[0][k][byte] & shortbase[offset]) // homozygote
g = (GG[1][k][byte] & shortbase[offset])? 2.0: 0.0;
else if(GG[1][k][byte] & shortbase[offset]) // Aa
g = 1.0;
if(g > -0.9){
if(flipFlag)
X[validSNP][i] = (2 - g - mean) / se;
else
X[validSNP][i] = (g - mean) / se;
}
}
for(int i = 0; i < ID.Length(); i++){
k = ID[i];
g = -1.0;
if(GG[0][k][byte] & shortbase[offset]) // homozygote
g = (GG[1][k][byte] & shortbase[offset])? 2.0: 0.0;
else if(GG[1][k][byte] & shortbase[offset]) // Aa
g = 1.0;
if(g > -0.9) {
if(flipFlag)
Z[validSNP][i] = (2 - g - mean) / se;
else
Z[validSNP][i] = (g - mean) / se;
}
}
validSNP++;
}
dimM = validSNP;
if(dimM == 0) return; // no SNPs involved
X.Dimension(dimM, dimN);
Z.Dimension(dimM, ID.Length());
#ifdef WITH_LAPACK
char JOBU = 'S';
char JOBVT = 'O';
int LDU = dimM;
int LDVT = 1;
int dimS = dimM>dimN? dimN: dimM;
int info;
double *A = (double *)malloc(dimM*dimN*sizeof(double));
for(int i = 0; i < dimM; i++)
for(int j = 0; j < dimN; j++)
A[j*dimM+i] = X[i][j];
double *S = (double *)malloc(dimS*sizeof(double));
double *U = (double *)malloc(LDU*dimS*sizeof(double));
double *VT = (double *)malloc(LDVT*sizeof(double));
int LWORK = dimM>dimN? dimM*2+8*dimN: dimN+8*dimM;
double *WORK = (double *)malloc(LWORK*sizeof(double));
dgesvd_(&JOBU, &JOBVT, &dimM, &dimN, A, &dimM, S, U, &LDU, VT, &LDVT, WORK, &LWORK, &info);
if(info!=0) error("SVD failed.");
free(WORK);
free(A);
free(VT);
int dimPC = 2;
Matrix EV(ID.Length(), dimPC);
EV.Zero();
for(int i = 0; i < ID.Length(); i++)
for(int j = 0; j < dimPC; j++){
for(int m = 0; m < dimM; m++)
EV.data[i]->data[j] += Z.data[m]->data[i] * U[j*dimM+m];
if(S[j] > 1E-100)
EV[i][j] /= S[j];
}
free(U);
free(S);
#else
SVD svd;
svd.Decompose(X);
if(svd.n == 0) return;
QuickIndex idx;
idx.Index(svd.w);
int dimPC = 2;
Matrix EV(ID.Length(), dimPC);
EV.Zero();
for(int i = 0; i < ID.Length(); i++)
for(int j = 0; j < dimPC; j++){
for(int m = 0; m < dimM; m++)
EV[i][j] += Z[m][i] * svd.u[m][idx[dimN-1-j]];
if(svd.w[idx[dimN-1-j]] > 1E-10)
EV[i][j] /= svd.w[idx[dimN-1-j]];
}
#endif
Vector ref0(0), ref1(0);
for(int i = 0; i < N; i++){
if(ancestry[i]==0) ref0.Push(EV[i][0]);
else if(ancestry[i]==1) ref1.Push(EV[i][0]);
}
double x0, x1;
if(ref0.Max() > ref1.Max()) {
x0 = ref0.Max();
x1 = ref1.Min();
}else{
x0 = ref0.Min();
x1 = ref1.Max();
}
for(int i = 0; i < N; i++){
if(ancestry[i] == 0 || ancestry[i] == 1) continue;
ancestry[i] = (EV[i][0] - x0) / (x1 - x0);
}
}
| 28.593458 | 125 | 0.518059 | [
"vector"
] |
3723a399401de69c1c7bfaa5de9aaf4ee71ca3c6 | 392 | hpp | C++ | OpenGLlession_2/OpenGLlession_2/shape.hpp | lianyuzhe/OpenGL | 7145474bab5ed12f901932bfb5a0234e75ccfbab | [
"MIT"
] | null | null | null | OpenGLlession_2/OpenGLlession_2/shape.hpp | lianyuzhe/OpenGL | 7145474bab5ed12f901932bfb5a0234e75ccfbab | [
"MIT"
] | null | null | null | OpenGLlession_2/OpenGLlession_2/shape.hpp | lianyuzhe/OpenGL | 7145474bab5ed12f901932bfb5a0234e75ccfbab | [
"MIT"
] | null | null | null | //
// shape.hpp
// OpenGLlession_2
//
// Created by lianyuzhe on 2017/1/26.
// Copyright © 2017年 lianyuzhe. All rights reserved.
//
#ifndef shape_hpp
#define shape_hpp
#include "define.h"
#include <cmath>
#include <iostream>
void generateTours(float * verts, float * norms, float * tex,unsigned int * el,float outerRadius, float innerRadius,int sides, int rings);
#endif /* shape_hpp */
| 24.5 | 138 | 0.716837 | [
"shape"
] |
37255d2b0c34a4da37f790c203a56940642c1de5 | 9,230 | cpp | C++ | old/src/Engine/glrendering.cpp | ttfractal44/MechSandbox | 75ac111b094ba1a93e77908048704a98afb72deb | [
"MIT"
] | null | null | null | old/src/Engine/glrendering.cpp | ttfractal44/MechSandbox | 75ac111b094ba1a93e77908048704a98afb72deb | [
"MIT"
] | null | null | null | old/src/Engine/glrendering.cpp | ttfractal44/MechSandbox | 75ac111b094ba1a93e77908048704a98afb72deb | [
"MIT"
] | null | null | null | /*
* glrendering.cpp
*
* Created on: Dec 8, 2014
* Author: theron
*/
#include "datastructures.h"
#include "world.h"
#include "../misc/utils.h"
#include "glrendering.h"
#include "userinput.h"
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/glu.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <stdio.h>
#include <string>
namespace Engine {
World* renderWorld;
bool runLoopThreads = true;
SDL_Thread* renderLoopThread;
SDL_Window* sdlWindow;
SDL_GLContext sdlglContext;
int frame=0;
int lastTime = 0;
int lastFrame = 0;
float currentFPS;
int updateFPSInterval = 60;
bool printFPS = false;
bool windowResize = false;
void waitNextRefresh() {
SDL_GL_SwapWindow(sdlWindow);
}
void setGraphicsRenderWorld(World* world) {
renderWorld = world;
}
void initSDLGLRendering() {
SDL_Init(SDL_INIT_EVERYTHING);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
sdlWindow = SDL_CreateWindow("GLTest", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1066,600,SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
sdlglContext = SDL_GL_CreateContext(sdlWindow);
//sdlglContext = SDL_GL_CreateContext(NULL);
glewExperimental = GL_TRUE;
glewInit();
SDL_GL_SetSwapInterval(1);
printf("GL Vendor: %s\n",glGetString(GL_VENDOR));
printf("GL Renderer: %s\n",glGetString(GL_RENDERER));
printf("GL Version: %s\n",glGetString(GL_VERSION));
printf("GL Shader Version: %s\n",glGetString(GL_SHADING_LANGUAGE_VERSION));
// WORLD SHADERS
renderWorld->basicEntityShaderProgram = compileShader("vertex.glsl","fragment.glsl");
assert(renderWorld->basicEntityShaderProgram);
glEnable(GL_DEPTH_TEST);
}
void destroySDLGLRendering() {
//
}
void render() {
if (windowResize) {
int width;
int height;
SDL_GetWindowSize(sdlWindow, &width, &height);
glViewport(0,0,width,height);
windowResize=false;
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Engine::drawWorld(renderWorld);
frame+=1;
if (frame%updateFPSInterval==0) {
int time = SDL_GetTicks();
currentFPS = (float)(frame-lastFrame)/(time-lastTime)*1000;
if (printFPS) {
printf("%f FPS\n",currentFPS);
}
lastTime = time;
lastFrame = frame;
}
SDL_GL_SwapWindow(sdlWindow);
}
void renderLoop() {
while (runLoopThreads) {
render();
}
}
int renderLoopThreadFunc(void *p) {
//initSDLGLRendering();
SDL_GL_MakeCurrent(sdlWindow,sdlglContext);
renderLoop();
return 0;
}
void startRenderLoopThread() {
renderLoopThread = SDL_CreateThread(renderLoopThreadFunc, "renderLoopThread", (void *)NULL);
}
void drawWorld(World* world) {
World::Camera* camera = world->renderCamera;
camera->proj = glm::perspective(90.0f, 1066.0f / 600.0f, 0.0001f, 100.0f);
camera->view = glm::lookAt(
camera->position,
camera->position + getCameraForwardVector(camera),
getCameraUpVector(camera)
);
for (unsigned int i=0; i<(world->entities.size()); i++) {
drawEntity(world->entities[i]);
}
}
void drawEntity(World::Entity* entity) {
if (!entity->vertexBufferId) {
printf("Entity being drawn before initializeEntityDrawBuffers!\n");
initializeEntityDrawing(entity);
}
glBindVertexArray(entity->vertexArrayId);
//printf("### entity->vertexArrayId=%d\n",entity->vertexArrayId);
//printf("glBindVertexArray(entity->vertexArrayId);\n");
//glUseProgram(0);
//printf("glUseProgram(0);\n");
glUseProgram(entity->shaderProgram);
//printf("### entity->shaderProgram=%d\n",entity->shaderProgram);
//printf("glUseProgram(entity->shaderProgram);\n");
//printf("### entity->vertexBufferId=%d\n",entity->vertexBufferId);
glBindBuffer(GL_ARRAY_BUFFER, entity->vertexBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, entity->elementBufferId);
//printf("glBindBuffer(GL_ARRAY_BUFFER, entity->vertexBufferId);\n");
glUniformMatrix4fv(entity->modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(entity->model));
///printf("glUniformMatrix4fv(entity->modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(entity->model));\n");
glUniformMatrix4fv(entity->viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(entity->world->renderCamera->view));
//printf("glUniformMatrix4fv(entity->viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(entity->world->renderCamera->view));\n");
glUniformMatrix4fv(entity->projMatrixLocation, 1, GL_FALSE, glm::value_ptr(entity->world->renderCamera->proj));
//printf("glUniformMatrix4fv(entity->projMatrixLocation, 1, GL_FALSE, glm::value_ptr(entity->world->renderCamera->proj));\n");
//printf("### entity->graphicsMesh.numelements=%d\n", entity->graphicsMesh.numelements);
//glDrawArrays(GL_TRIANGLES, 0, entity->graphicsMesh.numelements);
glDrawElements(GL_TRIANGLES, entity->graphicsMesh.numelements, GL_UNSIGNED_INT, 0);
//printf("glDrawArrays(GL_TRIANGLES, 0, entity->graphicsMesh.numelements);\n");
glBindBuffer(GL_ARRAY_BUFFER, 0);
//printf("glBindBuffer(GL_ARRAY_BUFFER, 0);\n");
}
GLuint compileShader(std::string vertexShaderPath, std::string fragmentShaderPath) {
std::string vertexShaderSourceStr = readResource("shaders/"+vertexShaderPath).c_str();
std::string fragmentShaderSourceStr = readResource("shaders/"+fragmentShaderPath).c_str();
const GLchar* vertexShaderSource = vertexShaderSourceStr.c_str();
const GLchar* fragmentShaderSource = fragmentShaderSourceStr.c_str();
bool error=false;
GLint vertexShaderStatus;
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &vertexShaderStatus);
if (vertexShaderStatus!=GL_TRUE) {
printf("Vertex shader error!\n");
char buffer[512];
glGetShaderInfoLog(vertexShader, 512, NULL, buffer);
printf("%s\n",buffer);
//printf("Vertex shader source:\n%s\n",vertexShaderSource);
error=true;
}
GLint fragmentShaderStatus;
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &fragmentShaderStatus);
if (fragmentShaderStatus!=GL_TRUE) {
printf("Fragment shader error!\n");
char buffer[512];
glGetShaderInfoLog(fragmentShader, 512, NULL, buffer);
printf("%s\n",buffer);
//printf("Fragment shader source:\n%s\n",fragmentShaderSource);
error=true;
}
if (!error) {
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glBindFragDataLocation(shaderProgram, 0, "outColor");
glLinkProgram(shaderProgram);
return shaderProgram;
} else {
return 0;
}
}
void initializeEntityDrawing(World::Entity* entity) {
glGenVertexArrays(1, &entity->vertexArrayId);
glBindVertexArray(entity->vertexArrayId);
glGenBuffers(1, &entity->vertexBufferId);
printf("Entity vertex buffer generated at id %i\n",entity->vertexBufferId);
glBindBuffer(GL_ARRAY_BUFFER, entity->vertexBufferId);
glGenBuffers(1, &entity->elementBufferId);
printf("Entity element buffer generated at id %i\n",entity->elementBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, entity->elementBufferId);
GLint vertexPositionAttrib = glGetAttribLocation(entity->shaderProgram, "position");
glEnableVertexAttribArray(vertexPositionAttrib);
glVertexAttribPointer(vertexPositionAttrib, 3, GL_FLOAT, GL_FALSE, 9*sizeof(GLfloat), 0);
GLint vertexColorAttrib = glGetAttribLocation(entity->shaderProgram, "color");
glEnableVertexAttribArray(vertexColorAttrib);
glVertexAttribPointer(vertexColorAttrib, 3, GL_FLOAT, GL_FALSE, 9*sizeof(GLfloat), (void*)(3*sizeof(GLfloat)));
GLint vertexNormalAttrib = glGetAttribLocation(entity->shaderProgram, "normal");
glEnableVertexAttribArray(vertexNormalAttrib);
glVertexAttribPointer(vertexNormalAttrib, 3, GL_FLOAT, GL_FALSE, 9*sizeof(GLfloat), (void*)(6*sizeof(GLfloat)));
entity->modelMatrixLocation = glGetUniformLocation(entity->shaderProgram, "model");
entity->viewMatrixLocation = glGetUniformLocation(entity->shaderProgram, "view");
entity->projMatrixLocation = glGetUniformLocation(entity->shaderProgram, "proj");
}
void updateEntityDrawBuffers(World::Entity* entity) {
if (!entity->vertexBufferId) {
printf("Entity draw buffers called to be updated before initializeEntityDrawBuffers!\n");
initializeEntityDrawing(entity);
}
glBindBuffer(GL_ARRAY_BUFFER, entity->vertexBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, entity->elementBufferId);
glBufferData(GL_ARRAY_BUFFER, entity->graphicsMesh.vertices.size()*sizeof(GLfloat), &entity->graphicsMesh.vertices.front(), GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, entity->graphicsMesh.elements.size()*sizeof(GLuint), &entity->graphicsMesh.elements.front(), GL_STATIC_DRAW);
entity->graphicsMesh.numelements = entity->graphicsMesh.elements.size();
printf("numelements=%d\n",entity->graphicsMesh.numelements);
}
void updateAllDrawBuffersInWorld(World* world) {
for (unsigned int i=0; i<(world->entities.size()); i++) {
updateEntityDrawBuffers(world->entities[i]);
}
}
}
| 31.609589 | 148 | 0.763272 | [
"render",
"model"
] |
37291115364776db2b35dea7148a0170d2582cbc | 4,036 | cpp | C++ | src/Engine/PluginManager.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | 2 | 2015-01-14T20:20:51.000Z | 2015-09-08T15:49:18.000Z | src/Engine/PluginManager.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | null | null | null | src/Engine/PluginManager.cpp | CronosTs/phobos3d | c0336456d946f3a9e62fb9b7815831ad32820da5 | [
"Zlib"
] | 1 | 2015-11-03T13:58:58.000Z | 2015-11-03T13:58:58.000Z | /*
Phobos 3d
September 2010
Copyright (c) 2005-2011 Bruno Sanches http://code.google.com/p/phobos3d
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 "Phobos/Engine/PluginManager.h"
#include <Phobos/Shell/Utils.h>
#include <Phobos/Error.h>
#include <Phobos/Exception.h>
#include <Phobos/Memory.h>
#include "Phobos/Engine/Console.h"
#include "Phobos/Engine/PluginInstance.h"
Phobos::Engine::PluginManagerPtr_t Phobos::Engine::PluginManager::ipInstance_gl;
Phobos::Engine::PluginManager &Phobos::Engine::PluginManager::CreateInstance(void)
{
PH_ASSERT(!ipInstance_gl);
ipInstance_gl.reset(PH_NEW PluginManager());
return *ipInstance_gl;
}
Phobos::Engine::PluginManager &Phobos::Engine::PluginManager::GetInstance(void)
{
return *ipInstance_gl;
}
void Phobos::Engine::PluginManager::ReleaseInstance(void)
{
ipInstance_gl.reset();
}
Phobos::Engine::PluginManager::PluginManager():
Module("PluginManager", NodeFlags::PRIVATE_CHILDREN),
m_cmdLoadPlugin("loadPlugin"),
m_cmdUnloadPlugin("unloadPlugin"),
m_fSystemReady(false)
{
m_cmdLoadPlugin.SetProc(PH_CONTEXT_CMD_BIND(&PluginManager::CmdLoadPlugin, this));
m_cmdUnloadPlugin.SetProc(PH_CONTEXT_CMD_BIND(&PluginManager::CmdUnloadPlugin, this));
}
Phobos::Engine::PluginManager::~PluginManager()
{
//empty
}
void Phobos::Engine::PluginManager::OnPrepareToBoot()
{
Console &console = Console::GetInstance();
console.AddContextCommand(m_cmdLoadPlugin);
console.AddContextCommand(m_cmdUnloadPlugin);
}
void Phobos::Engine::PluginManager::OnFinalize()
{
this->RemoveAllChildren();
}
void Phobos::Engine::PluginManager::OnRenderReady()
{
m_fSystemReady = true;
}
void Phobos::Engine::PluginManager::OnUpdate()
{
if(!m_fSystemReady)
return;
while(!m_lstPluginsToActivate.empty())
{
String_t pluginName;
pluginName.swap(m_lstPluginsToActivate.front());
m_lstPluginsToActivate.pop_front();
PluginInstance *plugin = static_cast<PluginInstance *>(this->TryGetChild(pluginName));
if(plugin)
{
plugin->Init();
}
}
}
void Phobos::Engine::PluginManager::LoadPlugin(const String_t &name)
{
{
std::unique_ptr<PluginInstance> plugin(PH_NEW PluginInstance(name));
this->AddPrivateChild(std::move(plugin));
}
m_lstPluginsToActivate.push_back(name);
}
void Phobos::Engine::PluginManager::UnloadPlugin(const String_t &name)
{
this->RemoveChild(this->GetChild(name));
}
void Phobos::Engine::PluginManager::CmdLoadPlugin(const Shell::StringVector_t &args, Shell::Context &)
{
if(args.size() < 2)
{
LogMessage("[PluginManager::CmdLoadPlugin] Insuficient parameters, usage: loadPlugin <pluginName> [pluginName1] [pluginName2] [pluginNamen]");
return;
}
for(int i = 1, len = args.size(); i < len; ++i)
{
try
{
this->LoadPlugin(args[i]);
}
catch(Exception &e)
{
LogMessage(e.what());
}
}
}
void Phobos::Engine::PluginManager::CmdUnloadPlugin(const Shell::StringVector_t &args, Shell::Context &)
{
if(args.size() < 2)
{
LogMessage("[PluginManager::CmdUnloadPlugin] Insuficient parameters, usage: unloadPlugin <pluginName> [pluginName1] [pluginName2] [pluginNamen]");
return;
}
for(int i = 1, len = args.size(); i < len; ++i)
{
try
{
this->UnloadPlugin(args[i]);
}
catch(Exception &e)
{
LogMessage(e.what());
}
}
}
| 25.544304 | 243 | 0.748018 | [
"3d"
] |
372aad7d105b07fbe4f13f01db2794befde0b088 | 598 | cpp | C++ | aoc2018/aoc180302.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | aoc2018/aoc180302.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | aoc2018/aoc180302.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | #include <fstream>
#include <iostream>
#include <fmt/format.h>
#include <numeric>
#include <algorithm>
#include <set>
using gint = std::int64_t;
int main(int argc, char **argv)
{
if (argc > 1) {
std::ifstream ifs(argv[1]);
std::istream_iterator<int> b(ifs);
std::istream_iterator<int> e;
std::set<int> his;
std::vector<int> v(b, e);
int s = 0;
for (auto i = v.begin();; ++i) {
if (i == v.end()) {
i = v.begin();
}
s += *i;
auto [it, v] = his.insert(s);
if (!v) {
fmt::print("{}\n", *it);
break;
}
}
}
} | 20.62069 | 38 | 0.503344 | [
"vector"
] |
372b4b1e3dc4b49d9cc23046c8cb977b22d493b2 | 715 | hpp | C++ | Questless/Questless/src/entities/perception.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | 2 | 2020-07-14T12:50:06.000Z | 2020-11-04T02:25:09.000Z | Questless/Questless/src/entities/perception.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | null | null | null | Questless/Questless/src/entities/perception.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | null | null | null | //! @file
//! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>.
#pragma once
#include "bounded/static.hpp"
#include "entities/beings/stats/vision.hpp"
#include "quantities/misc.hpp"
#include "reg.hpp"
#include "world/coordinates.hpp"
#include "cancel/quantity.hpp"
#include <vector>
namespace ql {
static constexpr auto max_perception = 100_perception;
//! The maximum possible distance a being with vision list @p vision_sources could see.
auto max_visual_range(std::vector<stats::vision> const& vision_sources) -> pace;
//! The nonnegative perception of the @p target tile by the being with ID @p perceptor_id.
auto perception_of(reg& reg, id perceptor_id, tile_hex_point target) -> perception;
}
| 28.6 | 91 | 0.74965 | [
"vector"
] |
372d5b9b85b56ebc67c12a421f94443feb7f67e5 | 742 | cpp | C++ | cpp/main.cpp | altayhunter/xkcd-2529 | 8ab52c33135e3cedfc4d3816a5a4eb3a21c8a3bb | [
"MIT"
] | 1 | 2021-11-22T23:17:55.000Z | 2021-11-22T23:17:55.000Z | cpp/main.cpp | altayhunter/xkcd-2529 | 8ab52c33135e3cedfc4d3816a5a4eb3a21c8a3bb | [
"MIT"
] | null | null | null | cpp/main.cpp | altayhunter/xkcd-2529 | 8ab52c33135e3cedfc4d3816a5a4eb3a21c8a3bb | [
"MIT"
] | null | null | null | #include "walker.hpp" // Walker
#include <iostream> // cout
#include <numeric> // accumulate
using namespace std;
double average(const vector<uint64_t>& v) {
uint64_t sum = accumulate(v.begin(), v.end(), 0);
return static_cast<double>(sum) / v.size();
}
int main() {
unsigned n = 4;
unsigned k = 1000;
unsigned runs = 1000000;
vector<uint64_t> steps;
vector<uint64_t> intersections;
steps.reserve(runs);
intersections.reserve(runs);
for (unsigned i = 0; i < runs; i++) {
Walker w(n, k);
steps.push_back(w.steps());
intersections.push_back(w.intersections());
}
cout << "Average of " << runs << " runs is " << average(steps)
<< " steps and " << average(intersections)
<< " intersections" << endl;
return 0;
};
| 24.733333 | 63 | 0.652291 | [
"vector"
] |
373835c507121b59f03799ec6bb1578ada8e04da | 1,913 | hpp | C++ | include/types.hpp | Portwell-BMC/pw-ipmi-oem | 1fbd25c9a0c96e03a9cbbb907d2b65e4d6d4e94c | [
"Apache-2.0"
] | 9 | 2018-11-05T23:39:18.000Z | 2021-12-01T12:10:34.000Z | include/types.hpp | Portwell-BMC/pw-ipmi-oem | 1fbd25c9a0c96e03a9cbbb907d2b65e4d6d4e94c | [
"Apache-2.0"
] | 6 | 2019-03-25T15:16:56.000Z | 2022-03-30T23:27:47.000Z | include/types.hpp | Portwell-BMC/pw-ipmi-oem | 1fbd25c9a0c96e03a9cbbb907d2b65e4d6d4e94c | [
"Apache-2.0"
] | 9 | 2018-11-27T08:02:32.000Z | 2021-05-21T16:36:50.000Z | /*
// Copyright (c) 2017 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#pragma once
#include <map>
#include <string>
#include <tuple>
#include <utility>
#include <variant>
#include <vector>
namespace ipmi
{
using Association = std::tuple<std::string, std::string, std::string>;
using DbusVariant =
std::variant<std::string, bool, uint8_t, uint16_t, int16_t, uint32_t,
int32_t, uint64_t, int64_t, double, std::vector<Association>>;
using GetSubTreeType = std::vector<
std::pair<std::string,
std::vector<std::pair<std::string, std::vector<std::string>>>>>;
using SensorMap = std::map<std::string, std::map<std::string, DbusVariant>>;
namespace types
{
namespace details
{
template <typename U>
using underlying_t =
typename std::conditional_t<std::is_enum_v<U>, std::underlying_type<U>,
std::enable_if<true, U>>::type;
} // namespace details
/**
* @brief Converts a number or enum class to another
* @tparam R - The output type
* @tparam T - The input type
* @param t - An enum or integer value to cast
* @return The value in R form
*/
template <typename R, typename T>
inline R enum_cast(T t)
{
auto tu = static_cast<details::underlying_t<T>>(t);
auto ru = static_cast<details::underlying_t<R>>(tu);
return static_cast<R>(ru);
}
} // namespace types
} // namespace ipmi
| 27.328571 | 79 | 0.687925 | [
"vector"
] |
3738388c5447b094d84b658a76f367f69018f2c8 | 2,782 | cpp | C++ | tc 160+/RequiredSubstrings.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/RequiredSubstrings.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/RequiredSubstrings.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
const int mod = 1000000009;
int C, L;
vector<string> W;
int len[6][51][6];
int next[6][51][6][26];
int dp[50][1<<6][6][50];
int bc[1<<6];
int go(int at, int mask, int w, int l) {
if (bc[mask] > C) {
return 0;
}
if (at == L) {
return (bc[mask] == C);
}
int &ret = dp[at][mask][w][l];
if (ret != -1) {
return ret;
}
ret = 0;
for (int c='a'; c<='z'; ++c) {
int foundmask = 0;
int okmask = 0;
for (int i=0; i<(int)W.size(); ++i) {
if (len[w][l][i]<(int)W[i].size() && W[i][len[w][l][i]]==c) {
if (len[w][l][i]+1 == (int)W[i].size()) {
foundmask |= (1<<i);
} else {
okmask |= (1<<i);
}
}
}
int bestlen = -1;
int nw = 0;
for (int i=0; i<(int)W.size(); ++i) {
if (okmask & (1<<i)) {
if (len[w][l][i] > bestlen) {
bestlen = len[w][l][i];
nw = i;
}
} else if (!(foundmask&(1<<i)) && next[w][l][i][c-'a']>bestlen) {
bestlen = next[w][l][i][c-'a'];
nw = i;
}
}
ret += go(at+1, mask|foundmask, nw, bestlen+1);
if (ret >= mod) {
ret -= mod;
}
}
return ret;
}
class RequiredSubstrings {
public:
int solve(vector <string> words, int C, int L) {
::C = C;
::L = L;
W = words;
memset(len, 0, sizeof len);
memset(next, 0xff, sizeof next);
for (int i=0; i<(int)W.size(); ++i) {
for (int j=0; j<(int)W.size(); ++j) {
for (int l=1; l<=(int)W[i].size(); ++l) {
next[i][l][j][W[j][0]-'a'] = 0;
for (int k=min(l, (int)W[j].size()); k>0; --k) {
if (W[i].substr(l-k, k) == W[j].substr(0, k)) {
if (len[i][l][j] == 0) {
len[i][l][j] = k;
}
if (k < (int)W[j].size()) {
int nextc = W[j][k];
next[i][l][j][nextc-'a'] = max(next[i][l][j][nextc-'a'], k);
}
}
}
}
}
}
for (int i=1; i<(1<<W.size()); ++i) {
bc[i] = bc[i>>1] + (i&1);
}
memset(dp, 0xff, sizeof dp);
return go(0, 0, 0, 0);
}
};
| 27.82 | 92 | 0.354062 | [
"vector"
] |
3745dd89cc83b49926fb1a71f36d49d8babe3ce8 | 2,800 | hh | C++ | include/WCSimLikelihoodDigitArray.hh | chipsneutrino/chips-reco | 0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba | [
"MIT"
] | null | null | null | include/WCSimLikelihoodDigitArray.hh | chipsneutrino/chips-reco | 0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba | [
"MIT"
] | null | null | null | include/WCSimLikelihoodDigitArray.hh | chipsneutrino/chips-reco | 0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba | [
"MIT"
] | null | null | null | /**
* \class WCSimLikelihoodDigitArray
* A class to hold one WCSimLikelihoodDigit for every
* PMT in the detector, hit or unhit.
* It contains all the detector information used to fit
* a single event
*/
#pragma once
#include <vector>
#include "WCSimLikelihoodDigit.hh"
#include "WCSimRootEvent.hh"
#include "TClonesArray.h"
#include "TObject.h"
class WCSimLikelihoodDigitArray : public TObject
{
public:
/**
* Geometry type enum
*/
enum GeomType_t
{
kUnknown = 0, //!< Unknown type
kCylinder = 1, //!< Detector is a cylinder
kMailBox = 2 //!< Detector is a cuboid
};
//TODO: we have a pointer as class member, so there should be
// a proper copy constructor and proper destructor...
WCSimLikelihoodDigitArray();
/**
* Constructor
* @param myRootEvent Event object from WCSim to build hit list from
*/
WCSimLikelihoodDigitArray(WCSimRootEvent *myRootEvent);
/**
* Constructor using undigitized hits for debugging
* @param myRootEvent Event object from WCSim to build the hit list from
* @param useUndigitized A hack to call the undigitized constructor. Has to be true.
*/
WCSimLikelihoodDigitArray(WCSimRootEvent *myRootEvent, Bool_t useUndigitized);
virtual ~WCSimLikelihoodDigitArray();
/**
* Get a single WCSimLikelihoodDigit object
* @param digit The digit's position in the TClonesArray (NOT its WCSim tubeID)
* @return The WCSimLikelihoodDigit at this place in the array
*/
WCSimLikelihoodDigit *GetDigit(Int_t digit);
/**
* @return Total number of digits in the array (i.e. PMTs in the detector)
*/
Int_t GetNDigits();
/**
* @return Total number of digits in the array with a non-zero hit (that
* passed the filtering step)
* */
Int_t GetNHits();
/**
* @return True if detector is a cylinder
*/
Bool_t IsCylinder();
/**
* @return True if detector is a mailbox (cuboid)
*/
Bool_t IsMailBox();
/**
* @return The geometry type enum for this detector
*/
GeomType_t GetGeomType();
/**
* @param i (0,1,2) for (x,y,z) if a mailbox and (r,r,z) if a cylinder
* @return The co-ordinate at which a particle will exit the detector volume
*/
Double_t GetExtent(Int_t i);
Double_t GetDuration() const;
protected:
private:
TClonesArray *fLikelihoodDigitArray; ///< Array with every PMT and its hit information
Int_t fNLikelihoodDigits; ///< Total number of PMTs
Int_t fNumHitPMTs; ///< Total number of hit PMTs, ie. ones with Q>0 that weren't filtered out
GeomType_t fGeomType; ///< Detector geometry type
Double_t fExtent[3]; ///< Maximum (x, y, z) or (r,r,z) in the detector
Double_t fFirstTime; ///< Time of earliest filtered PMT hit
Double_t fLastTime; ///< Time of latest filtered PMT hit
ClassDef(WCSimLikelihoodDigitArray, 1)
};
| 27.45098 | 99 | 0.702143 | [
"geometry",
"object",
"vector"
] |
37580de3708a11d96081a3fe105b38b70c51188c | 5,799 | hpp | C++ | include/shadertoy/buffers/program_buffer.hpp | vtavernier/libshadertoy | a0b2a133199383cc7e9bcb3c0300f39eb95177c0 | [
"MIT"
] | 2 | 2020-02-23T09:33:07.000Z | 2021-11-15T18:23:13.000Z | include/shadertoy/buffers/program_buffer.hpp | vtavernier/libshadertoy | a0b2a133199383cc7e9bcb3c0300f39eb95177c0 | [
"MIT"
] | 2 | 2019-08-09T15:48:07.000Z | 2020-11-16T13:51:56.000Z | include/shadertoy/buffers/program_buffer.hpp | vtavernier/libshadertoy | a0b2a133199383cc7e9bcb3c0300f39eb95177c0 | [
"MIT"
] | 3 | 2019-12-12T09:42:34.000Z | 2020-12-14T03:56:30.000Z | #ifndef _SHADERTOY_BUFFERS_PROGRAM_BUFFER_HPP_
#define _SHADERTOY_BUFFERS_PROGRAM_BUFFER_HPP_
#include "shadertoy/pre.hpp"
#include "shadertoy/buffers/gl_buffer.hpp"
#include "shadertoy/program_input.hpp"
#include "shadertoy/program_interface.hpp"
#include "shadertoy/compiler/program_template.hpp"
#include <deque>
#define SHADERTOY_ICHANNEL_COUNT 4
namespace shadertoy
{
namespace buffers
{
/**
* @brief Represents a buffer that processes its inputs with a shader
*/
class shadertoy_EXPORT program_buffer : public gl_buffer
{
private:
/// Buffer program
gl::program program_;
/// Program interface details
std::unique_ptr<program_interface> program_interface_;
/// Inputs for this shader
std::deque<program_input> inputs_;
/// Alternative template to use when generating the program for this buffer
std::shared_ptr<compiler::program_template> override_program_;
/// Template part that this buffer should provide to the shader template
std::unique_ptr<compiler::basic_part> source_;
/// Pointer to the map to store compiled sources
std::map<GLenum, std::string> *source_map_;
protected:
/**
* @brief Initialize the geometry to use for this buffer
*
* @param[in] context Rendering context to use for shared objects
* @param[in] io IO resource object
*/
virtual void init_geometry(const render_context &context, const io_resource &io) = 0;
/**
* @brief Render the geometry for this buffer. The inputs, program and framebuffer
* are already bound by the caller.
*
* @param[in] context Rendering context to use for rendering this buffer
* @param[in] io IO resource object
*/
virtual void render_geometry(const render_context &context, const io_resource &io) = 0;
/**
* @brief Initialize the contents of this buffer
*
* @param[in] context Rendering context to use for shared objects
* @param[in] io IO resource object
*/
void init_contents(const render_context &context, const io_resource &io) override;
/**
* @brief Render the contents of this buffer.
*
* @param[in] context Rendering context to use for rendering this buffer
* @param[in] io IO resource object
*/
void render_gl_contents(const render_context &context, const io_resource &io) override;
public:
/**
* @brief Initialize a new ShaderProgram buffer
*
* @param[in] id Identifier for this buffer
*/
program_buffer(const std::string &id);
/**
* @brief Get a reference to the program represented by this buffer
*
* @return OpenGL program for this buffer.
*/
inline const gl::program &program() const
{ return program_; }
/**
* @brief Get a reference to the input array for this buffer
*
* @return Reference to the input array for this buffer
*/
inline const std::deque<program_input> &inputs() const
{ return inputs_; }
/**
* @brief Get a reference to the input array for this buffer
*
* @return Reference to the input array for this buffer
*/
inline std::deque<program_input> &inputs()
{ return inputs_; }
/**
* @brief Get the current override program template for this buffer
*
* @return Pointer to the override program, or null if this buffer is using the default program template
*/
inline const std::shared_ptr<compiler::program_template> &override_program() const
{ return override_program_; }
/**
* @brief Set the current override program template for this buffer
*
* @param new_program Pointer to the override program template, or null if
* this buffer should use the default program template
*/
inline void override_program(std::shared_ptr<compiler::program_template> new_program)
{ override_program_ = new_program; }
/**
* @brief Get a reference to the current source part for this buffer
*
* @return Pointer to the source part
*/
inline const std::unique_ptr<compiler::basic_part> &source() const
{ return source_; }
/**
* @brief Set the sources for this buffer to the given part
*
* @param new_part New part to use as sources for this buffer
*/
inline void source(std::unique_ptr<compiler::basic_part> new_part)
{ source_ = std::move(new_part); }
/**
* @brief Set the sources for this buffer from the given part
*
* @param new_source New source string to use for compiling this buffer
*/
void source(const std::string &new_source);
/**
* @brief Set the sources for this buffer from the given part from a file
*
* The target file will be read everytime this buffer is being compiled. Use
* program_buffer#source if you want to cache the file's contents.
*
* @param new_file New file to load the sources from
*/
void source_file(const std::string &new_file);
/**
* @brief Get the current source map pointer
*
* @return Current source map pointer
*/
inline std::map<GLenum, std::string> *source_map() const
{ return source_map_; }
/**
* @brief Set the source map pointer for the compiled sources
*
* The pointer must either be null or remain valid until the sources for this
* buffer have been compiled.
*
* @param new_map New source map pointer
*/
inline void source_map(std::map<GLenum, std::string> *new_map)
{ source_map_ = new_map; }
/**
* @brief Obtains the list of outputs for this buffer.
*
* @return List of discovered program outputs
*/
std::optional<std::vector<buffer_output>> get_buffer_outputs() const override;
/**
* @brief Get the program interface for this buffer
*
* @return Reference to the interface object for this buffer
*/
inline const program_interface &interface() const
{ return *program_interface_; }
};
}
}
#endif /* _SHADERTOY_BUFFERS_PROGRAM_BUFFER_HPP_ */
| 29.140704 | 109 | 0.70357 | [
"geometry",
"render",
"object",
"vector"
] |
375add4099a5b817d74f40a9467d8c6d9ae583ca | 3,073 | cxx | C++ | src/box_occupation_matrix.cxx | atollena/packrect | 173c65a83261f577cd507263e2bdd43179ea7915 | [
"MIT"
] | 2 | 2018-08-23T10:55:30.000Z | 2018-08-23T11:01:20.000Z | src/box_occupation_matrix.cxx | atollena/packrect | 173c65a83261f577cd507263e2bdd43179ea7915 | [
"MIT"
] | null | null | null | src/box_occupation_matrix.cxx | atollena/packrect | 173c65a83261f577cd507263e2bdd43179ea7915 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cassert>
#include "box_occupation_matrix.hxx"
#include "rectangle.hxx"
#include "rectangle_position.hxx"
#include "bounding_box.hxx"
namespace packing {
BoxOccupationMatrix::BoxOccupationMatrix(const RectangleSize & boxSize)
:width(boxSize.width),
height(boxSize.height),
matrix(boxSize.computeArea(), -1),
emptyStripsTracker(*this)
{}
void BoxOccupationMatrix::set(const Rectangle & rectangle,
const RectanglePosition & position)
{
int rectangleHeight = rectangle.getH();
int rectangleWidth = rectangle.getW();
if(position.isVertical()) {
std::swap(rectangleHeight, rectangleWidth);
}
set(position.getLeftBottom(),
rectangleWidth,
rectangleHeight,
rectangle.getId());
}
void BoxOccupationMatrix::unset(const Rectangle & rectangle,
const RectanglePosition & position)
{
int rectangleHeight = rectangle.getH();
int rectangleWidth = rectangle.getW();
if(position.isVertical()) {
std::swap(rectangleHeight, rectangleWidth);
}
set(position.getLeftBottom(),
rectangleWidth,
rectangleHeight,
-1);
}
void BoxOccupationMatrix::set(const Point & position,
int rectangleWidth,
int rectangleHeight,
RectangleId id)
{
assert(position.getX() + rectangleWidth <= this->width);
assert(position.getY() + rectangleHeight <= this->height);
for(int i = 0; i < rectangleHeight; ++i) {
std::fill_n(at(position.getX(), position.getY() + i),
rectangleWidth,
id);
}
emptyStripsTracker.recomputeEmptyStrips(position.getX(),
position.getY(),
rectangleWidth,
rectangleHeight);
}
std::vector<RectangleId>::iterator BoxOccupationMatrix::at(int x, int y)
{
return matrix.begin() + (y*width + x);
}
RectangleId BoxOccupationMatrix::at(int x, int y) const
{
return matrix[y*width + x];
}
std::deque<int>
BoxOccupationMatrix::minContiguousFreeCells() const
{
return emptyStripsTracker.minContiguousFreeCells();
}
namespace {
int maxDigit(std::vector<int> vec)
{
int maxDigits = *std::max_element(vec.begin(), vec.end());
int digits = 0;
if(maxDigits > 0) {
while (maxDigits != 0) {
maxDigits /= 10; digits++;
}
}
return digits;
}
}
std::ostream& operator<<(std::ostream& out, const BoxOccupationMatrix& box)
{
int maxDigits = maxDigit(box.matrix);
out << std::endl;
for(int y = box.height - 1; y >= 0; y--) {
for(int x = 0; x < box.width; x++) {
out.width(maxDigits + 1);
if(box.at(x, y) != -1)
out << box.at(x, y);
else
out << 'x';
}
out << std::endl;
}
return out;
}
}
| 26.721739 | 77 | 0.566222 | [
"vector"
] |
375fae2eb3e498d0060e77f42d49755f8fe7ebb8 | 3,401 | cc | C++ | src/apps_root/stripes2root.cc | JohannesEbke/drillbit | 770888380224ce8b513250beb3027d5e6d8a985c | [
"BSD-2-Clause"
] | 6 | 2015-11-19T10:04:28.000Z | 2017-04-22T23:52:06.000Z | src/apps_root/stripes2root.cc | JohannesEbke/drillbit | 770888380224ce8b513250beb3027d5e6d8a985c | [
"BSD-2-Clause"
] | 1 | 2015-11-23T23:45:02.000Z | 2015-11-23T23:45:02.000Z | src/apps_root/stripes2root.cc | JohannesEbke/drillbit | 770888380224ce8b513250beb3027d5e6d8a985c | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <vector>
#include <TTree.h>
#include <TBranch.h>
#include <TFile.h>
#include "open_stripes.h"
#include "root_dictionaries.h"
#include "stdvector_reader.h"
#include "stdvector_reader_impl.h"
using namespace std;
using google::protobuf::io::CodedInputStream;
// Create a branch of this type in the given ROOT Tree and hold on to it
TBranch* make_branch(StdVectorReader *reader, TTree *tree) {
const StripeInfo &info = reader->metadata_stream()->info();
ensure_dictionary(info.root_type().c_str());
uint32_t level = info.max_dl();
// Create Branch
if (level == 0) {
// can be Int_t, UInt_t, Double_t, Float_t, Bool_t
if (info.root_type() == "Int_t") {
return tree->Branch(info.root_name().c_str(), reader->buffer(), (info.root_name() + "/I").c_str());
} else if (info.root_type() == "UInt_t") {
return tree->Branch(info.root_name().c_str(), reader->buffer(), (info.root_name() + "/i").c_str());
} else if (info.root_type() == "Float_t") {
return tree->Branch(info.root_name().c_str(), reader->buffer(), (info.root_name() + "/F").c_str());
} else if (info.root_type() == "Double_t") {
return tree->Branch(info.root_name().c_str(), reader->buffer(), (info.root_name() + "/D").c_str());
} else if (info.root_type() == "Bool_t") {
return tree->Branch(info.root_name().c_str(), reader->buffer(), (info.root_name() + "/O").c_str());
} else {
std::cerr << "Unknown root_type: " << info.root_type() << std::endl;
assert(false);
}
} else {
return tree->Branch(info.root_name().c_str(), info.root_type().c_str(), reader->buffer_address());
}
}
void compose_root_file(std::string name, const std::vector<std::string>& dit_files) {
std::vector<StripeInputStreamPtr> streams = open_stripes_read(dit_files);
std::cerr << "Looking up column metadata and creating root tree..." << std::endl;
TFile f(name.c_str(), "RECREATE");
f.SetCompressionLevel(9);
TTree * tree = new TTree("composed", "Composed Tree");
std::vector<StdVectorReader*> readers;
for (int i = 0; i < streams.size(); i++) {
MetaReader * sreader = MetaReader::Make(streams[i]->meta);
StdVectorReader * vreader = StdVectorReader::Make(sreader, streams[i]->data);
assert(make_branch(vreader, tree));
readers.push_back(vreader);
}
std::cerr << "Run over all events and collate them..." << std::endl;
int event_number = 0;
bool running = true;
while(running) {
//std::cerr << "Event start..." << std::endl;
//std::cout << event_number << std::endl;
if (event_number % 1000 == 0) std::cerr << event_number << std::endl;
for (int i = 0; i < dit_files.size(); i++) {
if (not readers[i]->next()) {
running = false;
break;
}
}
if (running) {
tree->Fill();
event_number++;
}
}
tree->Write("composed", TObject::kOverwrite);
//f.Write();
f.Close();
}
int main(int argc, const char ** argv) {
std::vector<std::string> dit_files;
for(int i = 1; i < argc; i++) {
dit_files.push_back(argv[i]);
}
compose_root_file("composed.root", dit_files);
return 0;
}
| 35.8 | 111 | 0.583652 | [
"vector"
] |
37615b0ad1c59bd3688691f9f50498e2cf2214f4 | 6,773 | cpp | C++ | src/zoneserver/model/gameobject/Anchor.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | src/zoneserver/model/gameobject/Anchor.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | src/zoneserver/model/gameobject/Anchor.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | #include "ZoneServerPCH.h"
#include "Anchor.h"
#include "Entity.h"
#include "ability/Inventoryable.h"
#include "ability/impl/KnowableAbility.h"
#include "ability/impl/SkillCastableAbility.h"
#include "ability/impl/CastNotificationableImpl.h"
#include "status/StaticObjectStatus.h"
#include "skilleffect/StaticObjectEffectScriptApplier.h"
#include "../time/GlobalCooldownTimer.h"
#include "../time/CooldownTimer.h"
#include "../item/LootItemInventory.h"
#include "../bank/BankAccount.h"
#include "../../world/World.h"
#include "../../world/WorldMap.h"
#include "../../controller/EntityController.h"
#include "../../service/skill/helper/SOEffectHelper.h"
#include <gideon/cs/datatable/AnchorTable.h>
#include <gideon/3d/3d.h>
#include <sne/base/concurrent/TaskScheduler.h>
#include <sne/core/memory/MemoryPoolMixin.h>
namespace gideon { namespace zoneserver { namespace go {
Anchor::Anchor(std::unique_ptr<gc::EntityController> controller) :
StaticObject(std::move(controller)),
expireTime_(0)
{
coolTime_= std::make_unique<CoolDownTimer>(*this);
knowable_= std::make_unique<KnowableAbility>(*this);
castNotificationable_= std::make_unique<CastNotificationableImpl>(*this);
skillCastableAbility_= std::make_unique<SkillCastableAbility>(*this);
oneSecondTracker_.reset(1000);
}
Anchor::~Anchor()
{
}
bool Anchor::initialize(DataCode dataCode, ObjectId objectId,
const ObjectPosition& position, go::Entity* player)
{
std::lock_guard<LockType> lock(getLock());
if (! StaticObject::initialize(otAnchor, objectId)) {
return false;
}
anchorTemlate_ = ANCHOR_TABLE->getAnchorTemplate(dataCode);
if (!anchorTemlate_) {
return false;
}
anchorInfo_.objectId_ = objectId;
anchorInfo_.objectType_ = otAnchor;
anchorInfo_.anchorCode_ = dataCode;
anchorInfo_.position_ = position;
initStaticObjectStatusInfo(anchorTemlate_->getStaticObjectStatusInfo());
if (player) {
anchorInfo_.ownerInfo_.ownerId_ = player->getObjectId();
anchorInfo_.ownerInfo_.nickname_ = player->getNickname();
}
skillCastableAbility_->learn(anchorTemlate_->getSkillCode());
UnionEntityInfo& entityInfo = getUnionEntityInfo_i();
entityInfo.objectType_ = getObjectType();
MoreAnchorInfo& moreAnchorInfo = entityInfo.asAnchorInfo();
static_cast<BaseAnchorInfo&>(moreAnchorInfo) = anchorInfo_;
const GameTime now = GAME_TIMER->msec();
if (0 < anchorTemlate_->getLiveSec()) {
expireTime_ = now + static_cast<GameTime>(anchorTemlate_->getLiveSec() * 1000);
}
if (0 < anchorTemlate_->getActiveInterval()) {
nextActivateTime_ = now + anchorTemlate_->getActiveInterval();
}
return true;
}
void Anchor::finalize()
{
{
std::lock_guard<LockType> lock(getLock());
anchorInfo_.reset();
}
StaticObject::finalize();
}
std::unique_ptr<EffectScriptApplier> Anchor::createEffectScriptApplier()
{
return std::make_unique<StaticObjectEffectScriptApplier>(*this);
}
std::unique_ptr<EffectHelper> Anchor::createEffectHelper()
{
return std::make_unique<SoEffectHelper>(*this);
}
void Anchor::tick(GameTime diff)
{
getEffectScriptApplier().tick();
oneSecondTracker_.update(diff);
if (! oneSecondTracker_.isPassed()) {
return;
}
oneSecondTracker_.reset(1000);
handleExpiredTasks();
}
void Anchor::handleExpiredTasks()
{
const GameTime now = GAME_TIMER->msec();
if (getStaticObjectStatus().isMinHp() || expireTime_ < now) {
despawn();
return;
}
if (nextActivateTime_ < now) {
nextActivateTime_ += anchorTemlate_->getActiveInterval();
castTo(getGameObjectInfo(), anchorTemlate_->getSkillCode());
}
}
void Anchor::setCooldown(DataCode dataCode, GameTime coolTime,
uint32_t index, GameTime globalCoolDownTime)
{
assert(globalCoolTime_.get() != nullptr && "TODO: 왜 초기화하지 않았는가?");
globalCoolTime_->setNextGlobalCooldownTime(index, globalCoolDownTime);
coolTime_->startCooldown(dataCode, coolTime);
}
void Anchor::cancelCooldown(DataCode dataCode, uint32_t index)
{
globalCoolTime_->cancelCooldown(index);
coolTime_->cancelCooldown(dataCode);
}
void Anchor::cancelPreCooldown()
{
globalCoolTime_->cancelPreCooldown();
coolTime_->cancelPreCooldown();
}
bool Anchor::isGlobalCooldown(uint32_t index) const
{
const GameTime currentTime = GAME_TIMER->msec();
const msec_t nextGlobalCooldownTime =
globalCoolTime_->getNextGlobalCooldownTime(index);
if (nextGlobalCooldownTime == 0) {
return false;
}
return currentTime < nextGlobalCooldownTime;
}
bool Anchor::isLocalCooldown(DataCode dataCode) const
{
return coolTime_->isCooldown(dataCode);;
}
// = Positionable overriding
WorldPosition Anchor::getWorldPosition() const
{
std::lock_guard<LockType> lock(getLockPositionable());
const WorldMap* worldMap = getCurrentWorldMap();
if (! worldMap) {
return WorldPosition();
}
return WorldPosition(getPosition(), worldMap->getMapCode());
}
// = SkillCastable overriding
ErrorCode Anchor::castTo(const GameObjectInfo& targetInfo, SkillCode skillCode)
{
return skillCastableAbility_->castTo(targetInfo, skillCode);
}
ErrorCode Anchor::castAt(const Position& targetPosition, SkillCode skillCode)
{
return skillCastableAbility_->castAt(targetPosition, skillCode);
}
void Anchor::cancel(SkillCode skillCode)
{
skillCastableAbility_->cancel(skillCode);
}
void Anchor::cancelConcentrationSkill(SkillCode /*skillCode*/)
{
}
void Anchor::cancelAll()
{
skillCastableAbility_->cancelAll();
}
void Anchor::consumePoints(const Points& points)
{
if (points.hp_ > 0) {
getStaticObjectStatus().reduceHp(points.hp_);
}
}
void Anchor::consumeMaterialItem(const BaseItemInfo& /*itemInfo*/)
{
}
ErrorCode Anchor::checkSkillCasting(SkillCode skillCode,
const GameObjectInfo& targetInfo) const
{
return skillCastableAbility_->checkSkillCasting(skillCode, targetInfo);
}
ErrorCode Anchor::checkSkillCasting(SkillCode skillCode,
const Position& targetPosition) const
{
return skillCastableAbility_->checkSkillCasting(skillCode, targetPosition);
}
float32_t Anchor::getLongestSkillDistance() const
{
return skillCastableAbility_->getLongestSkillDistance();
}
bool Anchor::isUsing(SkillCode skillCode) const
{
return skillCastableAbility_->isUsing(skillCode);
}
bool Anchor::canCast(SkillCode skillCode) const
{
// TODO: Anchor
//if (! isActiveAbillity()) {
// return true;
//}
// 쿨타임 체크
return skillCastableAbility_->canCast(skillCode);
}
}}} // namespace gideon { namespace zoneserver { namespace go {
| 24.275986 | 87 | 0.718441 | [
"3d"
] |
3764681244294ca61731aa49179f61bd5db9e9b1 | 47,994 | cpp | C++ | Engine/Source/ThirdParty/IntelEmbree/Embree270/src/kernels/xeon/bvh4/bvh4.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/ThirdParty/IntelEmbree/Embree270/src/kernels/xeon/bvh4/bvh4.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/ThirdParty/IntelEmbree/Embree270/src/kernels/xeon/bvh4/bvh4.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "bvh4.h"
#include "bvh4_statistics.h"
#include "../geometry/bezier1v.h"
#include "../geometry/bezier1i.h"
#include "../geometry/triangle4.h"
#include "../geometry/triangle8.h"
#include "../geometry/triangle4v.h"
#include "../geometry/triangle4v_mb.h"
#include "../geometry/triangle4i.h"
#include "../geometry/subdivpatch1.h"
#include "../geometry/subdivpatch1cached.h"
#include "../geometry/object.h"
#include "../../common/accelinstance.h"
namespace embree
{
DECLARE_SYMBOL(Accel::Intersector1,BVH4Bezier1vIntersector1);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Bezier1iIntersector1);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Bezier1vIntersector1_OBB);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Bezier1iIntersector1_OBB);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Bezier1iMBIntersector1_OBB);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Triangle4Intersector1Moeller);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Triangle8Intersector1Moeller);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Triangle4vIntersector1Pluecker);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Triangle4iIntersector1Pluecker);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Triangle4vMBIntersector1Moeller);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Subdivpatch1Intersector1);
DECLARE_SYMBOL(Accel::Intersector1,BVH4Subdivpatch1CachedIntersector1);
DECLARE_SYMBOL(Accel::Intersector1,BVH4GridAOSIntersector1);
DECLARE_SYMBOL(Accel::Intersector1,BVH4VirtualIntersector1);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Bezier1vIntersector4Chunk);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Bezier1iIntersector4Chunk);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Bezier1vIntersector4Single_OBB);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Bezier1iIntersector4Single_OBB);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Bezier1iMBIntersector4Single_OBB);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4Intersector4ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4Intersector4ChunkMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle8Intersector4ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle8Intersector4ChunkMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoeller);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoeller);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4vIntersector4ChunkPluecker);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4vIntersector4HybridPluecker);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4iIntersector4ChunkPluecker);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Triangle4vMBIntersector4ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Subdivpatch1Intersector4);
DECLARE_SYMBOL(Accel::Intersector4,BVH4Subdivpatch1CachedIntersector4);
DECLARE_SYMBOL(Accel::Intersector4,BVH4GridAOSIntersector4);
DECLARE_SYMBOL(Accel::Intersector4,BVH4VirtualIntersector4Chunk);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Bezier1vIntersector8Chunk);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Bezier1iIntersector8Chunk);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Bezier1vIntersector8Single_OBB);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Bezier1iIntersector8Single_OBB);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Bezier1iMBIntersector8Single_OBB);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4Intersector8ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4Intersector8ChunkMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle8Intersector8ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle8Intersector8ChunkMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoeller);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoeller);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4vIntersector8ChunkPluecker);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4vIntersector8HybridPluecker);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4iIntersector8ChunkPluecker);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Triangle4vMBIntersector8ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Subdivpatch1Intersector8);
DECLARE_SYMBOL(Accel::Intersector8,BVH4Subdivpatch1CachedIntersector8);
DECLARE_SYMBOL(Accel::Intersector8,BVH4GridAOSIntersector8);
DECLARE_SYMBOL(Accel::Intersector8,BVH4VirtualIntersector8Chunk);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Bezier1vIntersector16Chunk);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Bezier1iIntersector16Chunk);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Bezier1vIntersector16Single_OBB);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Bezier1iIntersector16Single_OBB);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Bezier1iMBIntersector16Single_OBB);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4Intersector16ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4Intersector16ChunkMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle8Intersector16ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle8Intersector16ChunkMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoeller);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoeller);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoellerNoFilter);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4vIntersector16ChunkPluecker);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4vIntersector16HybridPluecker);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4iIntersector16ChunkPluecker);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Triangle4vMBIntersector16ChunkMoeller);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Subdivpatch1Intersector16);
DECLARE_SYMBOL(Accel::Intersector16,BVH4Subdivpatch1CachedIntersector16);
DECLARE_SYMBOL(Accel::Intersector16,BVH4GridAOSIntersector16);
DECLARE_SYMBOL(Accel::Intersector16,BVH4VirtualIntersector16Chunk);
DECLARE_BUILDER(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderTwoLevelSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Bezier1vBuilder_OBB_New);
DECLARE_BUILDER(void,Scene,size_t,BVH4Bezier1iBuilder_OBB_New);
DECLARE_BUILDER(void,Scene,size_t,BVH4Bezier1iMBBuilder_OBB_New);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4SceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle8SceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4vSceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4iSceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4vMBSceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4SceneBuilderSpatialSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle8SceneBuilderSpatialSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4vSceneBuilderSpatialSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4iSceneBuilderSpatialSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Bezier1vSceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Bezier1iSceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4VirtualSceneBuilderSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4SubdivPatch1BuilderBinnedSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4SubdivPatch1CachedBuilderBinnedSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4SubdivGridEagerBuilderBinnedSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4MeshRefitSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle8MeshRefitSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4vMeshRefitSAH);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4iMeshRefitSAH);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4SceneBuilderMortonGeneral);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle8SceneBuilderMortonGeneral);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4vSceneBuilderMortonGeneral);
DECLARE_BUILDER(void,Scene,size_t,BVH4Triangle4iSceneBuilderMortonGeneral);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderMortonGeneral);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderMortonGeneral);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderMortonGeneral);
DECLARE_BUILDER(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderMortonGeneral);
void BVH4Register ()
{
int features = getCPUFeatures();
/* select builders */
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vBuilder_OBB_New);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iBuilder_OBB_New);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iMBBuilder_OBB_New);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSAH);
SELECT_SYMBOL_AVX (features,BVH4Triangle8SceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMBSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSpatialSAH);
SELECT_SYMBOL_AVX (features,BVH4Triangle8SceneBuilderSpatialSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSpatialSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSpatialSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderSAH);
SELECT_SYMBOL_AVX (features,BVH4Triangle8MeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4SubdivPatch1BuilderBinnedSAH);
SELECT_SYMBOL_DEFAULT_AVX_AVX512(features,BVH4SubdivPatch1CachedBuilderBinnedSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4SubdivGridEagerBuilderBinnedSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshRefitSAH);
SELECT_SYMBOL_AVX (features,BVH4Triangle8MeshRefitSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshRefitSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshRefitSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderMortonGeneral);
SELECT_SYMBOL_AVX (features,BVH4Triangle8SceneBuilderMortonGeneral);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderMortonGeneral);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderMortonGeneral);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderMortonGeneral);
SELECT_SYMBOL_AVX (features,BVH4Triangle8MeshBuilderMortonGeneral);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderMortonGeneral);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderMortonGeneral);
/* select intersectors1 */
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iMBIntersector1_OBB);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4Triangle4Intersector1Moeller);
SELECT_SYMBOL_AVX_AVX2 (features,BVH4Triangle8Intersector1Moeller);
SELECT_SYMBOL_DEFAULT_SSE41_AVX (features,BVH4Triangle4vIntersector1Pluecker);
SELECT_SYMBOL_DEFAULT_SSE41_AVX (features,BVH4Triangle4iIntersector1Pluecker);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4Triangle4vMBIntersector1Moeller);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4Subdivpatch1Intersector1);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector1);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4GridAOSIntersector1);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4VirtualIntersector1);
#if defined (RTCORE_RAY_PACKETS)
/* select intersectors4 */
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector4Chunk);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector4Chunk);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector4Single_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector4Single_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iMBIntersector4Single_OBB);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4Triangle4Intersector4ChunkMoeller);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4Triangle4Intersector4ChunkMoellerNoFilter);
SELECT_SYMBOL_AVX_AVX2 (features,BVH4Triangle8Intersector4ChunkMoeller);
SELECT_SYMBOL_DEFAULT2 (features,BVH4Triangle4Intersector4HybridMoeller,BVH4Triangle4Intersector4ChunkMoeller); // hybrid not supported below SSE4.2
SELECT_SYMBOL_AVX_AVX2 (features,BVH4Triangle8Intersector4ChunkMoellerNoFilter);
SELECT_SYMBOL_DEFAULT2 (features,BVH4Triangle4Intersector4HybridMoellerNoFilter,BVH4Triangle4Intersector4ChunkMoellerNoFilter); // hybrid not supported below SSE4.2
SELECT_SYMBOL_SSE42_AVX_AVX2 (features,BVH4Triangle4Intersector4HybridMoeller);
SELECT_SYMBOL_SSE42_AVX_AVX2 (features,BVH4Triangle4Intersector4HybridMoellerNoFilter);
SELECT_SYMBOL_AVX_AVX2 (features,BVH4Triangle8Intersector4HybridMoeller);
SELECT_SYMBOL_AVX_AVX2 (features,BVH4Triangle8Intersector4HybridMoellerNoFilter);
SELECT_SYMBOL_DEFAULT_SSE41_AVX (features,BVH4Triangle4vIntersector4ChunkPluecker);
SELECT_SYMBOL_DEFAULT2 (features,BVH4Triangle4vIntersector4HybridPluecker,BVH4Triangle4vIntersector4ChunkPluecker); // hybrid not supported below SSE4.2
SELECT_SYMBOL_SSE42_AVX (features,BVH4Triangle4vIntersector4HybridPluecker);
SELECT_SYMBOL_DEFAULT_SSE41_AVX (features,BVH4Triangle4iIntersector4ChunkPluecker);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4Triangle4vMBIntersector4ChunkMoeller);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Subdivpatch1Intersector4);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Subdivpatch1CachedIntersector4);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4GridAOSIntersector4);
SELECT_SYMBOL_DEFAULT_SSE41_AVX_AVX2(features,BVH4VirtualIntersector4Chunk);
/* select intersectors8 */
SELECT_SYMBOL_AVX_AVX2(features,BVH4Bezier1vIntersector8Chunk);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Bezier1iIntersector8Chunk);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Bezier1vIntersector8Single_OBB);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Bezier1iIntersector8Single_OBB);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Bezier1iMBIntersector8Single_OBB);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle4Intersector8ChunkMoeller);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle4Intersector8ChunkMoellerNoFilter);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle8Intersector8ChunkMoeller);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle8Intersector8ChunkMoellerNoFilter);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoeller);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoellerNoFilter);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoeller);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoellerNoFilter);
SELECT_SYMBOL_AVX (features,BVH4Triangle4vIntersector8ChunkPluecker);
SELECT_SYMBOL_AVX (features,BVH4Triangle4vIntersector8HybridPluecker);
SELECT_SYMBOL_AVX (features,BVH4Triangle4iIntersector8ChunkPluecker);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Triangle4vMBIntersector8ChunkMoeller);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Subdivpatch1Intersector8);
SELECT_SYMBOL_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector8);
SELECT_SYMBOL_AVX_AVX2(features,BVH4GridAOSIntersector8);
SELECT_SYMBOL_AVX_AVX2(features,BVH4VirtualIntersector8Chunk);
/* select intersectors16 */
SELECT_SYMBOL_AVX512(features,BVH4Bezier1vIntersector16Chunk);
SELECT_SYMBOL_AVX512(features,BVH4Bezier1iIntersector16Chunk);
SELECT_SYMBOL_AVX512(features,BVH4Bezier1vIntersector16Single_OBB);
SELECT_SYMBOL_AVX512(features,BVH4Bezier1iIntersector16Single_OBB);
SELECT_SYMBOL_AVX512(features,BVH4Bezier1iMBIntersector16Single_OBB);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4Intersector16ChunkMoeller);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4Intersector16ChunkMoellerNoFilter);
SELECT_SYMBOL_AVX512(features,BVH4Triangle8Intersector16ChunkMoeller);
SELECT_SYMBOL_AVX512(features,BVH4Triangle8Intersector16ChunkMoellerNoFilter);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4Intersector16HybridMoeller);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4Intersector16HybridMoellerNoFilter);
SELECT_SYMBOL_AVX512(features,BVH4Triangle8Intersector16HybridMoeller);
SELECT_SYMBOL_AVX512(features,BVH4Triangle8Intersector16HybridMoellerNoFilter);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4vIntersector16ChunkPluecker);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4vIntersector16HybridPluecker);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4iIntersector16ChunkPluecker);
SELECT_SYMBOL_AVX512(features,BVH4Triangle4vMBIntersector16ChunkMoeller);
SELECT_SYMBOL_AVX512(features,BVH4Subdivpatch1Intersector16);
SELECT_SYMBOL_AVX512(features,BVH4Subdivpatch1CachedIntersector16);
SELECT_SYMBOL_AVX512(features,BVH4GridAOSIntersector16);
SELECT_SYMBOL_AVX512(features,BVH4VirtualIntersector16Chunk);
#endif
}
BVH4::BVH4 (const PrimitiveType& primTy, Scene* scene, bool listMode)
: AccelData(AccelData::TY_BVH4), primTy(primTy), device(scene->device), scene(scene), listMode(listMode),
root(emptyNode), alloc(scene->device), numPrimitives(0), numVertices(0), data_mem(nullptr), size_data_mem(0) {}
BVH4::~BVH4 ()
{
for (size_t i=0; i<objects.size(); i++)
delete objects[i];
if (data_mem) {
os_free( data_mem, size_data_mem );
data_mem = nullptr;
size_data_mem = 0;
}
}
void BVH4::clear()
{
set(BVH4::emptyNode,empty,0);
alloc.clear();
}
void BVH4::set (NodeRef root, const BBox3fa& bounds, size_t numPrimitives)
{
this->root = root;
this->bounds = bounds;
this->numPrimitives = numPrimitives;
}
void BVH4::printStatistics()
{
std::cout << BVH4Statistics(this).str();
}
void BVH4::clearBarrier(NodeRef& node)
{
if (node.isBarrier())
node.clearBarrier();
else if (!node.isLeaf()) {
Node* n = node.node();
for (size_t c=0; c<N; c++)
clearBarrier(n->child(c));
}
}
void BVH4::layoutLargeNodes(size_t N)
{
struct NodeArea
{
__forceinline NodeArea() {}
__forceinline NodeArea(NodeRef& node, const BBox3fa& bounds)
: node(&node), A(node.isLeaf() ? float(neg_inf) : area(bounds)) {}
__forceinline bool operator< (const NodeArea& other) const {
return this->A < other.A;
}
NodeRef* node;
float A;
};
std::vector<NodeArea> lst;
lst.reserve(N);
lst.push_back(NodeArea(root,empty));
while (lst.size() < N)
{
std::pop_heap(lst.begin(), lst.end());
NodeArea n = lst.back(); lst.pop_back();
if (!n.node->isNode()) break;
Node* node = n.node->node();
for (size_t i=0; i<BVH4::N; i++) {
if (node->child(i) == BVH4::emptyNode) continue;
lst.push_back(NodeArea(node->child(i),node->bounds(i)));
std::push_heap(lst.begin(), lst.end());
}
}
for (size_t i=0; i<lst.size(); i++)
lst[i].node->setBarrier();
root = layoutLargeNodesRecursion(root);
}
BVH4::NodeRef BVH4::layoutLargeNodesRecursion(NodeRef& node)
{
if (node.isBarrier()) {
node.clearBarrier();
return node;
}
else if (node.isNode())
{
Node* oldnode = node.node();
Node* newnode = (BVH4::Node*) alloc.threadLocal2()->alloc0.malloc(sizeof(BVH4::Node)); // FIXME: optimize access to threadLocal2
*newnode = *oldnode;
for (size_t c=0; c<BVH4::N; c++)
newnode->child(c) = layoutLargeNodesRecursion(oldnode->child(c));
return encodeNode(newnode);
}
else return node;
}
double BVH4::preBuild(const char* builderName)
{
if (builderName == nullptr)
return inf;
if (device->verbosity(1))
std::cout << "building BVH4<" << primTy.name << "> using " << builderName << " ..." << std::flush;
double t0 = 0.0;
if (device->benchmark || device->verbosity(1)) t0 = getSeconds();
return t0;
}
void BVH4::postBuild(double t0)
{
if (t0 == double(inf))
return;
double dt = 0.0;
if (device->benchmark || device->verbosity(1))
dt = getSeconds()-t0;
/* print statistics */
if (device->verbosity(1)) {
std::cout << " [DONE]" << " " << 1000.0f*dt << "ms (" << 1E-6*double(numPrimitives)/dt << " Mprim/s)" << std::endl;
}
if (device->verbosity(2))
printStatistics();
if (device->verbosity(2))
alloc.print_statistics();
/* benchmark mode */
if (device->benchmark) {
BVH4Statistics stat(this);
std::cout << "BENCHMARK_BUILD " << dt << " " << double(numPrimitives)/dt << " " << stat.sah() << " " << stat.bytesUsed() << std::endl;
}
}
Accel::Intersectors BVH4Bezier1vIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1vIntersector1;
intersectors.intersector4 = BVH4Bezier1vIntersector4Chunk;
intersectors.intersector8 = BVH4Bezier1vIntersector8Chunk;
intersectors.intersector16 = BVH4Bezier1vIntersector16Chunk;
return intersectors;
}
Accel::Intersectors BVH4Bezier1iIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1iIntersector1;
intersectors.intersector4 = BVH4Bezier1iIntersector4Chunk;
intersectors.intersector8 = BVH4Bezier1iIntersector8Chunk;
intersectors.intersector16 = BVH4Bezier1iIntersector16Chunk;
return intersectors;
}
Accel::Intersectors BVH4Bezier1vIntersectors_OBB(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1vIntersector1_OBB;
intersectors.intersector4 = BVH4Bezier1vIntersector4Single_OBB;
intersectors.intersector8 = BVH4Bezier1vIntersector8Single_OBB;
intersectors.intersector16 = BVH4Bezier1vIntersector16Single_OBB;
return intersectors;
}
Accel::Intersectors BVH4Bezier1iIntersectors_OBB(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1iIntersector1_OBB;
intersectors.intersector4 = BVH4Bezier1iIntersector4Single_OBB;
intersectors.intersector8 = BVH4Bezier1iIntersector8Single_OBB;
intersectors.intersector16 = BVH4Bezier1iIntersector16Single_OBB;
return intersectors;
}
Accel::Intersectors BVH4Bezier1iMBIntersectors_OBB(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1iMBIntersector1_OBB;
intersectors.intersector4 = BVH4Bezier1iMBIntersector4Single_OBB;
intersectors.intersector8 = BVH4Bezier1iMBIntersector8Single_OBB;
intersectors.intersector16 = BVH4Bezier1iMBIntersector16Single_OBB;
return intersectors;
}
Accel::Intersectors BVH4Triangle4IntersectorsChunk(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4Intersector1Moeller;
intersectors.intersector4_filter = BVH4Triangle4Intersector4ChunkMoeller;
intersectors.intersector4_nofilter = BVH4Triangle4Intersector4ChunkMoellerNoFilter;
intersectors.intersector8_filter = BVH4Triangle4Intersector8ChunkMoeller;
intersectors.intersector8_nofilter = BVH4Triangle4Intersector8ChunkMoellerNoFilter;
intersectors.intersector16_filter = BVH4Triangle4Intersector16ChunkMoeller;
intersectors.intersector16_nofilter = BVH4Triangle4Intersector16ChunkMoellerNoFilter;
return intersectors;
}
Accel::Intersectors BVH4Triangle4IntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4Intersector1Moeller;
intersectors.intersector4_filter = BVH4Triangle4Intersector4HybridMoeller;
intersectors.intersector4_nofilter = BVH4Triangle4Intersector4HybridMoellerNoFilter;
intersectors.intersector8_filter = BVH4Triangle4Intersector8HybridMoeller;
intersectors.intersector8_nofilter = BVH4Triangle4Intersector8HybridMoellerNoFilter;
intersectors.intersector16_filter = BVH4Triangle4Intersector16HybridMoeller;
intersectors.intersector16_nofilter = BVH4Triangle4Intersector16HybridMoellerNoFilter;
return intersectors;
}
Accel::Intersectors BVH4Triangle8IntersectorsChunk(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle8Intersector1Moeller;
intersectors.intersector4_filter = BVH4Triangle8Intersector4ChunkMoeller;
intersectors.intersector4_nofilter = BVH4Triangle8Intersector4ChunkMoellerNoFilter;
intersectors.intersector8 = BVH4Triangle8Intersector8ChunkMoeller;
intersectors.intersector8_filter = BVH4Triangle8Intersector8ChunkMoeller;
intersectors.intersector8_nofilter = BVH4Triangle8Intersector8ChunkMoellerNoFilter;
intersectors.intersector16_filter = BVH4Triangle8Intersector16ChunkMoeller;
intersectors.intersector16_nofilter = BVH4Triangle8Intersector16ChunkMoellerNoFilter;
return intersectors;
}
Accel::Intersectors BVH4Triangle8IntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle8Intersector1Moeller;
intersectors.intersector4_filter = BVH4Triangle8Intersector4HybridMoeller;
intersectors.intersector4_nofilter = BVH4Triangle8Intersector4HybridMoellerNoFilter;
intersectors.intersector8_filter = BVH4Triangle8Intersector8HybridMoeller;
intersectors.intersector8_nofilter = BVH4Triangle8Intersector8HybridMoellerNoFilter;
intersectors.intersector16_filter = BVH4Triangle8Intersector16HybridMoeller;
intersectors.intersector16_nofilter = BVH4Triangle8Intersector16HybridMoellerNoFilter;
return intersectors;
}
Accel::Intersectors BVH4Triangle4vMBIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4vMBIntersector1Moeller;
intersectors.intersector4 = BVH4Triangle4vMBIntersector4ChunkMoeller;
intersectors.intersector8 = BVH4Triangle4vMBIntersector8ChunkMoeller;
intersectors.intersector16 = BVH4Triangle4vMBIntersector16ChunkMoeller;
return intersectors;
}
Accel::Intersectors BVH4Triangle4vIntersectorsChunk(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4vIntersector1Pluecker;
intersectors.intersector4 = BVH4Triangle4vIntersector4ChunkPluecker;
intersectors.intersector8 = BVH4Triangle4vIntersector8ChunkPluecker;
intersectors.intersector16 = BVH4Triangle4vIntersector16ChunkPluecker;
return intersectors;
}
Accel::Intersectors BVH4Triangle4vIntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4vIntersector1Pluecker;
intersectors.intersector4 = BVH4Triangle4vIntersector4HybridPluecker;
intersectors.intersector8 = BVH4Triangle4vIntersector8HybridPluecker;
intersectors.intersector16 = BVH4Triangle4vIntersector16HybridPluecker;
return intersectors;
}
Accel::Intersectors BVH4Triangle4iIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4iIntersector1Pluecker;
intersectors.intersector4 = BVH4Triangle4iIntersector4ChunkPluecker;
intersectors.intersector8 = BVH4Triangle4iIntersector8ChunkPluecker;
intersectors.intersector16 = BVH4Triangle4iIntersector16ChunkPluecker;
return intersectors;
}
Accel* BVH4::BVH4Bezier1v(Scene* scene)
{
BVH4* accel = new BVH4(Bezier1v::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Bezier1vIntersectors(accel);
Builder* builder = BVH4Bezier1vSceneBuilderSAH(accel,scene,LeafMode);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Bezier1i(Scene* scene)
{
BVH4* accel = new BVH4(Bezier1i::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Bezier1iIntersectors(accel);
Builder* builder = BVH4Bezier1iSceneBuilderSAH(accel,scene,LeafMode);
scene->needBezierVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4OBBBezier1v(Scene* scene, bool highQuality)
{
BVH4* accel = new BVH4(Bezier1v::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Bezier1vIntersectors_OBB(accel);
Builder* builder = BVH4Bezier1vBuilder_OBB_New(accel,scene,MODE_HIGH_QUALITY); // FIXME: enable high quality mode
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4OBBBezier1i(Scene* scene, bool highQuality)
{
BVH4* accel = new BVH4(Bezier1i::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Bezier1iIntersectors_OBB(accel);
Builder* builder = BVH4Bezier1iBuilder_OBB_New(accel,scene,MODE_HIGH_QUALITY); // FIXME: enable high quality mode
scene->needBezierVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4OBBBezier1iMB(Scene* scene, bool highQuality)
{
BVH4* accel = new BVH4(Bezier1i::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Bezier1iMBIntersectors_OBB(accel);
Builder* builder = BVH4Bezier1iMBBuilder_OBB_New(accel,scene,MODE_HIGH_QUALITY); // FIXME: support high quality mode
scene->needBezierVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene,LeafMode);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4IntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "chunk" ) intersectors = BVH4Triangle4IntersectorsChunk(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4IntersectorsHybrid(accel);
else THROW_RUNTIME_ERROR("unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>");
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "morton" ) builder = BVH4Triangle4SceneBuilderMortonGeneral(accel,scene,0);
else THROW_RUNTIME_ERROR("unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4>");
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4::BVH4Triangle8(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene,LeafMode);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle8IntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "chunk" ) intersectors = BVH4Triangle8IntersectorsChunk(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle8IntersectorsHybrid(accel);
else THROW_RUNTIME_ERROR("unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle8>");
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle8SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "morton" ) builder = BVH4Triangle8SceneBuilderMortonGeneral(accel,scene,0);
else THROW_RUNTIME_ERROR("unknown builder "+scene->device->tri_builder+" for BVH4<Triangle8>");
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4::BVH4Triangle4vMB(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4vMB::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4vMBIntersectors(accel);
Builder* builder = nullptr;
if (scene->device->tri_builder_mb == "default" ) builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder_mb == "sah") builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0);
else THROW_RUNTIME_ERROR("unknown builder "+scene->device->tri_builder_mb+" for BVH4<Triangle4vMB>");
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4v(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4v::type,scene,LeafMode);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "chunk" ) intersectors = BVH4Triangle4vIntersectorsChunk(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
else THROW_RUNTIME_ERROR("unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>");
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4vSceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "morton" ) builder = BVH4Triangle4vSceneBuilderMortonGeneral(accel,scene,0);
else THROW_RUNTIME_ERROR("unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4v>");
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4i(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4i::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4iIntersectors(accel);
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4iSceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "morton" ) builder = BVH4Triangle4iSceneBuilderMortonGeneral(accel,scene,0);
else THROW_RUNTIME_ERROR("unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4i>");
scene->needTriangleVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
void createTriangleMeshTriangle4(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
if (mesh->numTimeSteps != 1) THROW_RUNTIME_ERROR("internal error");
accel = new BVH4(Triangle4::type,mesh->parent,LeafMode);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = BVH4Triangle4MeshBuilderSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DEFORMABLE: builder = BVH4Triangle4MeshRefitSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DYNAMIC: builder = BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,LeafMode); break;
default: THROW_RUNTIME_ERROR("internal error");
}
}
#if defined (__TARGET_AVX__)
void createTriangleMeshTriangle8(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
if (mesh->numTimeSteps != 1) THROW_RUNTIME_ERROR("internal error");
accel = new BVH4(Triangle8::type,mesh->parent,LeafMode);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = BVH4Triangle8MeshBuilderSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DEFORMABLE: builder = BVH4Triangle8MeshRefitSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DYNAMIC: builder = BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,LeafMode); break;
default: THROW_RUNTIME_ERROR("internal error");
}
}
#endif
void createTriangleMeshTriangle4v(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
if (mesh->numTimeSteps != 1) THROW_RUNTIME_ERROR("internal error");
accel = new BVH4(Triangle4v::type,mesh->parent,LeafMode);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = BVH4Triangle4vMeshBuilderSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DEFORMABLE: builder = BVH4Triangle4vMeshRefitSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DYNAMIC: builder = BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,LeafMode); break;
default: THROW_RUNTIME_ERROR("internal error");
}
}
void createTriangleMeshTriangle4i(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
if (mesh->numTimeSteps != 1) THROW_RUNTIME_ERROR("internal error");
accel = new BVH4(Triangle4i::type,mesh->parent,LeafMode);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = BVH4Triangle4iMeshBuilderSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DEFORMABLE: builder = BVH4Triangle4iMeshRefitSAH(accel,mesh,LeafMode); break;
case RTC_GEOMETRY_DYNAMIC: builder = BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,LeafMode); break;
default: THROW_RUNTIME_ERROR("internal error");
}
}
Accel* BVH4::BVH4BVH4Triangle4ObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
Builder* builder = BVH4BuilderTwoLevelSAH(accel,scene,&createTriangleMeshTriangle4);
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4::BVH4BVH4Triangle8ObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel);
Builder* builder = BVH4BuilderTwoLevelSAH(accel,scene,&createTriangleMeshTriangle8);
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4::BVH4BVH4Triangle4vObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4v::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
Builder* builder = BVH4BuilderTwoLevelSAH(accel,scene,&createTriangleMeshTriangle4v);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4BVH4Triangle4iObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4i::type,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4iIntersectors(accel);
Builder* builder = BVH4BuilderTwoLevelSAH(accel,scene,&createTriangleMeshTriangle4i);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4SpatialSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene,LeafMode);
Builder* builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4::BVH4Triangle8SpatialSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene,LeafMode);
Builder* builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4::BVH4Triangle4ObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene,LeafMode);
Builder* builder = BVH4Triangle4SceneBuilderSAH(accel,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4::BVH4Triangle8ObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene,LeafMode);
Builder* builder = BVH4Triangle8SceneBuilderSAH(accel,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4::BVH4Triangle4vObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4v::type,scene,LeafMode);
Builder* builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4iObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4i::type,scene,LeafMode);
Builder* builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4iIntersectors(accel);
scene->needTriangleVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4SubdivPatch1(Scene* scene)
{
BVH4* accel = new BVH4(SubdivPatch1::type,scene,LeafMode);
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4Subdivpatch1Intersector1;
intersectors.intersector4 = BVH4Subdivpatch1Intersector4;
intersectors.intersector8 = BVH4Subdivpatch1Intersector8;
intersectors.intersector16 = BVH4Subdivpatch1Intersector16;
Builder* builder = BVH4SubdivPatch1BuilderBinnedSAH(accel,scene,LeafMode);
scene->needSubdivIndices = true;
scene->needSubdivVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4SubdivPatch1Cached(Scene* scene)
{
BVH4* accel = new BVH4(SubdivPatch1Cached::type,scene,LeafMode);
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4Subdivpatch1CachedIntersector1;
intersectors.intersector4 = BVH4Subdivpatch1CachedIntersector4;
intersectors.intersector8 = BVH4Subdivpatch1CachedIntersector8;
intersectors.intersector16 = BVH4Subdivpatch1CachedIntersector16;
Builder* builder = BVH4SubdivPatch1CachedBuilderBinnedSAH(accel,scene,LeafMode);
scene->needSubdivIndices = false;
scene->needSubdivVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4SubdivGridEager(Scene* scene)
{
BVH4* accel = new BVH4(PrimitiveType2::type,scene,LeafMode); // FIXME: type
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4GridAOSIntersector1;
//intersectors.intersector1 = BVH4Subdivpatch1CachedIntersector1;
intersectors.intersector4 = BVH4GridAOSIntersector4;
intersectors.intersector8 = BVH4GridAOSIntersector8;
intersectors.intersector16 = BVH4GridAOSIntersector16;
Builder* builder = BVH4SubdivGridEagerBuilderBinnedSAH(accel,scene,LeafMode);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4UserGeometry(Scene* scene)
{
BVH4* accel = new BVH4(Object::type,scene,LeafMode);
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4VirtualIntersector1;
intersectors.intersector4 = BVH4VirtualIntersector4Chunk;
intersectors.intersector8 = BVH4VirtualIntersector8Chunk;
intersectors.intersector16 = BVH4VirtualIntersector16Chunk;
Builder* builder = BVH4VirtualSceneBuilderSAH(accel,scene,LeafMode);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4ObjectSplit(TriangleMesh* mesh)
{
BVH4* accel = new BVH4(Triangle4::type,mesh->parent,LeafMode);
Builder* builder = BVH4Triangle4MeshBuilderSAH(accel,mesh,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4vObjectSplit(TriangleMesh* mesh)
{
BVH4* accel = new BVH4(Triangle4v::type,mesh->parent,LeafMode);
Builder* builder = BVH4Triangle4vMeshBuilderSAH(accel,mesh,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4::BVH4Triangle4Refit(TriangleMesh* mesh)
{
BVH4* accel = new BVH4(Triangle4::type,mesh->parent,LeafMode);
Builder* builder = BVH4Triangle4MeshRefitSAH(accel,mesh,LeafMode);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
}
| 50.255497 | 181 | 0.77691 | [
"mesh",
"geometry",
"object",
"vector"
] |
376a7d6db136dc83f0ca2bf599cca693bddbfbba | 485 | cc | C++ | ztm-algos-n-ds/section9/my-stack-implementation/using-dynamic-array/stack.cc | MatteoDelliRocioli/back-to-the-roots | 6c0fc1f0ab17937d6cdcc1a7f5f875d767b2b758 | [
"MIT"
] | null | null | null | ztm-algos-n-ds/section9/my-stack-implementation/using-dynamic-array/stack.cc | MatteoDelliRocioli/back-to-the-roots | 6c0fc1f0ab17937d6cdcc1a7f5f875d767b2b758 | [
"MIT"
] | null | null | null | ztm-algos-n-ds/section9/my-stack-implementation/using-dynamic-array/stack.cc | MatteoDelliRocioli/back-to-the-roots | 6c0fc1f0ab17937d6cdcc1a7f5f875d767b2b758 | [
"MIT"
] | null | null | null | #include "stack.h"
#include <vector>
#include <iostream>
using namespace std;
Stack::Stack () : data (vector<int> {}) {
cout << "Stack created" << endl;
}
int Stack::Pick() {
if (data.empty())
return 0;
return data.at(data.size() - 1);
}
void Stack::Push(int value) {
data.push_back(value);
}
int Stack::Pop() {
if (data.empty())
return 0;
int lastInserted = data.at(data.size() - 1);
data.pop_back();
return lastInserted;
} | 16.166667 | 47 | 0.57732 | [
"vector"
] |
376a7f1ee51b3f47776d91cc2b4a02a862053094 | 5,359 | cpp | C++ | src/prod/test/FabricTest/ReadWriteStatusValidator.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/test/FabricTest/ReadWriteStatusValidator.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/test/FabricTest/ReadWriteStatusValidator.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// 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 FabricTest;
using namespace std;
ReadWriteStatusValidator::ReadWriteStatusValidator(Common::ComPointer<IFabricStatefulServicePartition> const& partition)
: partition_(partition)
{
}
void ReadWriteStatusValidator::OnOpen()
{
ValidateStatusIsNotPrimaryOrTryAgain(L"Open");
}
void ReadWriteStatusValidator::OnClose()
{
ValidateStatusIsNotPrimary(L"Close");
}
void ReadWriteStatusValidator::OnAbort()
{
ValidateStatusIsNotPrimary(L"Abort");
}
void ReadWriteStatusValidator::OnChangeRole(FABRIC_REPLICA_ROLE newRole)
{
if (newRole == FABRIC_REPLICA_ROLE_PRIMARY)
{
ValidateStatusIsTryAgain(L"ChangeRolePrimary");
}
else if (newRole == FABRIC_REPLICA_ROLE_ACTIVE_SECONDARY)
{
ValidateStatusIsNotPrimaryOrTryAgain(L"ChangeRoleSecondary");
}
else
{
ValidateStatusIsNotPrimary(L"ChnageRoleOther");
}
}
void ReadWriteStatusValidator::OnOnDataLoss()
{
ValidateStatusIsTryAgain(L"OnDataLoss");
}
void ReadWriteStatusValidator::ValidateStatusIsNotPrimary(
std::wstring const & tag)
{
ValidateStatusIs(tag, FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY);
}
void ReadWriteStatusValidator::ValidateStatusIsTryAgain(
std::wstring const & tag)
{
ValidateStatusIs(tag, FABRIC_SERVICE_PARTITION_ACCESS_STATUS_RECONFIGURATION_PENDING);
}
void ReadWriteStatusValidator::ValidateStatusIsNotPrimaryOrTryAgain(
std::wstring const & tag)
{
ValidateStatusIs(tag, FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY, FABRIC_SERVICE_PARTITION_ACCESS_STATUS_RECONFIGURATION_PENDING);
}
void ReadWriteStatusValidator::ValidateStatusIs(
std::wstring const & tag,
FABRIC_SERVICE_PARTITION_ACCESS_STATUS expected1)
{
ValidateStatusIs(StatusType::Read, tag, &expected1, nullptr);
ValidateStatusIs(StatusType::Write, tag, &expected1, nullptr);
}
void ReadWriteStatusValidator::ValidateStatusIs(
std::wstring const & tag,
FABRIC_SERVICE_PARTITION_ACCESS_STATUS expected1,
FABRIC_SERVICE_PARTITION_ACCESS_STATUS expected2)
{
ValidateStatusIs(StatusType::Read, tag, &expected1, &expected2);
ValidateStatusIs(StatusType::Write, tag, &expected1, &expected2);
}
void ReadWriteStatusValidator::ValidateStatusIs(
StatusType::Enum type,
std::wstring const & tag,
FABRIC_SERVICE_PARTITION_ACCESS_STATUS * e1,
FABRIC_SERVICE_PARTITION_ACCESS_STATUS * e2)
{
vector<FABRIC_SERVICE_PARTITION_ACCESS_STATUS> expected;
if (e1 != nullptr) expected.push_back(*e1);
if (e2 != nullptr) expected.push_back(*e2);
FABRIC_SERVICE_PARTITION_ACCESS_STATUS actual = FABRIC_SERVICE_PARTITION_ACCESS_STATUS_INVALID;
if (!TryGetStatus(type, actual))
{
return;
}
if (find(expected.cbegin(), expected.cend(), actual) != expected.cend())
{
return;
}
// At this time the status is not in the expected list
// Check it the lease is still valid
auto typeText = type == StatusType::Read ? "read" : "write";
bool isLeaseExpired = false;
auto error = ReliabilityTestApi::ReconfigurationAgentComponentTestApi::IsLeaseExpired(partition_, isLeaseExpired);
TestSession::WriteNoise("RWStatusValidator", "IsLeaseExpired {0}. Error {1}. Actual {2}, Type {3}", isLeaseExpired, error, actual, typeText);
if (!error.IsSuccess())
{
return;
}
if (isLeaseExpired)
{
TestSession::FailTestIf(actual != FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY && actual != FABRIC_SERVICE_PARTITION_ACCESS_STATUS_RECONFIGURATION_PENDING, "{0} status at {1} is {2} when lease is expired. Expected FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY or FABRIC_SERVICE_PARTITION_ACCESS_STATUS_RECONFIGURATION_PENDING",
typeText,
tag,
actual);
return;
}
wstring allowed;
for (auto const & it : expected)
{
allowed += wformatString(it) + L" ";
}
TestSession::FailTest("{0} status mismatch at {1}. Actual = {2}. Allowed = [{3}]",
type == StatusType::Read ? "read" : "write",
tag,
actual,
allowed);
}
bool ReadWriteStatusValidator::TryGetStatus(
StatusType::Enum type,
FABRIC_SERVICE_PARTITION_ACCESS_STATUS & status)
{
function<HRESULT(FABRIC_SERVICE_PARTITION_ACCESS_STATUS &)> func;
if (type == StatusType::Read)
{
func = [this](FABRIC_SERVICE_PARTITION_ACCESS_STATUS & inner) { return partition_->GetReadStatus(&inner); };
}
else
{
func = [this](FABRIC_SERVICE_PARTITION_ACCESS_STATUS & inner) { return partition_->GetWriteStatus(&inner); };
}
auto hr = func(status);
if (SUCCEEDED(hr))
{
TestSession::FailTestIf(status == FABRIC_SERVICE_PARTITION_ACCESS_STATUS_INVALID, "Cannot return invalid partition access status");
return true;
}
else if (hr == FABRIC_E_OBJECT_CLOSED)
{
return false;
}
else
{
TestSession::FailTest("Unknown return value {0}", hr);
return false;
}
}
| 30.976879 | 346 | 0.704422 | [
"vector"
] |
376b94b6951345c5d5bfa907e445a39efee825fa | 4,879 | hh | C++ | track/detail/SurfaceFunctors.hh | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | track/detail/SurfaceFunctors.hh | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | track/detail/SurfaceFunctors.hh | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | //---------------------------------*-C++-*-----------------------------------//
/*!
* \file track/detail/SurfaceFunctors.hh
* \brief Functor definitions used by SurfaceContainer via SurfaceAction
* \note Copyright (c) 2020 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#pragma once
#include <iosfwd>
#include "base/Assert.hh"
#include "orange/Definitions.hh"
#include "orange/surfaces/Definitions.hh"
#include "../Definitions.hh"
namespace celeritas
{
namespace detail
{
//---------------------------------------------------------------------------//
//! Calculate the sense of a surface at a given position.
struct CalcSense
{
SpanConstReal3 pos;
template<class S>
SignedSense operator()(S&& surf)
{
return surf.calc_sense(this->pos);
}
};
//---------------------------------------------------------------------------//
//! Calculate the number of intersections
struct NumIntersections
{
template<class S>
size_type operator()(S&&)
{
return S::num_intersections();
}
};
//---------------------------------------------------------------------------//
//! Calculate the outward normal at a position.
struct CalcNormal
{
SpanConstReal3 pos;
template<class S>
Real3 operator()(S&& surf)
{
return surf.calc_normal(this->pos);
}
};
//---------------------------------------------------------------------------//
//! Calculate the smallest distance from a point to the surface.
struct CalcSafetyDistance
{
SpanConstReal3 pos;
//! Operate on a surface
template<class S>
real_type operator()(S&& surf)
{
// Calculate outward normal
Real3 dir = surf.calc_normal(this->pos);
// If sense is "positive" (on or outside), flip direction to inward so
// that the vector points toward the surface
if (to_sense(surf.calc_sense(this->pos)) == Sense::pos)
dir *= -1;
real_type distance[S::num_intersections()];
surf.calc_intersections(this->pos, dir, SurfaceState::off, distance);
return distance[0];
}
};
//---------------------------------------------------------------------------//
/*!
* Fill an array with distances-to-intersection.
*
* This assumes that each call is to the next face index, starting with face
* zero.
*/
class CalcIntersections
{
public:
//@{
//! Public type aliases
using NextFaceIter = VecNextFace::iterator;
using face_int = FaceId::size_type;
//@}
public:
// Construct from the particle point, direction, and faces
CalcIntersections(const SpanConstReal3& pos,
const SpanConstReal3& dir,
FaceId on_face,
celeritas::VecNextFace* face_dist)
: pos_(pos)
, dir_(dir)
, on_face_idx_(on_face.unchecked_get())
, cur_face_idx_(0)
, cur_face_dist_(face_dist->begin())
, end_face_dist_(face_dist->end())
{
}
// Construct from the local state
CalcIntersections(LocalState state, FaceId on_face)
: pos_(state.pos)
, dir_(state.dir)
, on_face_idx_(on_face.unchecked_get())
, cur_face_idx_(0)
, cur_face_dist_(state.temp_face_dist->begin())
, end_face_dist_(state.temp_face_dist->end())
{
}
//! Operate on a surface
template<class S>
void operator()(S&& surf)
{
auto on_surface = (on_face_idx_ == cur_face_idx_) ? SurfaceState::on
: SurfaceState::off;
// Calculate distance to surface along this direction
real_type temp_distances[S::num_intersections()];
surf.calc_intersections(pos_, dir_, on_surface, temp_distances);
// Copy possible intersections and this surface to the output
for (real_type dist : temp_distances)
{
CELER_ASSERT(cur_face_dist_ != end_face_dist_);
CELER_ASSERT(dist >= 0);
cur_face_dist_->first = FaceId{cur_face_idx_};
cur_face_dist_->second = dist;
++cur_face_dist_;
}
// Increment to next face
++cur_face_idx_;
}
NextFaceIter face_dist_iter() const { return cur_face_dist_; }
face_int face_idx() const { return cur_face_idx_; }
private:
//// DATA ////
const SpanConstReal3 pos_;
const SpanConstReal3 dir_;
const face_int on_face_idx_;
face_int cur_face_idx_;
NextFaceIter cur_face_dist_;
NextFaceIter end_face_dist_;
};
//---------------------------------------------------------------------------//
} // namespace detail
} // namespace celeritas
//---------------------------------------------------------------------------//
| 29.391566 | 79 | 0.530642 | [
"vector"
] |
37753eaff681fad604c36bd9db98c97f317f2091 | 1,591 | cpp | C++ | contracts/xy/src/uid.cpp | eosnationftw/geojsonpoint | e5b38051753d760cbe2759d542e5c9b92a70c002 | [
"MIT"
] | null | null | null | contracts/xy/src/uid.cpp | eosnationftw/geojsonpoint | e5b38051753d760cbe2759d542e5c9b92a70c002 | [
"MIT"
] | null | null | null | contracts/xy/src/uid.cpp | eosnationftw/geojsonpoint | e5b38051753d760cbe2759d542e5c9b92a70c002 | [
"MIT"
] | 2 | 2019-08-12T10:55:42.000Z | 2021-04-13T14:09:39.000Z | name xy::set_uid( const name owner, const uint64_t id, name uid, const name type )
{
// user can provide custom UID (unique identifier)
// user can define a UID for any node/way/relation using a custom name (ex: myuid.xy)
// using UID's lead to easier XY object tracking compared to using auto-incrementing integer
if ( uid.length() > 0 ) {
check( !uid_exists( owner, uid ), "uid already exists" );
// reserve uid for owner account name
if ( is_account( uid ) ) {
check( uid == owner, "uid is reserved for owner account");
} else {
// owner is no-premium *.xy account
const name suffix = owner.suffix();
if (suffix != "xy"_n) {
// must be 12 characters
check( uid.length() == 12, "uid is only availble for *.xy premium accounts (cannot be <12 length)");
// cannot contain `.`
check( uid.suffix() == uid , "uid is only availble for *.xy premium accounts (cannot contain '.')");
}
}
} else {
uid = name{ id };
}
// add owner to table if does not exist
if ( _owner.find( owner.value ) == _owner.end() ) {
_owner.emplace( get_self(), [&]( auto & row ) {
row.owner = owner;
});
}
// Add uid to table
uid_table _uid( get_self(), owner.value );
_uid.emplace( get_self(), [&]( auto & row ) {
row.uid = uid;
row.id = id;
row.owner = owner;
row.type = type;
});
return uid;
}
| 35.355556 | 116 | 0.529227 | [
"object"
] |
37793a2059de92d276a5538b0cef1c671a6b44aa | 3,640 | cpp | C++ | Player.cpp | Firely-Pasha/SpaceInvaders | 1a7427178574527c51e0f39e6ba562395a4bd280 | [
"Apache-2.0"
] | null | null | null | Player.cpp | Firely-Pasha/SpaceInvaders | 1a7427178574527c51e0f39e6ba562395a4bd280 | [
"Apache-2.0"
] | null | null | null | Player.cpp | Firely-Pasha/SpaceInvaders | 1a7427178574527c51e0f39e6ba562395a4bd280 | [
"Apache-2.0"
] | null | null | null | //
// Created by firely-pasha on 6/20/17.
//
#include "Texture2D.h"
#include "Player.h"
#include "GameLevel.h"
#include "Bullet.h"
#include "GameWindow.h"
Player::Player(QString *name, QVector2D *position) : GameObject(name, position, id = -1)
{
speed = 2;
canShoot = true;
hp = 10;
int spriteX = 36;
int spriteY = 416;
int spriteWidth = 13;
int spriteHeight = 8;
pause = false;
texture = new Texture2D(":resources/sprites/SpriteSheet.png", QRect(spriteX, spriteY, spriteWidth, spriteHeight));
setCollider(new QRect(position->x(), position->y(), texture->getWidth(), texture->getHeight()));
}
void Player::update()
{
updateCollider();
}
void Player::render()
{
GameObject::render();
QPainter painter(GameWindow::getPtr());
painter.setFont(*GameWindow::font);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
GameWindow::font->setPointSize(20);
painter.setPen(Qt::yellow);
QString str = "HP: " + QString::number(hp);
painter.drawText(500, 80, str);
str = "Score: " + QString::number(GameLevel::getScore());
painter.drawText(500, 100, str);
if (hp <= 0 || GameLevel::gameOver)
{
painter.setPen(Qt::darkRed);
str = "Game Over!";
GameWindow::font->setPointSize(75);
painter.setFont(*GameWindow::font);
painter.drawText(100, 400, str);
GameLevel::setCanPlay(false);
}
if (GameLevel::getScore() >= GameLevel::ENEMY_COUNT * 10)
{
painter.setPen(Qt::green);
str = "You Win!";
GameWindow::font->setPointSize(75);
painter.setFont(*GameWindow::font);
painter.drawText(200, 400, str);
GameLevel::setCanPlay(false);
}
if (pause)
{
painter.setPen(Qt::darkMagenta);
str = "Pause...";
GameWindow::font->setPointSize(75);
painter.setFont(*GameWindow::font);
painter.drawText(230, 400, str);
GameLevel::setCanPlay(false);
}
painter.end();
};
void Player::keyPressEvent(QKeyEvent *event)
{
if (GameLevel::isCanPlay())
{
if (event->key() == Qt::Key_Right || event->key() == Qt::Key_D)
{
if (position->x() <= 208 - speed)
{
position->setX(position->x() + speed);
}
}
else if (event->key() == Qt::Key_Left || event->key() == Qt::Key_A)
{
if (position->x() >= 16 + speed)
{
position->setX(position->x() - speed);
}
}
else if (event->key() == Qt::Key_F)
{
if (canShoot)
{
createBullet();
}
}
}
if ((event->key() == Qt::Key_P || event->key() == Qt::Key_Escape)
&& !event->isAutoRepeat() && hp > 0
&& GameLevel::getScore() < GameLevel::ENEMY_COUNT * 10)
{
GameLevel::setCanPlay(!GameLevel::isCanPlay());
pause = !GameLevel::isCanPlay();
}
if (event->key() == Qt::Key_R && !event->isAutoRepeat())
{
GameWindow::restartLevel();
}
}
void Player::createBullet()
{
Bullet *bullet;
QVector2D *pos = new QVector2D(position->x() + texture->getWidth() / 2, position->y() + texture->getHeight() - 10);
bullet = new Bullet(pos, true, GameLevel::gameObjects.rbegin()->first + 1, &canShoot, new QString("Enemy"), true);
GameLevel::gameObjects.insert(std::pair<int, GameObject*>(GameLevel::gameObjects.rbegin()->first + 1, bullet->getPtr()));
}
int Player::getHp() const
{
return hp;
}
void Player::addHp(int hp)
{
Player::hp += hp;
}
| 25.815603 | 125 | 0.568407 | [
"render"
] |
377c56e3626cfdc8dadfe7e3da2dfb57dbc86737 | 4,932 | cpp | C++ | test/PAGTimeStretchTest.cpp | DSPerson/libpag | 83d243e4914d688eaf6926128563cbfced6302b8 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | 1 | 2022-01-14T06:12:40.000Z | 2022-01-14T06:12:40.000Z | test/PAGTimeStretchTest.cpp | skymhzhang/libpag | e3d23ee1e84d98c410a48e25a01c52417c74d0f1 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null | test/PAGTimeStretchTest.cpp | skymhzhang/libpag | e3d23ee1e84d98c410a48e25a01c52417c74d0f1 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// unless required by applicable law or agreed to in writing, software distributed under the
// license is distributed on an "as is" basis, without warranties or conditions of any kind,
// either express or implied. see the license for the specific language governing permissions
// and limitations under the license.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#include <fstream>
#include <vector>
#include "TestUtils.h"
#include "base/utils/TimeUtil.h"
#include "framework/pag_test.h"
#include "framework/utils/PAGTestUtils.h"
#include "nlohmann/json.hpp"
namespace pag {
using nlohmann::json;
json dumpJson;
json compareJson;
bool needCompare;
bool dumpStatus;
PAG_TEST_SUIT(PAGTimeStrechTest)
void initData() {
std::ifstream inputFile("../test/res/compare_timestretch_md5.json");
if (inputFile) {
needCompare = true;
inputFile >> compareJson;
dumpJson = compareJson;
}
}
void saveFile() {
if (dumpStatus) {
std::ofstream outFile("../test/out/compare_timestretch_md5.json");
outFile << std::setw(4) << dumpJson << std::endl;
outFile.close();
}
}
void TimeStretchTest(std::string path, float scaleFactor) {
std::vector<int> shortenArray = {0, 6, 30, 59};
std::vector<int> stretchArray = {0, 12, 120, 239};
auto fileName = path.substr(path.rfind("/") + 1, path.size());
std::vector<std::string> compareVector;
auto TestPAGFile = PAGFile::Load(path);
ASSERT_NE(TestPAGFile, nullptr);
int64_t duartion = TestPAGFile->duration();
std::vector<int> array;
TestPAGFile->setDuration(duartion * scaleFactor);
if (scaleFactor < 1) {
fileName += "_shorten";
array = shortenArray;
} else {
fileName += "_stretch";
array = stretchArray;
}
bool needCompareThis = false;
if (needCompare && compareJson.contains(fileName) && compareJson[fileName].is_array()) {
compareVector = compareJson[fileName].get<std::vector<std::string>>();
needCompareThis = true;
}
auto pagSurface = PAGSurface::MakeOffscreen(TestPAGFile->width(), TestPAGFile->height());
ASSERT_NE(pagSurface, nullptr);
auto pagPlayer = std::make_shared<PAGPlayer>();
pagPlayer->setSurface(pagSurface);
pagPlayer->setComposition(TestPAGFile);
Frame totalFrames = TimeToFrame(TestPAGFile->duration(), TestPAGFile->frameRate());
std::vector<std::string> md5Vector;
std::string errorMsg = "";
auto pagImage = PAGImage::FromPath("../resources/apitest/test_timestretch.png");
TestPAGFile->replaceImage(0, pagImage);
bool status = true;
int index = 0;
for (const auto& currentFrame : array) {
pagPlayer->setProgress((currentFrame + 0.1) * 1.0 / totalFrames);
pagPlayer->getProgress();
pagPlayer->flush();
auto skImage = MakeSnapshot(pagSurface);
std::string md5 = DumpMD5(skImage);
md5Vector.push_back(md5);
if (needCompareThis && compareVector[index] != md5) {
errorMsg += (std::to_string(currentFrame) + ";");
if (status) {
std::string imagePath =
"../test/out/" + fileName + "_" + std::to_string(currentFrame) + ".png";
Trace(skImage, imagePath);
status = false;
dumpStatus = true;
}
}
index++;
}
EXPECT_EQ(errorMsg, "") << fileName << " frame fail";
dumpJson[fileName] = md5Vector;
}
/**
* 用例描述: PAGTimeStrech渲染测试: Repeat模式-缩减
*/
PAG_TEST_F(PAGTimeStrechTest, Repeat_Shorten_TestMD5) {
initData();
TimeStretchTest("../resources/timestretch/repeat.pag", 0.5);
}
/**
* 用例描述: PAGTimeStrech渲染测试: Repeat模式-拉伸
*/
PAG_TEST_F(PAGTimeStrechTest, Repeat_Stretch_TestMD5) {
TimeStretchTest("../resources/timestretch/repeat.pag", 2);
}
/**
* 用例描述: PAGTimeStrech渲染测试-RepeatInverted-缩减
*/
PAG_TEST_F(PAGTimeStrechTest, RepeatInverted_Shorten_TestMD5) {
TimeStretchTest("../resources/timestretch/repeatInverted.pag", 0.5);
}
/**
* 用例描述: PAGTimeStrech渲染测试-RepeatInverted-拉伸
*/
PAG_TEST_F(PAGTimeStrechTest, RepeatInverted_Stretch_TestMD5) {
TimeStretchTest("../resources/timestretch/repeatInverted.pag", 2);
}
/**
* 用例描述: PAGTimeStrech渲染测试-Scale模式-缩减
*/
PAG_TEST_F(PAGTimeStrechTest, Scale_Shorten_TestMD5) {
TimeStretchTest("../resources/timestretch/scale.pag", 0.5);
}
/**
* 用例描述: PAGTimeStrech渲染测试: Scale模式-拉伸
*/
PAG_TEST_F(PAGTimeStrechTest, Scale_Stretch_TestMD5) {
TimeStretchTest("../resources/timestretch/scale.pag", 2);
saveFile();
}
} // namespace pag
| 29.532934 | 97 | 0.672749 | [
"vector"
] |
377fda916781d37d63082aab367a241facbaf8a7 | 31,985 | cpp | C++ | OpenSees/SRC/element/elasticBeamColumn/ElasticBeam3d.cpp | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | null | null | null | OpenSees/SRC/element/elasticBeamColumn/ElasticBeam3d.cpp | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | null | null | null | OpenSees/SRC/element/elasticBeamColumn/ElasticBeam3d.cpp | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | 1 | 2020-08-06T21:12:16.000Z | 2020-08-06T21:12:16.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 6658 $
// $Date: 2018-01-28 12:29:45 -0800 (Sun, 28 Jan 2018) $
// $URL: svn://peera.berkeley.edu/usr/local/svn/OpenSees/trunk/SRC/element/elasticBeamColumn/ElasticBeam3d.cpp $
// File: ~/model/ElasticBeam3d.C
//
// Written: fmk 11/95
// Revised:
//
// Purpose: This file contains the class definition for ElasticBeam3d.
// ElasticBeam3d is a 3d beam element. As such it can only
// connect to a node with 6-dof.
#include <ElasticBeam3d.h>
#include <Domain.h>
#include <Channel.h>
#include <FEM_ObjectBroker.h>
#include <CrdTransf.h>
#include <Information.h>
#include <Parameter.h>
#include <ElementResponse.h>
#include <ElementalLoad.h>
#include <Renderer.h>
#include <SectionForceDeformation.h>
#include <ID.h>
#include <math.h>
#include <stdlib.h>
#include <string>
#include <elementAPI.h>
Matrix ElasticBeam3d::K(12,12);
Vector ElasticBeam3d::P(12);
Matrix ElasticBeam3d::kb(6,6);
void* OPS_ElasticBeam3d(void)
{
int numArgs = OPS_GetNumRemainingInputArgs();
if(numArgs < 10 && numArgs != 5) {
opserr<<"insufficient arguments:eleTag,iNode,jNode,A,E,G,J,Iy,Iz,transfTag\n";
return 0;
}
int ndm = OPS_GetNDM();
int ndf = OPS_GetNDF();
if(ndm != 3 || ndf != 6) {
opserr<<"ndm must be 3 and ndf must be 6\n";
return 0;
}
// inputs:
int iData[3];
int numData = 3;
if(OPS_GetIntInput(&numData,&iData[0]) < 0) return 0;
SectionForceDeformation* theSection = 0;
CrdTransf* theTrans = 0;
double data[6];
int transfTag, secTag;
if(numArgs == 5) {
numData = 1;
if(OPS_GetIntInput(&numData,&secTag) < 0) return 0;
if(OPS_GetIntInput(&numData,&transfTag) < 0) return 0;
theSection = OPS_getSectionForceDeformation(secTag);
if(theSection == 0) {
opserr<<"no section is found\n";
return 0;
}
theTrans = OPS_getCrdTransf(transfTag);
if(theTrans == 0) {
opserr<<"no CrdTransf is found\n";
return 0;
}
} else {
numData = 6;
if(OPS_GetDoubleInput(&numData,&data[0]) < 0) return 0;
numData = 1;
if(OPS_GetIntInput(&numData,&transfTag) < 0) return 0;
theTrans = OPS_getCrdTransf(transfTag);
if(theTrans == 0) {
opserr<<"no CrdTransf is found\n";
return 0;
}
}
// options
double mass = 0.0;
int cMass = 0;
while(OPS_GetNumRemainingInputArgs() > 0) {
std::string theType = OPS_GetString();
if (theType == "-mass") {
if(OPS_GetNumRemainingInputArgs() > 0) {
if(OPS_GetDoubleInput(&numData,&mass) < 0) return 0;
}
} else if (theType == "-cMass") {
cMass = 1;
}
}
if (theSection != 0) {
return new ElasticBeam3d(iData[0],iData[1],iData[2],theSection,*theTrans,mass,cMass);
} else {
return new ElasticBeam3d(iData[0],data[0],data[1],data[2],data[3],data[4],
data[5],iData[1],iData[2],*theTrans, mass,cMass);
}
}
ElasticBeam3d::ElasticBeam3d()
:Element(0,ELE_TAG_ElasticBeam3d),
A(0.0), E(0.0), G(0.0), Jx(0.0), Iy(0.0), Iz(0.0), rho(0.0), cMass(0),
Q(12), q(6), connectedExternalNodes(2), theCoordTransf(0)
{
// does nothing
q0[0] = 0.0;
q0[1] = 0.0;
q0[2] = 0.0;
q0[3] = 0.0;
q0[4] = 0.0;
p0[0] = 0.0;
p0[1] = 0.0;
p0[2] = 0.0;
p0[3] = 0.0;
p0[4] = 0.0;
// set node pointers to NULL
for (int i=0; i<2; i++)
theNodes[i] = 0;
}
ElasticBeam3d::ElasticBeam3d(int tag, double a, double e, double g,
double jx, double iy, double iz, int Nd1, int Nd2,
CrdTransf &coordTransf, double r, int cm, int sectTag)
:Element(tag,ELE_TAG_ElasticBeam3d),
A(a), E(e), G(g), Jx(jx), Iy(iy), Iz(iz), rho(r), cMass(cm), sectionTag(sectTag),
Q(12), q(6), connectedExternalNodes(2), theCoordTransf(0)
{
connectedExternalNodes(0) = Nd1;
connectedExternalNodes(1) = Nd2;
theCoordTransf = coordTransf.getCopy3d();
if (!theCoordTransf) {
opserr << "ElasticBeam3d::ElasticBeam3d -- failed to get copy of coordinate transformation\n";
exit(-1);
}
q0[0] = 0.0;
q0[1] = 0.0;
q0[2] = 0.0;
q0[3] = 0.0;
q0[4] = 0.0;
p0[0] = 0.0;
p0[1] = 0.0;
p0[2] = 0.0;
p0[3] = 0.0;
p0[4] = 0.0;
// set node pointers to NULL
for (int i=0; i<2; i++)
theNodes[i] = 0;
}
ElasticBeam3d::ElasticBeam3d(int tag, int Nd1, int Nd2, SectionForceDeformation *section,
CrdTransf &coordTransf, double r, int cm)
:Element(tag,ELE_TAG_ElasticBeam3d),
Q(12), q(6), connectedExternalNodes(2), theCoordTransf(0)
{
if (section != 0) {
sectionTag = section->getTag();
E = 1.0;
G = 1.0;
Jx = 0.0;
rho = r;
cMass = cm;
const Matrix §Tangent = section->getSectionTangent();
const ID §Code = section->getType();
for (int i=0; i<sectCode.Size(); i++) {
int code = sectCode(i);
switch(code) {
case SECTION_RESPONSE_P:
A = sectTangent(i,i);
break;
case SECTION_RESPONSE_MZ:
Iz = sectTangent(i,i);
break;
case SECTION_RESPONSE_MY:
Iy = sectTangent(i,i);
break;
case SECTION_RESPONSE_T:
Jx = sectTangent(i,i);
break;
default:
break;
}
}
}
if (Jx == 0.0) {
opserr << "ElasticBeam3d::ElasticBeam3d -- no torsion in section -- setting GJ = 1.0e10\n";
Jx = 1.0e10;
}
connectedExternalNodes(0) = Nd1;
connectedExternalNodes(1) = Nd2;
theCoordTransf = coordTransf.getCopy3d();
if (!theCoordTransf) {
opserr << "ElasticBeam3d::ElasticBeam3d -- failed to get copy of coordinate transformation\n";
exit(-1);
}
q0[0] = 0.0;
q0[1] = 0.0;
q0[2] = 0.0;
q0[3] = 0.0;
q0[4] = 0.0;
p0[0] = 0.0;
p0[1] = 0.0;
p0[2] = 0.0;
p0[3] = 0.0;
p0[4] = 0.0;
// set node pointers to NULL
for (int i=0; i<2; i++)
theNodes[i] = 0;
}
ElasticBeam3d::~ElasticBeam3d()
{
if (theCoordTransf)
delete theCoordTransf;
}
int
ElasticBeam3d::getNumExternalNodes(void) const
{
return 2;
}
const ID &
ElasticBeam3d::getExternalNodes(void)
{
return connectedExternalNodes;
}
Node **
ElasticBeam3d::getNodePtrs(void)
{
return theNodes;
}
int
ElasticBeam3d::getNumDOF(void)
{
return 12;
}
void
ElasticBeam3d::setDomain(Domain *theDomain)
{
if (theDomain == 0) {
opserr << "ElasticBeam3d::setDomain -- Domain is null\n";
exit(-1);
}
theNodes[0] = theDomain->getNode(connectedExternalNodes(0));
theNodes[1] = theDomain->getNode(connectedExternalNodes(1));
if (theNodes[0] == 0) {
opserr << "ElasticBeam3d::setDomain tag: " << this->getTag() << " -- Node 1: " << connectedExternalNodes(0) << " does not exist\n";
exit(-1);
}
if (theNodes[1] == 0) {
opserr << "ElasticBeam3d::setDomain tag: " << this->getTag() << " -- Node 2: " << connectedExternalNodes(1) << " does not exist\n";
exit(-1);
}
int dofNd1 = theNodes[0]->getNumberDOF();
int dofNd2 = theNodes[1]->getNumberDOF();
if (dofNd1 != 6) {
opserr << "ElasticBeam3d::setDomain tag: " << this->getTag() << " -- Node 1: " << connectedExternalNodes(0)
<< " has incorrect number of DOF\n";
exit(-1);
}
if (dofNd2 != 6) {
opserr << "ElasticBeam3d::setDomain tag: " << this->getTag() << " -- Node 2: " << connectedExternalNodes(1)
<< " has incorrect number of DOF\n";
exit(-1);
}
this->DomainComponent::setDomain(theDomain);
if (theCoordTransf->initialize(theNodes[0], theNodes[1]) != 0) {
opserr << "ElasticBeam3d::setDomain tag: " << this->getTag() << " -- Error initializing coordinate transformation\n";
exit(-1);
}
double L = theCoordTransf->getInitialLength();
if (L == 0.0) {
opserr << "ElasticBeam3d::setDomain tag: " << this->getTag() << " -- Element has zero length\n";
exit(-1);
}
}
int
ElasticBeam3d::commitState()
{
int retVal = 0;
// call element commitState to do any base class stuff
if ((retVal = this->Element::commitState()) != 0) {
opserr << "ElasticBeam3d::commitState () - failed in base class";
}
retVal += theCoordTransf->commitState();
return retVal;
}
int
ElasticBeam3d::revertToLastCommit()
{
return theCoordTransf->revertToLastCommit();
}
int
ElasticBeam3d::revertToStart()
{
return theCoordTransf->revertToStart();
}
int
ElasticBeam3d::update(void)
{
return theCoordTransf->update();
}
const Matrix &
ElasticBeam3d::getTangentStiff(void)
{
const Vector &v = theCoordTransf->getBasicTrialDisp();
double L = theCoordTransf->getInitialLength();
double oneOverL = 1.0/L;
double EoverL = E*oneOverL;
double EAoverL = A*EoverL; // EA/L
double EIzoverL2 = 2.0*Iz*EoverL; // 2EIz/L
double EIzoverL4 = 2.0*EIzoverL2; // 4EIz/L
double EIyoverL2 = 2.0*Iy*EoverL; // 2EIy/L
double EIyoverL4 = 2.0*EIyoverL2; // 4EIy/L
double GJoverL = G*Jx*oneOverL; // GJ/L
q(0) = EAoverL*v(0);
q(1) = EIzoverL4*v(1) + EIzoverL2*v(2);
q(2) = EIzoverL2*v(1) + EIzoverL4*v(2);
q(3) = EIyoverL4*v(3) + EIyoverL2*v(4);
q(4) = EIyoverL2*v(3) + EIyoverL4*v(4);
q(5) = GJoverL*v(5);
q(0) += q0[0];
q(1) += q0[1];
q(2) += q0[2];
q(3) += q0[3];
q(4) += q0[4];
kb(0,0) = EAoverL;
kb(1,1) = kb(2,2) = EIzoverL4;
kb(2,1) = kb(1,2) = EIzoverL2;
kb(3,3) = kb(4,4) = EIyoverL4;
kb(4,3) = kb(3,4) = EIyoverL2;
kb(5,5) = GJoverL;
return theCoordTransf->getGlobalStiffMatrix(kb,q);
}
const Matrix &
ElasticBeam3d::getInitialStiff(void)
{
// const Vector &v = theCoordTransf->getBasicTrialDisp();
double L = theCoordTransf->getInitialLength();
double oneOverL = 1.0/L;
double EoverL = E*oneOverL;
double EAoverL = A*EoverL; // EA/L
double EIzoverL2 = 2.0*Iz*EoverL; // 2EIz/L
double EIzoverL4 = 2.0*EIzoverL2; // 4EIz/L
double EIyoverL2 = 2.0*Iy*EoverL; // 2EIy/L
double EIyoverL4 = 2.0*EIyoverL2; // 4EIy/L
double GJoverL = G*Jx*oneOverL; // GJ/L
kb(0,0) = EAoverL;
kb(1,1) = kb(2,2) = EIzoverL4;
kb(2,1) = kb(1,2) = EIzoverL2;
kb(3,3) = kb(4,4) = EIyoverL4;
kb(4,3) = kb(3,4) = EIyoverL2;
kb(5,5) = GJoverL;
return theCoordTransf->getInitialGlobalStiffMatrix(kb);
}
const Matrix &
ElasticBeam3d::getMass(void)
{
K.Zero();
if (rho > 0.0) {
// get initial element length
double L = theCoordTransf->getInitialLength();
if (cMass == 0) {
// lumped mass matrix
double m = 0.5*rho*L;
K(0,0) = m;
K(1,1) = m;
K(2,2) = m;
K(6,6) = m;
K(7,7) = m;
K(8,8) = m;
} else {
// consistent mass matrix
static Matrix ml(12,12);
double m = rho*L/420.0;
ml(0,0) = ml(6,6) = m*140.0;
ml(0,6) = ml(6,0) = m*70.0;
ml(3,3) = ml(9,9) = m*(Jx/A)*140.0;
ml(3,9) = ml(9,3) = m*(Jx/A)*70.0;
ml(2,2) = ml(8,8) = m*156.0;
ml(2,8) = ml(8,2) = m*54.0;
ml(4,4) = ml(10,10) = m*4.0*L*L;
ml(4,10) = ml(10,4) = -m*3.0*L*L;
ml(2,4) = ml(4,2) = -m*22.0*L;
ml(8,10) = ml(10,8) = -ml(2,4);
ml(2,10) = ml(10,2) = m*13.0*L;
ml(4,8) = ml(8,4) = -ml(2,10);
ml(1,1) = ml(7,7) = m*156.0;
ml(1,7) = ml(7,1) = m*54.0;
ml(5,5) = ml(11,11) = m*4.0*L*L;
ml(5,11) = ml(11,5) = -m*3.0*L*L;
ml(1,5) = ml(5,1) = m*22.0*L;
ml(7,11) = ml(11,7) = -ml(1,5);
ml(1,11) = ml(11,1) = -m*13.0*L;
ml(5,7) = ml(7,5) = -ml(1,11);
// transform local mass matrix to global system
K = theCoordTransf->getGlobalMatrixFromLocal(ml);
}
}
return K;
}
void
ElasticBeam3d::zeroLoad(void)
{
Q.Zero();
q0[0] = 0.0;
q0[1] = 0.0;
q0[2] = 0.0;
q0[3] = 0.0;
q0[4] = 0.0;
p0[0] = 0.0;
p0[1] = 0.0;
p0[2] = 0.0;
p0[3] = 0.0;
p0[4] = 0.0;
return;
}
int
ElasticBeam3d::addLoad(ElementalLoad *theLoad, double loadFactor)
{
int type;
const Vector &data = theLoad->getData(type, loadFactor);
double L = theCoordTransf->getInitialLength();
if (type == LOAD_TAG_Beam3dUniformLoad) {
double wy = data(0)*loadFactor; // Transverse
double wz = data(1)*loadFactor; // Transverse
double wx = data(2)*loadFactor; // Axial (+ve from node I to J)
double Vy = 0.5*wy*L;
double Mz = Vy*L/6.0; // wy*L*L/12
double Vz = 0.5*wz*L;
double My = Vz*L/6.0; // wz*L*L/12
double P = wx*L;
// Reactions in basic system
p0[0] -= P;
p0[1] -= Vy;
p0[2] -= Vy;
p0[3] -= Vz;
p0[4] -= Vz;
// Fixed end forces in basic system
q0[0] -= 0.5*P;
q0[1] -= Mz;
q0[2] += Mz;
q0[3] += My;
q0[4] -= My;
}
else if (type == LOAD_TAG_Beam3dPointLoad) {
double Py = data(0)*loadFactor;
double Pz = data(1)*loadFactor;
double N = data(2)*loadFactor;
double aOverL = data(3);
if (aOverL < 0.0 || aOverL > 1.0)
return 0;
double a = aOverL*L;
double b = L-a;
// Reactions in basic system
p0[0] -= N;
double V1, V2;
V1 = Py*(1.0-aOverL);
V2 = Py*aOverL;
p0[1] -= V1;
p0[2] -= V2;
V1 = Pz*(1.0-aOverL);
V2 = Pz*aOverL;
p0[3] -= V1;
p0[4] -= V2;
double L2 = 1.0/(L*L);
double a2 = a*a;
double b2 = b*b;
// Fixed end forces in basic system
q0[0] -= N*aOverL;
double M1, M2;
M1 = -a * b2 * Py * L2;
M2 = a2 * b * Py * L2;
q0[1] += M1;
q0[2] += M2;
M1 = -a * b2 * Pz * L2;
M2 = a2 * b * Pz * L2;
q0[3] -= M1;
q0[4] -= M2;
}
else {
opserr << "ElasticBeam3d::addLoad() -- load type unknown for element with tag: " << this->getTag() << endln;
return -1;
}
return 0;
}
int
ElasticBeam3d::addInertiaLoadToUnbalance(const Vector &accel)
{
if (rho == 0.0)
return 0;
// get R * accel from the nodes
const Vector &Raccel1 = theNodes[0]->getRV(accel);
const Vector &Raccel2 = theNodes[1]->getRV(accel);
if (6 != Raccel1.Size() || 6 != Raccel2.Size()) {
opserr << "ElasticBeam3d::addInertiaLoadToUnbalance matrix and vector sizes are incompatable\n";
return -1;
}
// want to add ( - fact * M R * accel ) to unbalance
if (cMass == 0) {
// take advantage of lumped mass matrix
double L = theCoordTransf->getInitialLength();
double m = 0.5*rho*L;
Q(0) -= m * Raccel1(0);
Q(1) -= m * Raccel1(1);
Q(2) -= m * Raccel1(2);
Q(6) -= m * Raccel2(0);
Q(7) -= m * Raccel2(1);
Q(8) -= m * Raccel2(2);
} else {
// use matrix vector multip. for consistent mass matrix
static Vector Raccel(12);
for (int i=0; i<6; i++) {
Raccel(i) = Raccel1(i);
Raccel(i+6) = Raccel2(i);
}
Q.addMatrixVector(1.0, this->getMass(), Raccel, -1.0);
}
return 0;
}
const Vector &
ElasticBeam3d::getResistingForceIncInertia()
{
P = this->getResistingForce();
// subtract external load P = P - Q
P.addVector(1.0, Q, -1.0);
// add the damping forces if rayleigh damping
if (alphaM != 0.0 || betaK != 0.0 || betaK0 != 0.0 || betaKc != 0.0)
P.addVector(1.0, this->getRayleighDampingForces(), 1.0);
if (rho == 0.0)
return P;
// add inertia forces from element mass
const Vector &accel1 = theNodes[0]->getTrialAccel();
const Vector &accel2 = theNodes[1]->getTrialAccel();
if (cMass == 0) {
// take advantage of lumped mass matrix
double L = theCoordTransf->getInitialLength();
double m = 0.5*rho*L;
P(0) += m * accel1(0);
P(1) += m * accel1(1);
P(2) += m * accel1(2);
P(6) += m * accel2(0);
P(7) += m * accel2(1);
P(8) += m * accel2(2);
} else {
// use matrix vector multip. for consistent mass matrix
static Vector accel(12);
for (int i=0; i<6; i++) {
accel(i) = accel1(i);
accel(i+6) = accel2(i);
}
P.addMatrixVector(1.0, this->getMass(), accel, 1.0);
}
return P;
}
const Vector &
ElasticBeam3d::getResistingForce()
{
const Vector &v = theCoordTransf->getBasicTrialDisp();
double L = theCoordTransf->getInitialLength();
double oneOverL = 1.0/L;
double EoverL = E*oneOverL;
double EAoverL = A*EoverL; // EA/L
double EIzoverL2 = 2.0*Iz*EoverL; // 2EIz/L
double EIzoverL4 = 2.0*EIzoverL2; // 4EIz/L
double EIyoverL2 = 2.0*Iy*EoverL; // 2EIy/L
double EIyoverL4 = 2.0*EIyoverL2; // 4EIy/L
double GJoverL = G*Jx*oneOverL; // GJ/L
q(0) = EAoverL*v(0);
q(1) = EIzoverL4*v(1) + EIzoverL2*v(2);
q(2) = EIzoverL2*v(1) + EIzoverL4*v(2);
q(3) = EIyoverL4*v(3) + EIyoverL2*v(4);
q(4) = EIyoverL2*v(3) + EIyoverL4*v(4);
q(5) = GJoverL*v(5);
q(0) += q0[0];
q(1) += q0[1];
q(2) += q0[2];
q(3) += q0[3];
q(4) += q0[4];
Vector p0Vec(p0, 5);
// opserr << q;
P = theCoordTransf->getGlobalResistingForce(q, p0Vec);
// opserr << P;
return P;
}
int
ElasticBeam3d::sendSelf(int cTag, Channel &theChannel)
{
int res = 0;
static Vector data(17);
data(0) = A;
data(1) = E;
data(2) = G;
data(3) = Jx;
data(4) = Iy;
data(5) = Iz;
data(6) = rho;
data(7) = cMass;
data(8) = this->getTag();
data(9) = connectedExternalNodes(0);
data(10) = connectedExternalNodes(1);
data(11) = theCoordTransf->getClassTag();
int dbTag = theCoordTransf->getDbTag();
if (dbTag == 0) {
dbTag = theChannel.getDbTag();
if (dbTag != 0)
theCoordTransf->setDbTag(dbTag);
}
data(12) = dbTag;
data(13) = alphaM;
data(14) = betaK;
data(15) = betaK0;
data(16) = betaKc;
// Send the data vector
res += theChannel.sendVector(this->getDbTag(), cTag, data);
if (res < 0) {
opserr << "ElasticBeam3d::sendSelf -- could not send data Vector\n";
return res;
}
// Ask the CoordTransf to send itself
res += theCoordTransf->sendSelf(cTag, theChannel);
if (res < 0) {
opserr << "ElasticBeam3d::sendSelf -- could not send CoordTransf\n";
return res;
}
return res;
}
int
ElasticBeam3d::recvSelf(int cTag, Channel &theChannel, FEM_ObjectBroker &theBroker)
{
int res = 0;
static Vector data(17);
res += theChannel.recvVector(this->getDbTag(), cTag, data);
if (res < 0) {
opserr << "ElasticBeam3d::recvSelf -- could not receive data Vector\n";
return res;
}
A = data(0);
E = data(1);
G = data(2);
Jx = data(3);
Iy = data(4);
Iz = data(5);
rho = data(6);
cMass = (int)data(7);
this->setTag((int)data(8));
connectedExternalNodes(0) = (int)data(9);
connectedExternalNodes(1) = (int)data(10);
alphaM = data(13);
betaK = data(14);
betaK0 = data(15);
betaKc = data(16);
// Check if the CoordTransf is null; if so, get a new one
int crdTag = (int)data(11);
if (theCoordTransf == 0) {
theCoordTransf = theBroker.getNewCrdTransf(crdTag);
if (theCoordTransf == 0) {
opserr << "ElasticBeam3d::recvSelf -- could not get a CrdTransf3d\n";
exit(-1);
}
}
// Check that the CoordTransf is of the right type; if not, delete
// the current one and get a new one of the right type
if (theCoordTransf->getClassTag() != crdTag) {
delete theCoordTransf;
theCoordTransf = theBroker.getNewCrdTransf(crdTag);
if (theCoordTransf == 0) {
opserr << "ElasticBeam3d::recvSelf -- could not get a CrdTransf3d\n";
exit(-1);
}
}
// Now, receive the CoordTransf
theCoordTransf->setDbTag((int)data(12));
res += theCoordTransf->recvSelf(cTag, theChannel, theBroker);
if (res < 0) {
opserr << "ElasticBeam3d::recvSelf -- could not receive CoordTransf\n";
return res;
}
return res;
}
void
ElasticBeam3d::Print(OPS_Stream &s, int flag)
{
this->getResistingForce();
if (flag == -1) {
int eleTag = this->getTag();
s << "EL_BEAM\t" << eleTag << "\t";
s << sectionTag << "\t" << sectionTag;
s << "\t" << connectedExternalNodes(0) << "\t" << connectedExternalNodes(1);
s << "\t0\t0.0000000\n";
}
else if (flag < -1) {
int counter = (flag + 1) * -1;
int eleTag = this->getTag();
const Vector &force = this->getResistingForce();
double P, MZ1, MZ2, VY, MY1, MY2, VZ, T;
double L = theCoordTransf->getInitialLength();
double oneOverL = 1.0 / L;
P = q(0);
MZ1 = q(1);
MZ2 = q(2);
VY = (MZ1 + MZ2)*oneOverL;
MY1 = q(3);
MY2 = q(4);
VZ = (MY1 + MY2)*oneOverL;
T = q(5);
s << "FORCE\t" << eleTag << "\t" << counter << "\t0";
s << "\t" << -P + p0[0] << "\t" << VY + p0[1] << "\t" << -VZ + p0[3] << endln;
s << "FORCE\t" << eleTag << "\t" << counter << "\t1";
s << "\t" << P << ' ' << -VY + p0[2] << ' ' << VZ + p0[4] << endln;
s << "MOMENT\t" << eleTag << "\t" << counter << "\t0";
s << "\t" << -T << "\t" << MY1 << "\t" << MZ1 << endln;
s << "MOMENT\t" << eleTag << "\t" << counter << "\t1";
s << "\t" << T << ' ' << MY2 << ' ' << MZ2 << endln;
}
else if (flag == 2) {
this->getResistingForce(); // in case linear algo
static Vector xAxis(3);
static Vector yAxis(3);
static Vector zAxis(3);
theCoordTransf->getLocalAxes(xAxis, yAxis, zAxis);
s << "#ElasticBeamColumn3D\n";
s << "#LocalAxis " << xAxis(0) << " " << xAxis(1) << " " << xAxis(2);
s << " " << yAxis(0) << " " << yAxis(1) << " " << yAxis(2) << " ";
s << zAxis(0) << " " << zAxis(1) << " " << zAxis(2) << endln;
const Vector &node1Crd = theNodes[0]->getCrds();
const Vector &node2Crd = theNodes[1]->getCrds();
const Vector &node1Disp = theNodes[0]->getDisp();
const Vector &node2Disp = theNodes[1]->getDisp();
s << "#NODE " << node1Crd(0) << " " << node1Crd(1) << " " << node1Crd(2)
<< " " << node1Disp(0) << " " << node1Disp(1) << " " << node1Disp(2)
<< " " << node1Disp(3) << " " << node1Disp(4) << " " << node1Disp(5) << endln;
s << "#NODE " << node2Crd(0) << " " << node2Crd(1) << " " << node2Crd(2)
<< " " << node2Disp(0) << " " << node2Disp(1) << " " << node2Disp(2)
<< " " << node2Disp(3) << " " << node2Disp(4) << " " << node2Disp(5) << endln;
double N, Mz1, Mz2, Vy, My1, My2, Vz, T;
double L = theCoordTransf->getInitialLength();
double oneOverL = 1.0 / L;
N = q(0);
Mz1 = q(1);
Mz2 = q(2);
Vy = (Mz1 + Mz2)*oneOverL;
My1 = q(3);
My2 = q(4);
Vz = -(My1 + My2)*oneOverL;
T = q(5);
s << "#END_FORCES " << -N + p0[0] << ' ' << Vy + p0[1] << ' ' << Vz + p0[3] << ' '
<< -T << ' ' << My1 << ' ' << Mz1 << endln;
s << "#END_FORCES " << N << ' ' << -Vy + p0[2] << ' ' << -Vz + p0[4] << ' '
<< T << ' ' << My2 << ' ' << Mz2 << endln;
}
if (flag == OPS_PRINT_CURRENTSTATE) {
this->getResistingForce(); // in case linear algo
s << "\nElasticBeam3d: " << this->getTag() << endln;
s << "\tConnected Nodes: " << connectedExternalNodes;
s << "\tCoordTransf: " << theCoordTransf->getTag() << endln;
s << "\tmass density: " << rho << ", cMass: " << cMass << endln;
double N, Mz1, Mz2, Vy, My1, My2, Vz, T;
double L = theCoordTransf->getInitialLength();
double oneOverL = 1.0 / L;
N = q(0);
Mz1 = q(1);
Mz2 = q(2);
Vy = (Mz1 + Mz2)*oneOverL;
My1 = q(3);
My2 = q(4);
Vz = -(My1 + My2)*oneOverL;
T = q(5);
s << "\tEnd 1 Forces (P Mz Vy My Vz T): "
<< -N + p0[0] << ' ' << Mz1 << ' ' << Vy + p0[1] << ' ' << My1 << ' ' << Vz + p0[3] << ' ' << -T << endln;
s << "\tEnd 2 Forces (P Mz Vy My Vz T): "
<< N << ' ' << Mz2 << ' ' << -Vy + p0[2] << ' ' << My2 << ' ' << -Vz + p0[4] << ' ' << T << endln;
}
if (flag == OPS_PRINT_PRINTMODEL_JSON) {
s << "\t\t\t{";
s << "\"name\": " << this->getTag() << ", ";
s << "\"type\": \"ElasticBeam3d\", ";
s << "\"nodes\": [" << connectedExternalNodes(0) << ", " << connectedExternalNodes(1) << "], ";
s << "\"E\": " << E << ", ";
s << "\"G\": " << G << ", ";
s << "\"A\": " << A << ", ";
s << "\"Jx\": " << Jx << ", ";
s << "\"Iy\": " << Iy << ", ";
s << "\"Iz\": " << Iz << ", ";
s << "\"massperlength\": " << rho << ", ";
s << "\"crdTransformation\": \"" << theCoordTransf->getTag() << "\"}";
}
}
int
ElasticBeam3d::displaySelf(Renderer &theViewer, int displayMode, float fact, const char **modes, int numMode)
{
static Vector v1(3);
static Vector v2(3);
theNodes[0]->getDisplayCrds(v1, fact);
theNodes[1]->getDisplayCrds(v2, fact);
float d1 = 0.0;
float d2 = 0.0;
int res = 0;
if (displayMode > 0) {
res += theViewer.drawLine(v1, v2, d1, d1, this->getTag(), 0);
} else if (displayMode < 0) {
theNodes[0]->getDisplayCrds(v1, 0.);
theNodes[1]->getDisplayCrds(v2, 0.);
// add eigenvector values
int mode = displayMode * -1;
const Matrix &eigen1 = theNodes[0]->getEigenvectors();
const Matrix &eigen2 = theNodes[1]->getEigenvectors();
if (eigen1.noCols() >= mode) {
for (int i = 0; i < 3; i++) {
v1(i) += eigen1(i,mode-1)*fact;
v2(i) += eigen2(i,mode-1)*fact;
}
}
return theViewer.drawLine (v1, v2, 0.0, 0.0, this->getTag(), 0);
}
if (numMode > 0) {
// calculate q for potential need below
this->getResistingForce();
}
for (int i=0; i<numMode; i++) {
const char *theMode = modes[i];
if (strcmp(theMode, "axialForce") == 0) {
d1 = q(0);
d2 = q(0);;
res +=theViewer.drawLine(v1, v2, d1, d1, this->getTag(), i);
} else if (strcmp(theMode, "endMoments") == 0) {
d1 = q(1);
d2 = q(2);
static Vector delta(3); delta = v2-v1; delta/=10;
res += theViewer.drawPoint(v1+delta, d1, this->getTag(), i);
res += theViewer.drawPoint(v2-delta, d2, this->getTag(), i);
}
}
return res;
}
Response*
ElasticBeam3d::setResponse(const char **argv, int argc, OPS_Stream &output)
{
Response *theResponse = 0;
output.tag("ElementOutput");
output.attr("eleType","ElasticBeam3d");
output.attr("eleTag",this->getTag());
output.attr("node1",connectedExternalNodes[0]);
output.attr("node2",connectedExternalNodes[1]);
// global forces
if (strcmp(argv[0],"force") == 0 || strcmp(argv[0],"forces") == 0 ||
strcmp(argv[0],"globalForce") == 0 || strcmp(argv[0],"globalForces") == 0) {
output.tag("ResponseType","Px_1");
output.tag("ResponseType","Py_1");
output.tag("ResponseType","Pz_1");
output.tag("ResponseType","Mx_1");
output.tag("ResponseType","My_1");
output.tag("ResponseType","Mz_1");
output.tag("ResponseType","Px_2");
output.tag("ResponseType","Py_2");
output.tag("ResponseType","Pz_2");
output.tag("ResponseType","Mx_2");
output.tag("ResponseType","My_2");
output.tag("ResponseType","Mz_2");
theResponse = new ElementResponse(this, 2, P);
// local forces
} else if (strcmp(argv[0],"localForce") == 0 || strcmp(argv[0],"localForces") == 0) {
output.tag("ResponseType","N_1");
output.tag("ResponseType","Vy_1");
output.tag("ResponseType","Vz_1");
output.tag("ResponseType","T_1");
output.tag("ResponseType","My_1");
output.tag("ResponseType","Mz_1");
output.tag("ResponseType","N_2");
output.tag("ResponseType","Vy_2");
output.tag("ResponseType","Vz_2");
output.tag("ResponseType","T_2");
output.tag("ResponseType","My_2");
output.tag("ResponseType","Mz_2");
theResponse = new ElementResponse(this, 3, P);
// basic forces
} else if (strcmp(argv[0],"basicForce") == 0 || strcmp(argv[0],"basicForces") == 0) {
output.tag("ResponseType","N");
output.tag("ResponseType","Mz_1");
output.tag("ResponseType","Mz_2");
output.tag("ResponseType","My_1");
output.tag("ResponseType","My_2");
output.tag("ResponseType","T");
theResponse = new ElementResponse(this, 4, Vector(6));
} else if (strcmp(argv[0],"deformations") == 0 ||
strcmp(argv[0],"basicDeformations") == 0) {
output.tag("ResponseType","eps");
output.tag("ResponseType","theta11");
output.tag("ResponseType","theta12");
output.tag("ResponseType","theta21");
output.tag("ResponseType","theta22");
output.tag("ResponseType","phi");
theResponse = new ElementResponse(this, 5, Vector(6));
}
output.endTag(); // ElementOutput
return theResponse;
}
int
ElasticBeam3d::getResponse (int responseID, Information &eleInfo)
{
double N, V, M1, M2, T;
double L = theCoordTransf->getInitialLength();
double oneOverL = 1.0/L;
static Vector Res(12);
Res = this->getResistingForce();
switch (responseID) {
case 1: // stiffness
return eleInfo.setMatrix(this->getTangentStiff());
case 2: // global forces
return eleInfo.setVector(Res);
case 3: // local forces
// Axial
N = q(0);
P(6) = N;
P(0) = -N+p0[0];
// Torsion
T = q(5);
P(9) = T;
P(3) = -T;
// Moments about z and shears along y
M1 = q(1);
M2 = q(2);
P(5) = M1;
P(11) = M2;
V = (M1+M2)*oneOverL;
P(1) = V+p0[1];
P(7) = -V+p0[2];
// Moments about y and shears along z
M1 = q(3);
M2 = q(4);
P(4) = M1;
P(10) = M2;
V = (M1+M2)*oneOverL;
P(2) = -V+p0[3];
P(8) = V+p0[4];
return eleInfo.setVector(P);
case 4: // basic forces
return eleInfo.setVector(q);
case 5:
return eleInfo.setVector(theCoordTransf->getBasicTrialDisp());
default:
return -1;
}
}
int
ElasticBeam3d::setParameter(const char **argv, int argc, Parameter ¶m)
{
if (argc < 1)
return -1;
// E of the beam interior
if (strcmp(argv[0],"E") == 0)
return param.addObject(1, this);
// A of the beam interior
if (strcmp(argv[0],"A") == 0)
return param.addObject(2, this);
// Iz of the beam interior
if (strcmp(argv[0],"Iz") == 0)
return param.addObject(3, this);
// Iy of the beam interior
if (strcmp(argv[0],"Iy") == 0)
return param.addObject(4, this);
// G of the beam interior
if (strcmp(argv[0],"G") == 0)
return param.addObject(5, this);
// J of the beam interior
if (strcmp(argv[0],"J") == 0)
return param.addObject(6, this);
return -1;
}
int
ElasticBeam3d::updateParameter (int parameterID, Information &info)
{
switch (parameterID) {
case -1:
return -1;
case 1:
E = info.theDouble;
return 0;
case 2:
A = info.theDouble;
return 0;
case 3:
Iz = info.theDouble;
return 0;
case 4:
Iy = info.theDouble;
return 0;
case 5:
G = info.theDouble;
return 0;
case 6:
Jx = info.theDouble;
return 0;
default:
return -1;
}
}
| 26.281841 | 138 | 0.548945 | [
"vector",
"model",
"transform",
"3d"
] |
3797a75dbbdf6abef6de71580d96a17c6ff1823b | 12,211 | cc | C++ | phone2image_ex/phone_img.cc | WinterW/crawler_cpp | e0c8dba77233005b1ab13731d1cbcce274b70778 | [
"Apache-2.0"
] | null | null | null | phone2image_ex/phone_img.cc | WinterW/crawler_cpp | e0c8dba77233005b1ab13731d1cbcce274b70778 | [
"Apache-2.0"
] | null | null | null | phone2image_ex/phone_img.cc | WinterW/crawler_cpp | e0c8dba77233005b1ab13731d1cbcce274b70778 | [
"Apache-2.0"
] | 2 | 2020-09-12T13:50:38.000Z | 2020-09-16T15:55:14.000Z | /**
* @Copyright 2010 GanJi Inc.
* @file ganji/crawler/phone2image_ex/phone_level.cc
* @namespace ganji::crawler::phone2image
* @version 1.0
* @author miaoxijun
* @author lisizhong
* @author luomeiqing
* @date 2012-11-18
*
* 改动程序后, 请使用tools/cpplint/cpplint.py 检查代码是否符合编码规范!
* 遵循的编码规范请参考: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
* Change Log:
*/
#include "phone2image_ex/phone_img.h"
#include <sys/time.h>
#include <unistd.h>
#include <assert.h>
#include <gdfontg.h>
#include <math.h>
#include <string>
#include <list>
#include <algorithm>
#include "util/log/thread_fast_log.h"
#include "phone2image_ex/img_config.h"
namespace ganji { namespace crawler { namespace phone2image {
using std::list;
using std::string;
using std::vector;
namespace FastLog = ganji::util::log::ThreadFastLog;
using FastLog::kLogFatal;
using FastLog::WriteLog;
int PhoneImg::Init(ImgConfigMgr *p_img_config_mgr) {
p_img_config_mgr_ = p_img_config_mgr;
gdFontCacheSetup();
return 0;
}
int PhoneImg::GetFontFile(int level, const StyleConfig *style_config, string *p_font_file) {
*p_font_file = style_config->GetFontFile();
// int rand_font_level = p_img_config_mgr_->GetRandFontLevel();
// if (level >= rand_font_level)
// *p_font_file = p_img_config_mgr_->GetRandFont();
if (p_font_file->empty())
return -1;
else
return 0;
}
void PhoneImg::GetPhoneSplit(int level,
const StyleConfig *style_config,
const string &phone,
int32_t col,
vector<PhoneItem> *p_phone_list) {
const string &font_file = style_config->GetFontFile();
int rand_font_level = p_img_config_mgr_->GetRandFontLevel();
bool is_rand_font = false;
if (level >= rand_font_level)
is_rand_font = true;
if (col < 1)
col = 1;
int32_t space = phone.size() / col;
if (space < 1)
space = 1;
int32_t index_ = 0;
PhoneItem item;
while (true) {
if (index_ >= static_cast<int32_t>(phone.size()))
break;
if (is_rand_font)
item.font_ = p_img_config_mgr_->GetRandFont();
else
item.font_ = font_file;
int32_t leave_len_ = phone.size() - index_;
if (leave_len_ < space)
space = leave_len_;
item.str_ = string(phone.c_str() + index_, space);
index_ += space;
(*p_phone_list).push_back(item);
}
}
int PhoneImg::DrawText(int level,
const LevelConfig *level_config,
const StyleConfig *style_config,
const string &phone,
int32_t height,
int font_color,
gdImagePtr &im) {
vector<PhoneItem> phones;
GetPhoneSplit(level, style_config, phone, level_config->GetSplitNum(), &phones);
int x_pos = 0;
int brect[8];
unsigned int seed = 0;
for (int i = 0; i < static_cast<int>(phones.size()); i++) {
double angle = 0.0;
if (phones.size() > 300) {
int r1 = random();
seed = r1;
angle = r1 % 50;
angle *= 0.004;
if (r1%2 == 0)
angle *= -1;
}
/// gdImageStringFT(gdImagePtr im, int *brect, int fg, char *fontname, double ptsize, double angle, int x, int y, char *string)
char *err = gdImageStringFT(im,
&brect[0],
font_color,
const_cast<char*>(phones[i].font_.c_str()),
height*0.8,
angle,
x_pos,
height-height*0.1,
const_cast<char*>(phones[i].str_.c_str()));
if (err) {
WriteLog(kLogFatal, "DrawText error:%s", err);
return -1;
}
x_pos += brect[4]-brect[0];
x_pos -= level_config->GetIndent();
}
return 0;
}
int PhoneImg::DrawTextGap(int level,
const LevelConfig *level_config,
const StyleConfig *style_config,
const string &phone,
int32_t height,
int font_color,
gdImagePtr *im,
gdImagePtr *im_new) {
int ptsize = style_config->GetPtsize();
const int start_pos = 3;
int x_pos = start_pos;
int minus_flag = 0;
int phone_len = phone.size();
int gap_level = level_config->GetGap();
int gap_style = style_config->GetGap();
int gap = gap_level + gap_style;
int cluster_ch = level_config->GetClusterCh();
int brect[8];
double angle = 0;
string font_file;
GetFontFile(level, style_config, &font_file);
if(cluster_ch >= 5)
{
int dm = cluster_ch - 2;
cluster_ch = random()%dm + 3;
}
int cur_cluster_ch = 1;
if (phone_len > 13 && style_config->GetLongNum()) {
ptsize = std::max(9, ptsize - (phone_len - 12));
// gap = static_cast<int>(ceilf(static_cast<float>(ptsize) * 4 / 9));
gap = static_cast<int>(static_cast<float>(ptsize) * 4 / 9);
}
if (string::npos == phone.find('-') && phone_len == 11) {
minus_flag = random() % 11;
}
for (int i = 0; i < phone_len; i++) {
string letter = phone.substr(i, 1);
char ch = phone[i];
int shift = 0;
int cur_size = 0;
if (ch == '1') {
cur_size = ptsize + 2;
shift = 1;
} else {
shift = random() % 3 - 1;
cur_size = ptsize + shift;
}
/// 在数字中插入-
if ((minus_flag > 3 && i == 3) ||
(minus_flag > 7 && i == 7)) {
/// gdImageStringFT(gdImagePtr im, int *brect, int fg, char *fontname, double ptsize, double angle, int x, int y, char *string)
x_pos += 2;
char *err = gdImageStringFT(*im,
&brect[0],
font_color,
const_cast<char*>(font_file.c_str()),
ptsize + 2,
0.0,
x_pos,
height*0.9,
const_cast<char *>("-"));
if (err) {
WriteLog(kLogFatal, "DrawText error:%s", err);
return -1;
}
x_pos += brect[2] - brect[0] - gap;
cur_cluster_ch = 1;
}
if(x_pos > 3 && (ch == '1'))
{
x_pos -= 1;
}
//angle = -1 *(0.015 * (random()%11));
char *err = gdImageStringFT(*im,
&brect[0],
font_color,
const_cast<char*>(font_file.c_str()),
ptsize,
angle,
x_pos,
height*0.9+shift,
const_cast<char *>(letter.c_str()));
if (err) {
WriteLog(kLogFatal, "DrawText error:%s", err);
return -1;
}
if (ch != '-') {
if (cur_cluster_ch < cluster_ch) {
x_pos += brect[2] - brect[0] - gap + random()%2;
cur_cluster_ch++;
} else {
x_pos += brect[2] - brect[0];
int denom = static_cast<int>(static_cast<float>(gap)*3/4)+1;
x_pos = x_pos - random() % denom + 1;
cur_cluster_ch = 1;
}
} else {
x_pos += brect[2] - brect[0] - gap;
}
}
/// 把im中的字符部分copy到新的图片中
/// XXX 新的图片长度设定为x_pos+trailing_width,保证末尾的字符完全copy
const int trailing_width = 3;
height = gdImageSY(*im);
*im_new = gdImageCreate(x_pos + start_pos + trailing_width, height);
gdImageCopy(*im_new, *im, 0, 0, 0, 0, x_pos + start_pos + trailing_width, height);
return 0;
}
/// Y\X 0 1 2 3
/// -----------------
/// 0 | 0 | 1 | 2 | 3 |
/// -----------------
/// 1 | 4 | 5 | 6 | 7 |
/// -----------------
/// 4种组合: 区间0<=>6, 区间1<=>7,区间4<=>2,区间6<=>3
void PhoneImg::DrawFirstLine(int32_t width, int32_t height, int color, gdImagePtr *im) {
int delim_x0 = random()%(width/4);
int delim_x1 = random()%(width/4) + width/4;
int delim_x2 = random()%(width/4) + width/2;
int delim_x3 = random()%(width/4) + width*3/4;
int delim_y0 = random()%(height/2);
int delim_y1 = random()%(height/2) + height/2;
int x0 = 0, y0 = 0, x1 = 0, y1 = 0;
int r = random() % 4;
if (r == 0) {
x0 = delim_x0;
x1 = delim_x2;
y0 = delim_y0;
y1 = delim_y1;
} else if (r == 1) {
x0 = delim_x1;
x1 = delim_x3;
y0 = delim_y0;
y1 = delim_y1;
} else if (r == 2) {
x0 = delim_x0;
x1 = delim_x2;
y0 = delim_y1;
y1 = delim_y0;
} else {
x0 = delim_x1;
x1 = delim_x3;
y0 = delim_y1;
y1 = delim_y0;
}
gdImageLine(*im, x0, y0, x1, y1, color);
}
void PhoneImg::DrawLines(int32_t num, const int32_t width, const int32_t height, int color, gdImagePtr *im) {
if (num <= 0)
return;
/// XXX 因为下面随机画线可能不会画在字符上,所以第一条线需保证画在字符数
DrawFirstLine(width, height, color, im);
for (int i = 1; i < num; i++) {
int r0 = random();
int r1 = random();
gdImageLine(*im, r0%width, r0%height, r1%width, r1%height, color);
}
}
/// 获取 对应类别对应级别的 电话号码配置
void PhoneImg::GetImageConfig(const LevelConfig * level,
const StyleConfig * style,
int *p_width,
int *p_height,
RGBColor *p_back_color,
RGBColor *p_font_color) {
*p_width = style->GetWidth();
*p_height = style->GetHeight();
// *p_back_color = level->GetBackColor();
// if (*p_back_color != style->GetBackClolor()) {
*p_back_color = style->GetBackClolor();
// }
// *p_font_color = level->GetFontColor();
// if (*p_font_color != style->GetFontColor()) {
*p_font_color = style->GetFontColor();
// }
}
int PhoneImg::PhoneToImage(int level,
const string &style,
const string &phone,
string *image_str) {
const LevelConfig *level_config = p_img_config_mgr_->GetLevelConf(level);
const StyleConfig *style_config = p_img_config_mgr_->GetStyleConf(style);
int width = 0;
int height = 0;
/// 获取对应的图片配置
GetImageConfig(level_config, style_config, &width, &height, &back_color_, &font_color_);
gdImagePtr im;
im = gdImageCreate(width, height);
if (!im) {
WriteLog(kLogFatal, "gdImageCreate() failed");
return -1;
}
int back_color = gdImageColorAllocate(im, back_color_.red_, back_color_.green_, back_color_.blue_);
int font_color = gdImageColorAllocate(im, font_color_.red_, font_color_.green_, font_color_.blue_);
if (back_color < 0 || font_color < 0) {
gdImageDestroy(im);
WriteLog(kLogFatal, "gdImageColorAllocate() failed");
return -1;
}
gdImagePtr im_new;
if (DrawTextGap(level, level_config, style_config, phone, height, font_color, &im, &im_new) < 0) {
/// XXX 不需要destroy im_new,因为gdImageCopy不会返回错误码
gdImageDestroy(im);
WriteLog(kLogFatal, "DrawTextGap() failed");
return -1;
}
/// XXX 新图片的宽度
int new_width = gdImageSX(im_new)+4;
/// XXX style对应的图片较小,则线数量可以适量减少
int back_num = level_config->GetLineBackNum() + style_config->GetLineBackNum();
int font_num = level_config->GetLineFontNum() + style_config->GetLineFontNum();
if (phone.size() > 13 && style_config->GetLongNum()) {
back_num -= 1;
font_num -= 1;
}
DrawLines(back_num, new_width, height, back_color, &im_new);
DrawLines(font_num, new_width, height, font_color, &im_new);
int image_size = 0;
void *image_data = gdImagePngPtr(im_new, &image_size);
*image_str = string(reinterpret_cast<const char*>(image_data), image_size);
gdFree(image_data);
gdImageDestroy(im_new);
gdImageDestroy(im);
/// DrawText(level, level_config, style_config, phone, height, font_color, im);
/// DrawLines(level_config->GetLineBackNum(), width, height, im, back_color);
/// DrawLines(level_config->GetLineFontNum(), width, height, im, font_color);
/// int image_size =0;
/// void *image_data = gdImagePngPtr(im,&image_size);
/// *image_str = string(reinterpret_cast<const char*>(image_data), image_size);
/// gdFree(image_data);
/// gdImageDestroy(im);
return 0;
}
}}}
| 30.5275 | 133 | 0.562526 | [
"vector"
] |
379c3e29affe04dfeaa189e1d1614d156686a52c | 1,314 | cpp | C++ | online_judges/cf/102465/d/d.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | 2 | 2018-02-20T14:44:57.000Z | 2018-02-20T14:45:03.000Z | online_judges/cf/102465/d/d.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | online_judges/cf/102465/d/d.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
// By Miguel Ortiz https://github.com/miaortizma
typedef long long ll;
typedef pair<ll, ll> pll;
vector<pll> v, lines;
int X, Y, N;
ll d(ll y, pll line) {
ll y0 = line.first, y1 = line.second;
if (y < y0) {
return y0 - y;
} else if (y > y1) {
return y - y1;
} else {
return 0;
}
}
ll f(ll y) {
ll S = X - 1;
for (size_t i = 0; i < lines.size(); ++i) {
S += 2 *(d(y, lines[i]) + lines[i].second - lines[i].first);
}
return S;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
ll x, y;
cin >> X >> Y;
cin >> N;
for (int i = 0; i < N; ++i) {
cin >> x >> y;
pll p{x, y};
v.push_back(p);
}
sort(v.begin(), v.end());
ll last_x = -1;
for (int i = 0; i < N; ++i) {
x = v[i].first, y = v[i].second;
if (x != last_x) {
lines.push_back({y, y});
}
int s = lines.size() - 1;
ll y0 = lines[s].first, y1 = lines[s].second;
lines[s].first = min(y0, y);
lines[s].second = max(y1, y);
last_x = x;
}
ll l = 0, h = Y - 1;
while (l < h) {
ll m = (l + h) >> 1;
ll f0 = f(m), f1 = f(m + 1);
if (f1 > f0) {
h = m;
} else if (f0 > f1) {
l = m + 1;
} else {
l = m;
break;
}
}
cout << min(f(l), f(l - 1));
return 0;
}
| 19.043478 | 64 | 0.464231 | [
"vector"
] |
379ecc08d029071d77b9b86d77aad7c3ea10325e | 146,559 | hpp | C++ | third_party/boost/sandbox/boost/property_tree/detail/pugxml.hpp | gbucknell/fsc-sdk | 11b7cda4eea35ec53effbe37382f4b28020cd59d | [
"MIT"
] | null | null | null | third_party/boost/sandbox/boost/property_tree/detail/pugxml.hpp | gbucknell/fsc-sdk | 11b7cda4eea35ec53effbe37382f4b28020cd59d | [
"MIT"
] | null | null | null | third_party/boost/sandbox/boost/property_tree/detail/pugxml.hpp | gbucknell/fsc-sdk | 11b7cda4eea35ec53effbe37382f4b28020cd59d | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
//
// Pug XML Parser - Version 1.0002
// --------------------------------------------------------
// Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
// Released into the Public Domain. Use at your own risk.
// See pugxml.xml for further information, history, etc.
// Contributions by Neville Franks (readonly@getsoft.com).
//
// Modified to suit boost::property_tree library by Marcin Kalicinski
#ifndef BOOST_PROPERTY_TREE_DETAIL_PUGXML_HPP_INCLUDED
#define BOOST_PROPERTY_TREE_DETAIL_PUGXML_HPP_INCLUDED
#ifndef TCHAR
#define UNDEF_TCHAR_AND_REST
#define TCHAR char
#define _tcslen strlen
#define _istalnum isalnum
#define _tcsncpy strncpy
#define _tcscpy strcpy
#define _tcscmp strcmp
#define _tcstol strtol
#define _tcstod strtod
#define _tcstok strtok
#define _stprintf sprintf
#define _T(s) s
#endif
//#define PUGOPT_MEMFIL //Uncomment to enable memory-mapped file parsing support.
//#define PUGOPT_NONSEG //Uncomment to enable non-destructive (non-segmenting) parsing support.
#ifdef PUGOPT_MEMFIL
# ifndef PUGOPT_NONSEG
# define PUGOPT_NONSEG //PUGOPT_MEMFIL implies PUGOPT_NONSEG.
# endif
#endif
#include <iostream>
#include <ostream>
#include <string>
#if defined(PUGOPT_MEMFIL) | defined(PUGOPT_NONSEG)
# include <assert.h>
#endif
#ifndef HIWORD
# define UNDEF_LOHIWORD
# define HIWORD(X) ((unsigned short)((unsigned long)(X)>>16))
# define LOWORD(X) ((unsigned short)((unsigned long)(X)&0xFFFF))
#endif
//<summary>
// Library variant ID. The ID 0x58475550 is owned by Kristen Wegner. You *MUST*
// provide your own unique ID if you modify or fork the code in this library to
// your own purposes. If you change this then *you* are now the maintainer, not me.
// Change also in the package section of pugxml.xml, and append yourself to the
// authors section.
//</summary>
#define PUGAPI_INTERNAL_VARIANT 0xdeadbeef
//<summary>Major version. Increment for each major release. Only change if you own the variant.</summary>
#define PUGAPI_INTERNAL_VERSION_MAJOR 1
//<summary>Minor version. Increment for each minor release. Only change if you own the variant ID.</summary>
#define PUGAPI_INTERNAL_VERSION_MINOR 2
#define PUGAPI_INTERNAL_VERSION ((PUGAPI_INTERNAL_VERSION_MINOR&0xFFFF)|PUGAPI_INTERNAL_VERSION_MAJOR<<16)
#define PUGDEF_ATTR_NAME_SIZE 128
#define PUGDEF_ATTR_VALU_SIZE 256
#define PUGDEF_ELEM_NAME_SIZE 256
//<summary>The PugXML Parser namespace.</summary>
namespace boost { namespace property_tree { namespace xml_parser { namespace pug
{
//<summary>The Library Variant ID. See PUGAPI_INTERNAL_VARIANT for an explanation.</summary>
//<returns>The current Library Variant ID.</returns>
inline static unsigned long lib_variant(){ return PUGAPI_INTERNAL_VARIANT; }
//<summary>The library version. High word is major version. Low word is minor version.</summary>
//<returns>The current Library Version.</returns>
inline static unsigned long lib_version(){ return PUGAPI_INTERNAL_VERSION; }
//<summary>A 'name=value' XML attribute structure.</summary>
typedef struct t_xml_attribute_struct
{
TCHAR* name; //Pointer to attribute name.
bool name_insitu; //True if 'name' is a segment of the original parse string.
#ifdef PUGOPT_NONSEG
unsigned int name_size; //Length of element name.
#endif
TCHAR* value; //Pointer to attribute value.
bool value_insitu; //True if 'value' is a segment of the original parse string.
#ifdef PUGOPT_NONSEG
unsigned int value_size; //Length of element name.
#endif
}
xml_attribute_struct;
//<summary>Tree node classification.</summary>
//<remarks>See 'xml_node_struct::type'.</remarks>
typedef enum t_xml_node_type
{
node_null, //An undifferentiated entity.
node_document, //A document tree's absolute root.
node_element, //E.g. '<...>'
node_pcdata, //E.g. '>...<'
node_cdata, //E.g. '<![CDATA[...]]>'
node_comment, //E.g. '<!--...-->'
node_pi, //E.g. '<?...?>'
node_include, //E.g. '<![INCLUDE[...]]>'
node_doctype, //E.g. '<!DOCTYPE ...>'.
node_dtd_entity, //E.g. '<!ENTITY ...>'.
node_dtd_attlist, //E.g. '<!ATTLIST ...>'.
node_dtd_element, //E.g. '<!ELEMENT ...>'.
node_dtd_notation //E.g. '<!NOTATION ...>'.
}
xml_node_type;
static const unsigned long parse_grow = 4; //Default child element & attribute space growth increment.
//Parser Options
static const unsigned long parse_minimal = 0x00000000; //Unset the following flags.
static const unsigned long parse_pi = 0x00000002; //Parse '<?...?>'
static const unsigned long parse_doctype = 0x00000004; //Parse '<!DOCTYPE ...>' section, setting '[...]' as data member.
static const unsigned long parse_comments = 0x00000008; //Parse <!--...-->'
static const unsigned long parse_cdata = 0x00000010; //Parse '<![CDATA[...]]>', and/or '<![INCLUDE[...]]>'
static const unsigned long parse_escapes = 0x00000020; //Not implemented.
static const unsigned long parse_trim_pcdata = 0x00000040; //Trim '>...<'
static const unsigned long parse_trim_attribute = 0x00000080; //Trim 'foo="..."'.
static const unsigned long parse_trim_cdata = 0x00000100; //Trim '<![CDATA[...]]>', and/or '<![INCLUDE[...]]>'
static const unsigned long parse_trim_entity = 0x00000200; //Trim '<!ENTITY name ...>', etc.
static const unsigned long parse_trim_doctype = 0x00000400; //Trim '<!DOCTYPE [...]>'
static const unsigned long parse_trim_comment = 0x00000800; //Trim <!--...-->'
static const unsigned long parse_wnorm = 0x00001000; //Normalize all entities that are flagged to be trimmed.
static const unsigned long parse_dtd = 0x00002000; //If parse_doctype set, then parse whatever is in data member ('[...]').
static const unsigned long parse_dtd_only = 0x00004000; //If parse_doctype|parse_dtd set, then parse only '<!DOCTYPE [*]>'
static const unsigned long parse_default = 0x0000FFFF;
static const unsigned long parse_noset = 0x80000000;
//<summary>An XML document tree node.</summary>
typedef struct t_xml_node_struct
{
t_xml_node_struct* parent; //Pointer to parent
TCHAR* name; //Pointer to element name.
#ifdef PUGOPT_NONSEG
unsigned int name_size; //Length of element name. Since 19 Jan 2003 NF.
#endif
bool name_insitu; //True if 'name' is a segment of the original parse string.
xml_node_type type; //Node type; see xml_node_type.
unsigned int attributes; //Count attributes.
unsigned int attribute_space; //Available pointer space in 'attribute'.
xml_attribute_struct** attribute; //Array of pointers to attributes; see xml_attribute_struct.
unsigned int children; //Count children in member 'child'.
unsigned int child_space; //Available pointer space in 'child'.
t_xml_node_struct** child; //Array of pointers to children.
TCHAR* value; //Pointer to any associated string data.
#ifdef PUGOPT_NONSEG
unsigned int value_size; //Length of element data. Since 19 Jan 2003 NF.
#endif
bool value_insitu; //True if 'data' is a segment of the original parse string.
}
xml_node_struct;
//<summary>Concatenate 'rhs' to 'lhs', growing 'rhs' if neccessary.</summary>
//<param name="lhs">Pointer to pointer to receiving string. Note: If '*lhs' is not null, it must have been dynamically allocated using 'malloc'.</param>
//<param name="rhs">Source.</param>
//<returns>Success if 'realloc' was successful.</returns>
//<remarks>'rhs' is resized and 'rhs' is concatenated to it.</remarks>
inline static bool strcatgrow(TCHAR** lhs,const TCHAR* rhs)
{
if(!*lhs) //Null, so first allocate.
{
*lhs = (TCHAR*) malloc(1UL*sizeof(TCHAR));
**lhs = 0; //Zero-terminate.
}
size_t ulhs = _tcslen(*lhs);
size_t urhs = _tcslen(rhs);
TCHAR* temp = (TCHAR*) realloc(*lhs,(ulhs+urhs+1UL)*sizeof(TCHAR));
if(!temp) return false; //Realloc failed.
memcpy(temp+ulhs,rhs,urhs*sizeof(TCHAR)); //Concatenate.
temp[ulhs+urhs] = 0; //Terminate it.
*lhs = temp;
return true;
}
inline static bool chartype_symbol(TCHAR c) //Character is alphanumeric, -or- '_', -or- ':', -or- '-', -or- '.'.
{ return (_istalnum(c)||c==_T('_')||c==_T(':')||c==_T('-')||c==_T('.')); }
inline static bool chartype_space(TCHAR c) //Character is greater than 0 or character is less than exclamation.
{ return (c>0 && c<_T('!')); }
inline static bool chartype_enter(TCHAR c) //Character is '<'.
{ return (c==_T('<')); }
inline static bool chartype_leave(TCHAR c) //Character is '>'.
{ return (c==_T('>')); }
inline static bool chartype_close(TCHAR c) //Character is '/'.
{ return (c==_T('/')); }
inline static bool chartype_equals(TCHAR c) //Character is '='.
{ return (c==_T('=')); }
inline static bool chartype_special(TCHAR c) //Character is '!'.
{ return (c==_T('!')); }
inline static bool chartype_pi(TCHAR c) //Character is '?'.
{ return (c==_T('?')); }
inline static bool chartype_dash(TCHAR c) //Character is '-'.
{ return (c==_T('-')); }
inline static bool chartype_quote(TCHAR c) //Character is "‘" -or- ‘"‘.
{ return (c==_T('"')||c==_T('\'')); }
inline static bool chartype_lbracket(TCHAR c) //Character is '['.
{ return (c==_T('[')); }
inline static bool chartype_rbracket(TCHAR c) //Character is ']'.
{ return (c==_T(']')); }
#ifdef PUGOPT_NONSEG
//<summary>Concatenate 'rhs' to 'lhs', growing 'lhs' if neccessary.</summary>
//<param name="lhs">Pointer to pointer to receiving string. Note: If '*lhs' is not null, it must have been dynamically allocated using 'malloc'.</param>
//<param name="rhs">Source.</param>
//<param name="lsize">Specifies the length of *lhs in bytes and returns its new length.</param>
//<param name="rsize">Specifies the length of *rhs in bytes.</param>
//<returns>Success if 'realloc' was successful.</returns>
//<remarks>'lhs' is resized and 'rhs' is concatenated to it.</remarks>
inline static bool strcatgrown_impl(TCHAR** lhs,const TCHAR* rhs,unsigned int& lsize,unsigned int rsize)
{
if(!*lhs) //Null, allocate and copy.
{
*lhs = (TCHAR*) malloc(rsize+sizeof(TCHAR));
if(!*lhs)
{
lsize = 0;
return false; //Allocate failed.
}
memcpy(*lhs,rhs,rsize); //Concatenate.
*(*lhs + rsize) = 0; //Terminate it.
lsize = rsize;
}
else //Reallocate. NF I don't think this is right for MBCS, nor is code in 'StrCatGrow()'.
{
TCHAR* temp = (TCHAR*) realloc(*lhs,lsize + rsize + sizeof(TCHAR));
if(!temp) return false; //Realloc failed.
memcpy(temp+lsize,rhs,rsize); //Concatenate.
lsize += rsize; //Set new length.
temp[lsize] = 0; //Terminate it.
*lhs = temp;
}
return true;
}
//<summary>Concatenate 'rhs' to 'lhs', growing 'lhs' if neccessary.</summary>
//<param name="lhs">Pointer to pointer to receiving string. Note: If '*lhs' is not null, it must have been dynamically allocated using 'malloc'.</param>
//<param name="rhs">Source.</param>
//<param name="lsize">Specifies the length of *lhs in bytes and returns its new length.</param>
//<returns>Success if 'realloc' was successful.</returns>
//<remarks>'lhs' is resized and 'rhs' is concatenated to it.</remarks>
inline static bool strcatgrown(TCHAR** lhs,const TCHAR* rhs,unsigned int& lsize)
{
const unsigned int rsize = _tcslen(rhs) * sizeof(TCHAR);
return pug::strcatgrown_impl(lhs,rhs,lsize,rsize);
}
//<summary>Trim leading and trailing whitespace.</summary>
//<param name="s">Pointer to pointer to string.</param>
//<param name="len">Specifies the length of *s in bytes and returns its new length.</param>
//<returns>Success.</returns>
//<remarks>*s is modified to point to the first non-white character in the string.</remarks>
inline static bool strwtrim(TCHAR** s,unsigned int& len)
{
if(!s || !*s) return false;
TCHAR* pse = *s + len;
while(*s < pse && pug::chartype_space(**s)) //Find first non-white character.
++*s; //As long as we hit whitespace, increment the string pointer.
for(; *s < --pse;) //As long as we hit whitespace, decrement.
{
if(!pug::chartype_space(*pse))
{
len = pse + 1 - *s;
break;
}
}
return true;
}
#else
//<summary>Trim leading and trailing whitespace.</summary>
//<param name="s">Pointer to pointer to string.</param>
//<returns>Success.</returns>
inline static bool strwtrim(TCHAR** s)
{
if(!s || !*s) return false;
while(**s > 0 && **s < _T('!')) ++*s; //As long as we hit whitespace, increment the string pointer.
const TCHAR* temp = *s;
while(0 != *temp++); //Find the terminating null.
long i, n = (long)(temp-*s-1);
--n; //Start from the last string TCHAR.
for(i=n; (i > -1) && (*s)[i] > 0 && (*s)[i] < _T('!'); --i); //As long as we hit whitespace, decrement.
if(i<n) (*s)[i+1] = 0; //Zero-terminate.
return true;
}
//<summary>
// In situ trim leading and trailing whitespace, then convert all consecutive
// whitespace to a single space TCHAR.
//</summary>
//<param name="s">Pointer to pointer to string.</param>
//<returns>Success.</returns>
inline static bool strwnorm(TCHAR** s)
{
if(!s || !*s) return false; //No string to normalize.
while(**s > 0 && **s < _T('!')) ++(*s); //As long as we hit whitespace, increment the string pointer.
const TCHAR* temp = *s;
while(0 != *temp++); //Find the terminating null.
long n = (long)(temp-*s-1);
TCHAR* norm = (TCHAR*)malloc(sizeof(TCHAR)*(n+1)); //Allocate a temporary normalization buffer.
if(!norm) return false; //Allocation failed.
memset(norm,0,sizeof(TCHAR)*(n+1)); //Zero it.
long j = 1;
norm[0] = (*s)[0];
long i;
for(i=1; i<n; ++i) //For each character, starting at offset 1.
{
if((*s)[i] < _T('!')) //Whitespace-like.
{
if((*s)[i-1] >= _T('!')) //Previous was not whitespace-like.
{
norm[j] = _T(' '); //Convert to a space TCHAR.
++j; //Normalization buffer grew by one TCHAR.
}
}
else { norm[j] = (*s)[i]; ++j; } //Not whitespace, so just copy over.
}
if(j < n) //Normalization buffer is actually different that input.
{
_tcsncpy(*s,norm,j); //So, copy it back to input.
(*s)[j] = 0; //Zero-terminate.
}
free(norm); //Don't need this anymore.
--n; //Start from the last string TCHAR.
for(i=n; (i > -1) && (*s)[i] > 0 && (*s)[i] < _T('!'); --i); //Find the first non-whitespace from the end.
if(i<n) (*s)[i+1] = 0; //Truncate it.
return true;
}
#endif
//<summary>Set structure string member to given value.</summary>
//<param name="dest">Pointer to pointer to destination.</param>
//<param name="src">Source.</param>
//<param name="insitu">Pointer to boolean in-situ string flag.</param>
//<returns>True if member was set to the new value.</returns>
//<remarks>
// If 'src' is larger than 'dest' then 'dest' is resized, in which case
// it is probably no longer in-situ,and 'in_situ' is set to false. If
// 'dest' is already no longer in-situ, and 'src' is too small then the
// existing memory pointed to is freed. If 'dest' is larger than or equal
// to 'dest' then it is merely copied with no resize.
//</remarks>
inline static bool strcpyinsitu
(
TCHAR** dest,
const TCHAR* src,
bool* insitu
#ifdef PUGOPT_NONSEG
,
unsigned int& destlen
#endif
)
{
if(!dest || !src || !insitu) return false; //Bad argument(s), so fail.
#ifndef PUGOPT_NONSEG //Always use heap for our r/o string.
size_t l = (*dest) ? _tcslen(*dest) : 0; //How long is destination?
if(l >= _tcslen(src)) //Destination is large enough, so just copy.
{
_tcscpy(*dest,src); //Copy.
return true; //Success.
}
else //Destination is too small.
#endif
{
if(*dest && !*insitu) free(*dest); //If destination is not in-situ, then free it.
*dest = NULL; //Mark destination as NULL, forcing 'StrCatGrow' to 'malloc.
#ifdef PUGOPT_NONSEG
if(strcatgrown(dest,src,destlen)) //Allocate & copy source to destination
#else
if(strcatgrow(dest,src)) //Allocate & copy source to destination
#endif
{
*insitu = false; //Mark as no longer being in-situ, so we can free it later.
return true; //Success.
}
}
return false; //Failure.
}
//<summary>Character set pattern match.</summary>
//<param name="lhs">String or expression for left-hand side of comparison.</param>
//<param name="rhs">String for right-hand side of comparison.</param>
//<remarks>Used by 'strcmpwild'.</remarks>
inline int strcmpwild_cset(const TCHAR** src,const TCHAR** dst)
{
int find = 0;
int excl = 0;
int star = 1;
if(**src == _T('!'))
{
excl = 1;
++(*src);
}
while(**src != _T(']') || star == 1)
{
if(find == 0)
{
if(**src == _T('-') && *(*src-1) < *(*src+1) && *(*src+1) != _T(']') && star == 0)
{
if(**dst >= *(*src-1) && **dst <= *(*src+1))
{
find = 1;
++(*src);
}
}
else if(**src == **dst) find = 1;
}
++(*src);
star = 0;
}
if(excl == 1) find = (1 - find);
if(find == 1) ++(*dst);
return find;
}
inline int strcmpwild_impl(const TCHAR* src,const TCHAR* dst); //Forward declaration.
//<summary>Wildcard pattern match.</summary>
//<param name="lhs">String or expression for left-hand side of comparison.</param>
//<param name="rhs">String for right-hand side of comparison.</param>
//<remarks>Used by 'strcmpwild'.</remarks>
inline int strcmpwild_astr(const TCHAR** src,const TCHAR** dst)
{
int find = 1;
++(*src);
while((**dst != 0 && **src == _T('?')) || **src == _T('*'))
{
if(**src == _T('?')) ++(*dst);
++(*src);
}
while(**src == _T('*')) ++(*src);
if(**dst == 0 && **src != 0) return 0;
if(**dst == 0 && **src == 0) return 1;
else
{
if(strcmpwild_impl(*src,*dst) == 0)
{
do
{
++(*dst);
while(**src != **dst && **src != _T('[') && **dst != 0)
++(*dst);
}
while((**dst != 0) ? strcmpwild_impl(*src,*dst) == 0 : 0 != (find=0));
}
if(**dst == 0 && **src == 0) find = 1;
return find;
}
}
//<summary>Compare two strings, with globbing, and character sets.</summary>
//<param name="lhs">String or expression for left-hand side of comparison.</param>
//<param name="rhs">String for right-hand side of comparison.</param>
//<remarks>Used by 'strcmpwild'.</remarks>
inline int strcmpwild_impl(const TCHAR* src,const TCHAR* dst)
{
int find = 1;
for(; *src != 0 && find == 1 && *dst != 0; ++src)
{
switch(*src)
{
case _T('?'): ++dst; break;
case _T('['): ++src; find = strcmpwild_cset(&src,&dst); break;
case _T('*'): find = strcmpwild_astr(&src,&dst); --src; break;
default : find = (int) (*src == *dst); ++dst;
}
}
while(*src == _T('*') && find == 1) ++src;
return (int) (find == 1 && *dst == 0 && *src == 0);
}
//<summary>Compare two strings, with globbing, and character sets.</summary>
//<param name="lhs">String or expression for left-hand side of comparison.</param>
//<param name="rhs">String for right-hand side of comparison.</param>
//<returns>
// Returns 1 if src does not match dst, or -1 if either src or dst are null,
// or 0 if src matches dst.
//</returns>
//<remarks>
// Simple regular expressions are permitted in 'src': The character '*' matches
// zero or more characters up to the next pattern, or the end of the string. The
// '?' character matches any single character. Character sets and negation are
// also permitted, for example, '[abcd]', '[a-zA-Z]', etc.
//</remarks>
inline int strcmpwild(const TCHAR* src,const TCHAR* dst)
{
if(!src || !dst) return -1;
return (strcmpwild_impl(src,dst)==1)?0:1;
}
//<summary>Allocate & init an xml_attribute_struct structure.</summary>
//<returns>Pointer to new xml_attribute_struct structure.</returns>
inline static xml_attribute_struct* new_attribute(void)
{
xml_attribute_struct* p = (xml_attribute_struct*)malloc(sizeof(xml_attribute_struct)); //Allocate one attribute.
if(p) //If allocation succeeded.
{
p->name = p->value = 0; //No name or value.
#ifdef PUGOPT_NONSEG
p->name_size = p->value_size = 0; //Lengths of zero.
#endif
p->name_insitu = p->value_insitu = true; //Default to being in-situ of the parse string.
}
return p;
}
//<summary>Allocate & init an xml_node_struct structure.</summary>
//<param name="type">Desired node type.</param>
//<returns>Pointer to new xml_node_struct structure.</returns>
inline static xml_node_struct* new_node(xml_node_type type = node_element)
{
xml_node_struct* p = (xml_node_struct*)malloc(sizeof(xml_node_struct)); //Allocate one node.
if(p) //If allocation succeeded.
{
p->name = p->value = 0; //No name or data.
#ifdef PUGOPT_NONSEG
p->name_size = p->value_size = 0;
#endif
p->type = type; //Set the desired type.
p->attributes = p->children = 0; //No attributes or children.
p->name_insitu = p->value_insitu = true; //Default to being in-situ of the parse string.
if
(
type != node_document && //None of these will have attributes.
type != node_pcdata &&
type != node_cdata &&
type != node_include &&
type != node_comment
)
p->attribute = (xml_attribute_struct**)malloc(sizeof(xml_attribute_struct*)); //Allocate one attribute.
else p->attribute = NULL;
p->attribute_space = (p->attribute) ? 1 : 0;
if
(
type == node_element || //Only these will have children.
type == node_doctype ||
type == node_document
)
p->child = (xml_node_struct**)malloc(sizeof(xml_node_struct*)); //Allocate one child.
else p->child = NULL;
p->child_space = (p->child) ? 1 : 0;
}
return p;
}
//<summary>Allocate & append a new xml_node_struct onto the given parent.</summary>
//<param name="parent">Pointer to parent node.</param>
//<param name="grow">Pointer space growth increment.</param>
//<param name="type">Desired node type.</param>
//<returns>Pointer to new node.</returns>
//<remarks>Child pointer space of 'node' may be reallocated.</remarks>
inline static xml_node_struct* append_node(xml_node_struct* parent,long grow,xml_node_type type = node_element)
{
if(!parent) return NULL; //Must have a parent.
if(parent->children == parent->child_space) //Out of pointer space.
{
xml_node_struct** t = (xml_node_struct**)realloc(parent->child,sizeof(xml_node_struct*)*(parent->child_space+grow)); //Grow pointer space.
if(t) //Reallocation succeeded.
{
parent->child = t;
parent->child_space += grow; //Update the available space.
}
}
xml_node_struct* child = new_node(type); //Allocate a new child.
child->parent = parent; //Set it's parent pointer.
parent->child[parent->children] = child; //Set the parent's child pointer.
parent->children++; //One more child.
return child;
}
//<summary>Allocate & append a new attribute to the given xml_node_struct.</summary>
//<param name="node">Pointer to parent node.</param>
//<param name="grow">Pointer space growth increment.</param>
//<returns>Pointer to appended xml_attribute_struct.</returns>
//<remarks>Attribute pointer space of 'node' may be reallocated.</remarks>
inline static xml_attribute_struct* append_attribute(xml_node_struct* node,long grow)
{
if(!node) return NULL;
xml_attribute_struct* a = new_attribute();
if(!a) return NULL;
if(node->attributes == node->attribute_space) //Out of space, so grow.
{
xml_attribute_struct** t = (xml_attribute_struct**)realloc(node->attribute,sizeof(xml_node_struct*)*(node->attribute_space+grow));
if(t)
{
node->attribute = t;
node->attribute_space += grow;
}
}
node->attribute[node->attributes] = a;
node->attributes++;
return a;
}
//<summary>Non-recursively free a tree.</summary>
//<param name="root">
// Pointer to the root of the tree. Note: 'root' must have been dynamically
// allocated using 'malloc' or 'realloc', as 'free_node' tries to also free
// the structure pointed to by 'root'.
//</param>
//<remarks>'root' no longer points to a valid structure.</remarks>
inline static void free_node(xml_node_struct* node)
{
if(!node) return;
register xml_node_struct* cursor = node;
//Free all children of children.
do
{
LOC_STEP_INTO:
for(; cursor->children>0; --cursor->children) //Free each child in turn; 'children' keeps count while we jump around.
{
register xml_node_struct* t = cursor->child[cursor->children-1]; //Take a pointer to the child.
if(t && t->children) //If the child has children.
{
cursor = t; //Step in.
goto LOC_STEP_INTO; //Step into this node.
}
else if(t)
{
if(t->attributes) //Child has attributes.
{
register unsigned int n = t->attributes; //Free each attribute.
for(register unsigned int i=0; i<n; ++i)
{
if(t->attribute[i]->name && !t->attribute[i]->name_insitu)
free(t->attribute[i]->name);
if(t->attribute[i]->value && !t->attribute[i]->value_insitu)
free(t->attribute[i]->value);
free(t->attribute[i]);
}
}
if(t->attribute) free(t->attribute); //Free attribute pointer space.
if(t->child) free(t->child); //Free child pointer space.
if(t->name && !t->name_insitu) free(t->name);
if(t->value && !t->value_insitu) free(t->value);
free(t); //Free the child node.
}
}
cursor = cursor->parent; //Step out.
}
while(cursor->children); //While there are children.
//Finally, free the root's children & the root itself.
if(cursor->attributes)
{
register unsigned int n = cursor->attributes;
for(register unsigned int i=0; i<n; ++i)
{
if(cursor->attribute[i]->name && !cursor->attribute[i]->name_insitu)
free(cursor->attribute[i]->name);
if(cursor->attribute[i]->value && !cursor->attribute[i]->value_insitu)
free(cursor->attribute[i]->value);
free(cursor->attribute[i]);
}
}
if(cursor->attribute) free(cursor->attribute); //Free attribute pointer space.
if(cursor->child) free(cursor->child); //Free child pointer space.
if(cursor->name && !cursor->name_insitu) free(cursor->name); //Free name & data.
if(cursor->value && !cursor->value_insitu) free(cursor->value);
free(cursor); //Free the root itself.
}
//<summary>Recursively free a tree.</summary>
//<param name="root">Pointer to the root of the tree.</param>
//<remarks>Not used.</remarks>
inline static void free_node_recursive(xml_node_struct* root)
{
if(root)
{
unsigned int n = root->attributes;
register unsigned int i;
for(i=0; i<n; i++)
{
if(root->attribute[i]->name && !root->attribute[i]->name_insitu)
free(root->attribute[i]->name);
if(root->attribute[i]->value && !root->attribute[i]->value_insitu)
free(root->attribute[i]->value);
free(root->attribute[i]);
}
free(root->attribute);
n = root->children;
for(i=0; i<n; i++)
free_node_recursive(root->child[i]);
free(root->child);
if(root->name && !root->name_insitu) free(root->name);
if(root->value && !root->value_insitu) free(root->value);
free(root);
}
}
//<summary>Parser utilities.</summary>
#define SKIPWS() { while(chartype_space(*s)) ++s; if(*s==0) return s; }
#define OPTSET(OPT) ( optmsk & OPT )
#define PUSHNODE(TYPE) { cursor = append_node(cursor,growby,TYPE); }
#define POPNODE() { cursor = cursor->parent; }
#define SCANFOR(X) { while(*s!=0 && !(X)) ++s; if(*s==0) return s; }
#define SCANWHILE(X) { while((X)) ++s; if(*s==0) return s; }
#ifndef PUGOPT_NONSEG
# define ENDSEG() { ch = *s; *s = 0; ++s; if(*s==0) return s; }
#else
# define ENDSEG() { ch = *s; ++s; if(*s==0) return s; }
# define SETLEN() ( cursor->value_size = s - cursor->value )
# define ENDSEGDAT() { ch = *s; SETLEN(); ++s; if(*s==0) return s; }
# define ENDSEGNAM(S) { ch = *s; S->name_size = s - S->name; ++s; if(*s==0) return s; }
# define ENDSEGATT(S) { ch = *s; S->value_size = s - S->value; ++s; if(*s==0) return s; }
#endif
//<summary>Static single-pass in-situ parse the given xml string.</summary>
//<param name="s">Pointer to XML-formatted string.</param>
//<param name="root">Pointer to root.</param>
//<param name="grow">Pointer space growth increment.</param>
//<param name="optmsk">Parse options mask.</param>
//<returns>Last string position or null.</returns>
//<remarks>
// Input string is zero-segmented if 'PUGOPT_NONSEG' is not defined. Memory
// may have been allocated to 'root' (free with 'free_node').
//</remarks>
static TCHAR* parse(register TCHAR* s,xml_node_struct* xmldoc,long growby,unsigned long optmsk = parse_default)
{
if(!s || !xmldoc) return s;
TCHAR ch = 0; //Current char, in cases where we must null-terminate before we test.
xml_node_struct* cursor = xmldoc; //Tree node cursor.
TCHAR* mark = s; //Marked string position for temporary look-ahead.
while(*s!=0)
{
LOC_SEARCH: //Obliviously search for next element.
SCANFOR(chartype_enter(*s)); //Find the next '<'.
if(chartype_enter(*s))
{
++s;
LOC_CLASSIFY: //What kind of element?
if(chartype_pi(*s)) //'<?...'
{
++s;
if(chartype_symbol(*s) && OPTSET(parse_pi))
{
mark = s;
SCANFOR(chartype_pi(*s)); //Look for terminating '?'.
#ifndef PUGOPT_NONSEG
if(chartype_pi(*s)) *s = _T('/'); //Same semantics as for '<.../>', so fudge it.
#endif
s = mark;
PUSHNODE(node_pi); //Append a new node on the tree.
goto LOC_ELEMENT; //Go read the element name.
}
else //Bad PI or parse_pi not set.
{
SCANFOR(chartype_leave(*s)); //Look for '>'.
++s;
mark = 0;
continue;
}
}
else if(chartype_special(*s)) //'<!...'
{
++s;
if(chartype_dash(*s)) //'<!-...'
{
++s;
if(OPTSET(parse_comments) && chartype_dash(*s)) //'<!--...'
{
++s;
PUSHNODE(node_comment); //Append a new node on the tree.
cursor->value = s; //Save the offset.
while(*s!=0 && *(s+1) && *(s+2) && !((chartype_dash(*s) && chartype_dash(*(s+1))) && chartype_leave(*(s+2)))) ++s; //Scan for terminating '-->'.
if(*s==0) return s;
#ifdef PUGOPT_NONSEG
SETLEN(); //NF 19 Jan 2003.
#else
*s = 0; //Zero-terminate this segment at the first terminating '-'.
#endif
if(OPTSET(parse_trim_comment)) //Trim whitespace.
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value,cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
s += 2; //Step over the '\0-'.
POPNODE(); //Pop since this is a standalone.
goto LOC_LEAVE; //Look for any following PCDATA.
}
else
{
while(*s!=0 && *(s+1)!=0 && *(s+2)!=0 && !((chartype_dash(*s) && chartype_dash(*(s+1))) && chartype_leave(*(s+2)))) ++s; //Scan for terminating '-->'.
if(*s==0) return s;
s += 2;
goto LOC_LEAVE; //Look for any following PCDATA.
}
}
else if(chartype_lbracket(*s)) //'<![...'
{
++s;
if(*s==_T('I')) //'<![I...'
{
++s;
if(*s==_T('N')) //'<![IN...'
{
++s;
if(*s==_T('C')) //'<![INC...'
{
++s;
if(*s==_T('L')) //'<![INCL...'
{
++s;
if(*s==_T('U')) //'<![INCLU...'
{
++s;
if(*s==_T('D')) //'<![INCLUD...'
{
++s;
if(*s==_T('E')) //'<![INCLUDE...'
{
++s;
if(chartype_lbracket(*s)) //'<![INCLUDE[...'
{
++s;
if(OPTSET(node_cdata))
{
PUSHNODE(node_include); //Append a new node on the tree.
cursor->value = s; //Save the offset.
while(!(chartype_rbracket(*s) && chartype_rbracket(*(s+1)) && chartype_leave(*(s+2)))) ++s; //Scan for terminating ']]>'.
if(chartype_rbracket(*s))
{
#ifdef PUGOPT_NONSEG
SETLEN(); //NF 19 Jan 2003.
#else
*s = 0; //Zero-terminate this segment.
#endif
++s;
if(OPTSET(parse_trim_cdata)) //Trim whitespace.
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value, cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
}
POPNODE(); //Pop since this is a standalone.
}
else //Flagged for discard, but we still have to scan for the terminator.
{
while(*s!=0 && *(s+1)!=0 && *(s+2)!=0 && !(chartype_rbracket(*s) && chartype_rbracket(*(s+1)) && chartype_leave(*(s+2)))) ++s; //Scan for terminating ']]>'.
++s;
}
++s; //Step over the last ']'.
goto LOC_LEAVE; //Look for any following PCDATA.
}
}
}
}
}
}
}
}
else if(*s==_T('C')) //'<![C...'
{
++s;
if(*s==_T('D')) //'<![CD...'
{
++s;
if(*s==_T('A')) //'<![CDA...'
{
++s;
if(*s==_T('T')) //'<![CDAT...'
{
++s;
if(*s==_T('A')) //'<![CDATA...'
{
++s;
if(chartype_lbracket(*s)) //'<![CDATA[...'
{
++s;
if(OPTSET(parse_cdata))
{
PUSHNODE(node_cdata); //Append a new node on the tree.
cursor->value = s; //Save the offset.
while(*s!=0 && *(s+1)!=0 && *(s+2)!=0 && !(chartype_rbracket(*s) && chartype_rbracket(*(s+1)) && chartype_leave(*(s+2)))) ++s; //Scan for terminating ']]>'.
if(*(s+2)==0) return s; //Very badly formed.
if(chartype_rbracket(*s))
{
#ifdef PUGOPT_NONSEG
SETLEN(); //NF 19 Jan 2003.
#else
*s = 0; //Zero-terminate this segment.
#endif
++s;
if(OPTSET(parse_trim_cdata)) //Trim whitespace.
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value,cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
}
POPNODE(); //Pop since this is a standalone.
}
else //Flagged for discard, but we still have to scan for the terminator.
{
while(*s!=0 && *(s+1)!=0 && *(s+2)!=0 && !(chartype_rbracket(*s) && chartype_rbracket(*(s+1)) && chartype_leave(*(s+2)))) ++s; //Scan for terminating ']]>'.
++s;
}
++s; //Step over the last ']'.
goto LOC_LEAVE; //Look for any following PCDATA.
}
}
}
}
}
}
continue; //Probably a corrupted CDATA section, so just eat it.
}
else if(*s==_T('D')) //'<!D...'
{
++s;
if(*s==_T('O')) //'<!DO...'
{
++s;
if(*s==_T('C')) //'<!DOC...'
{
++s;
if(*s==_T('T')) //'<!DOCT...'
{
++s;
if(*s==_T('Y')) //'<!DOCTY...'
{
++s;
if(*s==_T('P')) //'<!DOCTYP...'
{
++s;
if(*s==_T('E')) //'<!DOCTYPE...'
{
++s;
SKIPWS(); //Eat any whitespace.
xml_attribute_struct* a = 0;
if(OPTSET(parse_doctype))
{
PUSHNODE(node_doctype); //Append a new node on the tree.
a = append_attribute(cursor,3); //Store the DOCTYPE name.
a->value = a->name = s; //Save the offset.
}
SCANWHILE(chartype_symbol(*s)); //'<!DOCTYPE symbol...'
#ifdef PUGOPT_NONSEG
if(OPTSET(parse_doctype))
a->name_size = a->value_size = s - a->value; //Save the length. rem: Before ENDSEG()
#endif
ENDSEG(); //Save char in 'ch', terminate & step over.
if(chartype_space(ch)) SKIPWS(); //Eat any whitespace.
LOC_DOCTYPE_SYMBOL:
if(chartype_symbol(*s))
{
mark = s;
SCANWHILE(chartype_symbol(*s)); //'...symbol SYSTEM...'
if(OPTSET(parse_doctype))
{
a = append_attribute(cursor,1);
a->value = a->name = mark;
#ifdef PUGOPT_NONSEG
a->value_size = a->name_size = s - mark; //NF 19 Jan 2003.
#else
*s = 0;
#endif
}
++s;
SKIPWS();
}
if(chartype_quote(*s)) //'...SYSTEM "..."'
{
LOC_DOCTYPE_QUOTE:
ch = *s;
++s;
mark = s;
while(*s!=0 && *s != ch) ++s;
if(*s!=0)
{
if(OPTSET(parse_doctype))
{
a = append_attribute(cursor,1);
a->value = mark;
#ifdef PUGOPT_NONSEG
a->value_size = s - mark; //NF 19 Jan 2003.
#else
*s = 0;
#endif
}
++s;
SKIPWS(); //Eat whitespace.
if(chartype_quote(*s)) goto LOC_DOCTYPE_QUOTE; //Another quoted section to store.
else if(chartype_symbol(*s)) goto LOC_DOCTYPE_SYMBOL; //Not wellformed, but just parse it.
}
}
if(chartype_lbracket(*s)) //'...[...'
{
++s; //Step over the bracket.
if(OPTSET(parse_doctype)) cursor->value = s; //Store the offset.
unsigned int bd = 1; //Bracket depth counter.
while(*s!=0) //Loop till we're out of all brackets.
{
if(chartype_rbracket(*s)) --bd;
else if(chartype_lbracket(*s)) ++bd;
if(bd == 0) break;
++s;
}
//Note: 's' now points to end of DTD, i.e.: ']'.
if(OPTSET(parse_doctype))
{
//Note: If we aren't parsing the DTD ('!parse_dtd', etc.) then it is stored in the DOM as one whole chunk.
#ifdef PUGOPT_NONSEG
SETLEN(); //NF 19 Jan 2003
#else
*s = 0; //Zero-terminate.
#endif
if(OPTSET(parse_dtd)||OPTSET(parse_dtd_only))
{
if(OPTSET(parse_dtd))
{
#ifdef PUGOPT_NONSEG
TCHAR svch = *s;
try
{
*s = 0; //Zero-terminate.
parse(cursor->value,cursor,growby,optmsk); //Parse it.
}
catch(...){ assert(false); }
*s = svch;
#else
parse(cursor->value,cursor,growby,optmsk); //Parse it.
#endif
}
if(OPTSET(parse_dtd_only)) return (s+1); //Flagged to parse DTD only, so leave here.
}
else if(OPTSET(parse_trim_doctype)) //Trim whitespace.
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value, cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
++s; //Step over the zero.
POPNODE(); //Pop since this is a standalone.
}
SCANFOR(chartype_leave(*s));
continue;
}
//Fall-through; make sure we pop.
POPNODE(); //Pop since this is a standalone.
continue;
}
}
}
}
}
}
}
else if(chartype_symbol(*s)) //An inline DTD tag.
{
mark = s;
SCANWHILE(chartype_symbol(*s));
ENDSEG(); //Save char in 'ch', terminate & step over.
xml_node_type e = node_dtd_entity;
#ifdef PUGOPT_NONSEG
const unsigned int dtdilen = (s - 1) - mark;
if(_tcsncmp(mark,_T("ATTLIST"),max((7*sizeof(TCHAR)),dtdilen))==0) e = node_dtd_attlist;
else if(_tcsncmp(mark,_T("ELEMENT"),max((7*sizeof(TCHAR)),dtdilen))==0) e = node_dtd_element;
else if(_tcsncmp(mark,_T("NOTATION"),max((8*sizeof(TCHAR)),dtdilen))==0) e = node_dtd_notation;
#else
if(_tcscmp(mark,_T("ATTLIST"))==0) e = node_dtd_attlist;
else if(_tcscmp(mark,_T("ELEMENT"))==0) e = node_dtd_element;
else if(_tcscmp(mark,_T("NOTATION"))==0) e = node_dtd_notation;
#endif
PUSHNODE(e); //Append a new node on the tree.
if(*s!=0 && chartype_space(ch))
{
SKIPWS(); //Eat whitespace.
if(chartype_symbol(*s) || *s==_T('%'))
{
mark = s;
if(*s==_T('%')) //Could be '<!ENTITY % name' -or- '<!ENTITY %name'
{
#ifdef PUGOPT_NONSEG
//Note: For memory-mapped file support we need to treat 's' as read-only so we can't do '*(s-1) = _T('%');' below.
cursor->name = mark; //Sort out extraneous whitespace when we retrieve it. TODO: Whitespace cleanup.
#endif
++s;
if(chartype_space(*s))
{
SKIPWS(); //Eat whitespace.
#ifndef PUGOPT_NONSEG
*(s-1) = _T('%');
cursor->name = (s-1);
#endif
}
#ifndef PUGOPT_NONSEG
else cursor->name = mark;
#endif
}
else cursor->name = s;
SCANWHILE(chartype_symbol(*s));
#ifdef PUGOPT_NONSEG
cursor->name_size = s - cursor->name;
#endif
ENDSEG(); //Save char in 'ch', terminate & step over.
if(chartype_space(ch))
{
SKIPWS(); //Eat whitespace.
if(e == node_dtd_entity) //Special case; may have multiple quoted sections w/anything inside.
{
cursor->value = s; //Just store everything here.
bool qq = false; //Quote in/out flag.
while(*s != 0) //Loop till we find the right sequence.
{
if(!qq && chartype_quote(*s)){ ch = *s; qq = true; }
else if(qq && *s == ch) qq = false;
else if(!qq && chartype_leave(*s)) //Not in quoted reqion and '>' hit.
{
#ifdef PUGOPT_NONSEG
SETLEN(); //NF 19 Jan 2003.
#else
*s = 0;
#endif
++s;
if(OPTSET(parse_trim_entity))
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value,cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
POPNODE();
goto LOC_SEARCH;
}
++s;
}
if(OPTSET(parse_trim_entity))
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value, cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
}
else
{
cursor->value = s;
SCANFOR(chartype_leave(*s)); //Just look for '>'.
#ifdef PUGOPT_NONSEG
SETLEN(); //NF 19 Jan 2003.
#else
*s = 0;
#endif
++s;
if(OPTSET(parse_trim_entity))
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value, cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
POPNODE();
goto LOC_SEARCH;
}
}
}
}
POPNODE();
}
}
else if(chartype_symbol(*s)) //'<#...'
{
cursor = append_node(cursor,growby); //Append a new node to the tree.
LOC_ELEMENT: //Scan for & store element name.
cursor->name = s;
SCANWHILE(chartype_symbol(*s)); //Scan for a terminator.
#ifdef PUGOPT_NONSEG
cursor->name_size = s - cursor->name; //Note: Before ENDSEG().
#endif
ENDSEG(); //Save char in 'ch', terminate & step over.
if
(
*s!=0 &&
(
chartype_close(ch) //'</...'
#ifdef PUGOPT_NONSEG
//||
//chartype_pi(ch) //Treat '?>' as '/>' NF 19 Jan 2003
#endif
)
)
{
SCANFOR(chartype_leave(*s)); //Scan for '>', stepping over the tag name.
POPNODE(); //Pop.
continue;
}
else if(*s!=0 && !chartype_space(ch)) goto LOC_PCDATA; //No attributes, so scan for PCDATA.
else if(*s!=0 && chartype_space(ch))
{
SKIPWS(); //Eat any whitespace.
LOC_ATTRIBUTE:
if(chartype_symbol(*s)) //<... #...
{
xml_attribute_struct* a = append_attribute(cursor,growby); //Make space for this attribute.
a->name = s; //Save the offset.
SCANWHILE(chartype_symbol(*s)); //Scan for a terminator.
#ifdef PUGOPT_NONSEG
ENDSEGNAM(a);
#else
ENDSEG(); //Save char in 'ch', terminate & step over.
#endif
if(*s!=0 && chartype_space(ch)) SKIPWS(); //Eat any whitespace.
if(*s!=0 && (chartype_equals(ch) || chartype_equals(*s))) //'<... #=...'
{
if(chartype_equals(*s)) ++s;
SKIPWS(); //Eat any whitespace.
if(chartype_quote(*s)) //'<... #="...'
{
ch = *s; //Save quote char to avoid breaking on "''" -or- '""'.
++s; //Step over the quote.
a->value = s; //Save the offset.
SCANFOR(*s == ch); //Scan for the terminating quote, or '>'.
#ifdef PUGOPT_NONSEG
ENDSEGATT(a);
#else
ENDSEG(); //Save char in 'ch', terminate & step over.
#endif
if(OPTSET(parse_trim_attribute)) //Trim whitespace.
{
#ifdef PUGOPT_NONSEG
strwtrim(&a->value,a->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&a->value);
else strwtrim(&a->value);
#endif
}
if(chartype_leave(*s)){ ++s; goto LOC_PCDATA; }
else if(chartype_close(*s))
{
++s;
POPNODE();
SKIPWS(); //Eat any whitespace.
if(chartype_leave(*s)) ++s;
goto LOC_PCDATA;
}
if(chartype_space(*s)) //This may indicate a following attribute.
{
SKIPWS(); //Eat any whitespace.
goto LOC_ATTRIBUTE; //Go scan for additional attributes.
}
}
}
if(chartype_symbol(*s)) goto LOC_ATTRIBUTE;
else if(*s!=0 && cursor->type == node_pi)
{
#ifdef PUGOPT_NONSEG
SCANFOR(chartype_pi(*s)); //compliments change where we don't fudge to '/>' when we find the PI. NF 20 Jan 2003
SKIPWS(); //Eat any whitespace.
if(chartype_pi(*s)) ++s;
#else
SCANFOR(chartype_close(*s));
SKIPWS(); //Eat any whitespace.
if(chartype_close(*s)) ++s;
#endif
SKIPWS(); //Eat any whitespace.
if(chartype_leave(*s)) ++s;
POPNODE();
goto LOC_PCDATA;
}
}
}
LOC_LEAVE:
if(chartype_leave(*s)) //'...>'
{
++s; //Step over the '>'.
LOC_PCDATA: //'>...<'
mark = s; //Save this offset while searching for a terminator.
SKIPWS(); //Eat whitespace if no genuine PCDATA here.
if(chartype_enter(*s)) //We hit a '<...', with only whitespace, so don't bother storing anything.
{
if(chartype_close(*(s+1))) //'</...'
{
SCANFOR(chartype_leave(*s)); //Scan for '>', stepping over any end-tag name.
POPNODE(); //Pop.
continue; //Continue scanning.
}
else goto LOC_SEARCH; //Expect a new element enter, so go scan for it.
}
s = mark; //We hit something other than whitespace; restore the original offset.
PUSHNODE(node_pcdata); //Append a new node on the tree.
cursor->value = s; //Save the offset.
SCANFOR(chartype_enter(*s)); //'...<'
#ifdef PUGOPT_NONSEG
ENDSEGDAT();
#else
ENDSEG(); //Save char in 'ch', terminate & step over.
#endif
if(OPTSET(parse_trim_pcdata)) //Trim whitespace.
{
#ifdef PUGOPT_NONSEG
strwtrim(&cursor->value,cursor->value_size);
#else
if(OPTSET(parse_wnorm)) strwnorm(&cursor->value);
else strwtrim(&cursor->value);
#endif
}
POPNODE(); //Pop since this is a standalone.
if(chartype_enter(ch)) //Did we hit a '<...'?
{
if(chartype_close(*s)) //'</...'
{
SCANFOR(chartype_leave(*s)); //'...>'
POPNODE(); //Pop.
goto LOC_LEAVE;
}
else if(chartype_special(*s)) goto LOC_CLASSIFY; //We hit a '<!...'. We must test this here if we want comments intermixed w/PCDATA.
else if(*s) goto LOC_CLASSIFY;
else return s;
}
}
//Fall-through A.
else if(chartype_close(*s)) //'.../'
{
++s;
if(chartype_leave(*s)) //'.../>'
{
POPNODE(); //Pop.
++s;
continue;
}
}
}
//Fall-through B.
else if(chartype_close(*s)) //'.../'
{
SCANFOR(chartype_leave(*s)); //'.../>'
POPNODE(); //Pop.
continue;
}
}
}
return s;
}
/*
//<summary>Read data from the file at 'path' into the buffer. Free with 'free'.</summary>
//<param name="path">File path.</param>
//<param name="buffer">Pointer to pointer to string to recieve buffer.</param>
//<param name="size">Pointer to count bytes read and stored in 'buffer'.</param>
//<param name="tempsize">Temporary read buffer size.</param>
//<returns>Success if file at 'path' was opened and bytes were read into memory.</returns>
//<remarks>Memory is allocated at '*buffer'. Free with 'free'.</remarks>
inline static bool load_file(const TCHAR* path,TCHAR** buffer,unsigned long* size,unsigned long tempsize = 4096)
{
if(!path || !buffer || !size) return false;
*size = 0;
*buffer = 0;
HANDLE file_handle = CreateFile(path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(file_handle == INVALID_HANDLE_VALUE) return false;
TCHAR* temp = (TCHAR*) malloc(sizeof(TCHAR)*tempsize);
if(!temp) return false;
unsigned long read_bytes = 0;
ZeroMemory(temp,sizeof(TCHAR)*tempsize);
while(ReadFile(file_handle,(void*)temp,tempsize-1,&read_bytes,0) && read_bytes && strcatgrow(buffer,temp))
{
*size += read_bytes;
ZeroMemory(temp,sizeof(TCHAR)*tempsize);
}
CloseHandle(file_handle);
free(temp);
return (*size) ? true : false;
}
*/
//<summary>A void pointer array. Used by various xml_node::find* functions.</summary>
class pointer_array
{
//Internal Data Members
protected:
unsigned int _size; //Count items.
unsigned int _room; //Available space.
void** _data; //The list.
unsigned int _grow; //Grow by increment.
public:
//<summary>Default constructor.</summary>
//<param name="grow">Array growth increment.</param>
pointer_array(unsigned int grow = 4):
_size(0),
_room(0),
_data(NULL),
_grow(grow)
{
_data = (void**)malloc(sizeof(void*)*_grow);
_room = (_data) ? _grow : 0;
}
~pointer_array(){ if(_data) free(_data); }
public:
bool empty(){ return (_size == 0); } //True if there is no data in the array.
void remove_all(){ _size = 0; } //Remove all data elements from the array.
void clear() //Free any allocated memory.
{
if(_data)
{
_data = (void**)realloc(_data,sizeof(void*)*_grow); //Reallocate to first growth increment.
_room = _grow; //Mark it as such.
_size = 0; //Mark array as empty.
}
}
virtual void*& operator[](unsigned int i) //Access element at subscript, or dummy value if overflow.
{
static void* dummy = 0;
if(i < _size) return _data[i]; else return dummy;
}
unsigned int size(){ return _size; } //Count data elements in the array.
virtual void* at(unsigned int i){ if(i < _size) return _data[i]; else return NULL; } //Access element at subscript, or NULL if overflow.
long push_back(void* element) //Append a new element to the array.
{
if(_data) //Fail if no array.
{
if(_size < _room) //There is enough allocated space.
{
_data[_size] = element; //Set it.
_size++; //Increment our count of elements.
return _size-1; //Return the element's subscript.
}
else //Not enough room.
{
void** temp = (void**)realloc(_data,sizeof(void*)*(_size+_grow)); //Grow the array.
if(temp) //Reallocation succeeded.
{
_room += _grow; //Increment available space.
_data = temp; //Assign reallocated value to array pointer.
_data[_size] = element; //Set the element to be added.
_size++; //Increment our count of elements.
return _size-1; //Return the element's subscript.
}
}
}
return -1; //Something failed, so return a bad subscript.
}
};
//<summary>A simple indentation stack.</summary>
//<remarks>Used by xml_node::outer_xml function.</remarks>
class indent_stack
{
//Internal Data Members
protected:
TCHAR _inch; //The indent character.
TCHAR* _stac; //The aggregate indent string (stack).
int _size; //Current depth (avoids using '_tcslen' on push/pop).
//Construction/Destruction
public:
//<summary>Default constructor.</summary>
//<param name="c">Indent character.</param>
indent_stack(TCHAR c = _T('\t')):
_inch(c),
_stac(0) ,
_size(0)
{
_stac = (TCHAR*)malloc(sizeof(TCHAR)); //Allocate.
*_stac = 0; //Zero-terminate.
}
//Destructor.
virtual ~indent_stack(){ if(_stac) free(_stac); }
//Stack Operators
public:
//<summary>Grow indent string by one indent character.</summary>
//<remarks>Reallocates the indent string.</remarks>
void push()
{
if(_inch && _stac)
{
_size++;
_stac = (TCHAR*)realloc(_stac,sizeof(TCHAR)*(_size+1));
_stac[_size-1] = _inch;
_stac[_size] = 0;
}
}
//<summary>Shrink the indent string by one indent character.</summary>
void pop()
{
if(_inch && _stac && _size > 0)
{
_size--;
_stac = (TCHAR*)realloc(_stac,sizeof(TCHAR)*(_size+1));
_stac[_size] = 0;
}
}
//<summary>Accesses the indent depth.</summary>
//<returns>The current indent string, or "" if empty.</returns>
const TCHAR* depth(){ return (_inch && _stac) ? _stac : _T(""); }
};
//<summary>
// Stream output. Recursively writes the given xml_node_struct structure to
// the given stream. NOTE: Use this recursive implementation for debug purposes
// only, since a large tree may cause a stack overflow.
//</summary>
//<param name="os">Reference to output stream.</param>
//<param name="indent">Reference to indentation stack.</param>
//<param name="node">Pointer to the node.</param>
//<param name="breaks">Use linebreaks?</param>
//<returns>
// String data is written to stream. Indent stack may be altered.
// If you want to make this prettier, and to avoid propagating whitespace,
// you will have to trim excess whitespace from the PCDATA sections.
//</returns>
inline static void outer_xml(std::basic_ostream<TCHAR,std::char_traits<TCHAR> > & os,indent_stack& indent,xml_node_struct* node,bool breaks = true)
{
if(node && os.good()) //There is a node and ostream is OK.
{
register unsigned int n, i;
os << indent.depth();
switch(node->type)
{
case node_dtd_attlist:
if(node->name)
{
#ifdef PUGOPT_NONSEG
os << _T("<!ATTLIST ");
os.write( node->name, node->name_size );
#else
os << _T("<!ATTLIST ") << node->name;
#endif
if(node->value)
#ifdef PUGOPT_NONSEG
{
os << _T(" ");
os.write( node->value, node->value_size );
}
#else
os << _T(" ") << node->value;
#endif
os << _T(">");
}
break;
case node_dtd_element:
if(node->name)
{
#ifdef PUGOPT_NONSEG
os << _T("<!ELEMENT ");
os.write( node->name, node->name_size );
if(node->value)
{
os << _T(" ");
os.write( node->value, node->value_size );
}
#else
os << _T("<!ELEMENT ") << node->name;
if(node->value) os << _T(" ") << node->value;
#endif
os << _T(">");
}
break;
case node_dtd_entity:
if(node->name)
{
#ifdef PUGOPT_NONSEG
os << _T("<!ENTITY ");
os.write( node->name, node->name_size );
if(node->value)
{
os << _T(" ");
os.write( node->value, node->value_size );
}
#else
os << _T("<!ENTITY ") << node->name;
if(node->value) os << _T(" ") << node->value;
#endif
os << _T(">");
}
break;
case node_dtd_notation:
if(node->name)
{
#ifdef PUGOPT_NONSEG
os << _T("<!NOTATION ");
os.write( node->name, node->name_size );
if(node->value)
{
os << _T(" ");
os.write( node->value, node->value_size );
}
#else
os << _T("<!NOTATION ") << node->name;
if(node->value) os << _T(" ") << node->value;
#endif
os << _T(">");
}
break;
case node_doctype:
os << _T("<!DOCTYPE");
n = node->attributes;
for(i=0; i<n; ++i)
{
os << _T(" ");
if(node->attribute[i]->name)
#ifdef PUGOPT_NONSEG
os.write( node->attribute[i]->name, node->attribute[i]->name_size );
#else
os << node->attribute[i]->name;
#endif
else if(node->attribute[i]->value)
#ifdef PUGOPT_NONSEG
{
os << _T("\"");
os.write( node->attribute[i]->value, node->attribute[i]->value_size );
os << _T("\"");
}
#else
os << _T("\"") << node->attribute[i]->value << _T("\"");
#endif
}
if(node->children)
{
if(breaks) os << std::endl;
else os << _T(" ");
os << _T("[");
if(breaks) os << std::endl;
else os << _T(" ");
n = node->children;
indent.push(); //Push the indent stack.
for(i=0; i<n; ++i)
{
if
(
node->child[i] && //There is a child at i.
(
node->child[i]->type == node_dtd_attlist || //Skip all other types.
node->child[i]->type == node_dtd_element ||
node->child[i]->type == node_dtd_entity ||
node->child[i]->type == node_dtd_notation
)
)
outer_xml(os,indent,node->child[i],breaks);
}
indent.pop(); //Pop the indent stack.
os << _T("]");
}
else if(node->value)
#ifdef PUGOPT_NONSEG
{
os << _T(" [");
os.write(node->value,node->value_size);
os << _T("]");
}
#else
os << _T(" [") << node->value << _T("]");
#endif
os << _T(">");
break;
case node_pcdata:
#ifdef PUGOPT_NONSEG
if(node->value) os.write(node->value,node->value_size);
#else
if(node->value) os << node->value;
#endif
break;
case node_cdata:
#ifdef PUGOPT_NONSEG
if(node->value)
{
os << _T("<![CDATA[");
os.write(node->value,node->value_size);
os << _T("]]>");
}
#else
if(node->value) os << _T("<![CDATA[") << node->value << _T("]]>");
#endif
break;
case node_include:
#ifdef PUGOPT_NONSEG
if(node->value)
{
os << _T("<![INCLUDE[");
os.write(node->value, node->value_size);
os << _T("]]>");
}
#else
if(node->value) os << _T("<![INCLUDE[") << node->value << _T("]]>");
#endif
break;
case node_comment:
#ifdef PUGOPT_NONSEG
if(node->value)
{
os << _T("<!--");
os.write(node->value, node->value_size);
os << _T("-->");
}
#else
if(node->value) os << _T("<!--") << node->value << _T("-->");
#endif
break;
case node_element:
case node_pi:
os << _T("<");
if(node->type==node_pi) os << _T("?");
if(node->name)
#ifdef PUGOPT_NONSEG
os.write(node->name,node->name_size);
#else
os << node->name;
#endif
else os << _T("anonymous");
n = node->attributes;
for(i=0; i<n; ++i)
{
if(node->attribute[i] && node->attribute[i]->name)
{
#ifdef PUGOPT_NONSEG
os << _T(" ");
os.write(node->attribute[i]->name,node->attribute[i]->name_size);
if(node->attribute[i]->value)
{
os << _T("=\"");
os.write(node->attribute[i]->value,node->attribute[i]->value_size);
os << _T("\"");
}
#else
os << _T(" ") << node->attribute[i]->name;
if(node->attribute[i]->value) os << _T("=\"") << node->attribute[i]->value << _T("\"");
#endif
}
}
n = node->children;
if(n && node->type == node_element)
{
os << _T(">");
if(n == 1 && node->child[0]->type == node_pcdata)
{
if(node->child[0] && node->child[0]->value)
#ifdef PUGOPT_NONSEG
os.write(node->child[0]->value,node->child[0]->value_size);
#else
os << node->child[0]->value;
#endif
}
else
{
if(breaks) os << std::endl;
indent.push();
for(i=0; i<n; ++i) pug::outer_xml(os,indent,node->child[i],breaks);
indent.pop();
os << indent.depth();
}
os << _T("</");
#ifdef PUGOPT_NONSEG
if(node->name)
os.write(node->name, node->name_size);
#else
if(node->name) os << node->name;
#endif
os << _T(">");
}
else
{
if(node->type==node_pi) os << _T("?>");
else os << _T("/>");
}
break;
default: break;
}
if(breaks) os << std::endl;
os.flush();
}
}
//<summary>Abstract iterator class for interating over a node's members.</summary>
//<remarks>Used as base class for 'xml_node_iterator' and 'xml_attribute_iterator'.</remarks>
template <class _Ty,class _Diff,class _Pointer,class _Reference>
class xml_iterator : public std::_Ranit<_Ty,_Diff,_Pointer,_Reference>
{
protected:
xml_node_struct* _vref; //A pointer to the node over which to iterate.
long _sscr; //Current subscript of element.
public:
xml_iterator() : _vref(0), _sscr(-1) {} //Default constructor.
xml_iterator(xml_node_struct* vref,long sscr = 0) : _vref(vref), _sscr(sscr){ } //Initializing constructor.
xml_iterator(const xml_iterator& r) : _vref(r._vref), _sscr(r._sscr){ } //Copy constructor.
virtual ~xml_iterator(){} //Destructor.
public:
virtual bool good() = 0; //Internal validity of '_vref'.
virtual bool oob() = 0; //Out of bounds check for '_sscr' with respect to '_vref'. Returns true if '_sscr' is O.O.B.
public:
virtual long subscript(){ return _sscr; } //Get subscript value;
virtual void subscript(long new_subscript){ _sscr = new_subscript; } //Set subscript value;
public:
virtual xml_iterator& operator=(const xml_iterator& rhs){ _vref = rhs._vref; _sscr = rhs._sscr; return *this; } //Assignment.
virtual bool operator==(const xml_iterator& rhs){ return (_sscr == rhs._sscr); } //True if this is equal to RHS.
virtual bool operator!=(const xml_iterator& rhs){ return (_sscr != rhs._sscr); } //True if this is not equal to RHS.
virtual bool operator<(const xml_iterator& rhs){ return (_sscr < rhs._sscr); } //True if this subscript is less than RHS.
virtual bool operator>(const xml_iterator& rhs){ return (_sscr > rhs._sscr); } //True if this subscript is greater than RHS.
virtual bool operator<=(const xml_iterator& rhs){ return (_sscr <= rhs._sscr); } //True if this subscript is less than or equal to RHS.
virtual bool operator>=(const xml_iterator& rhs){ return (_sscr >= rhs._sscr); } //True if this subscript is greater than or equal to RHS.
virtual xml_iterator& operator++(){ _sscr++; return *this; } //Increment the iterator (subscript).
virtual xml_iterator& operator--(){ _sscr--; return *this; } //Decrement the iterator (subscript).
virtual _Ty& operator*() = 0; //Dereference operator.
virtual _Ty* operator->() = 0;
};
class xml_node; //Forward decl.
//<summary>Abstract tree walker class for xml_node::traverse().</summary>
class xml_tree_walker
{
protected:
long _deep; //Current node depth.
public:
xml_tree_walker() : _deep(0) {} //Default constructor.
virtual ~xml_tree_walker(){} //Destructor.
public:
virtual void push(){ ++_deep; } //Increment node depth.
virtual void pop(){ --_deep; } //Decrement node depth.
virtual long depth(){ return (_deep > 0) ? _deep : 0; } //Access node depth.
public:
//<summary>Callback when traverse on a given root node begins.</summary>
//<returns>Returning false will abort the traversal.</returns>
//<remarks>Override this to implement your own custom behavior.</remarks>
virtual bool begin(xml_node&){ return true; }
//<summary>Callback for each node that is hit on traverse.</summary>
//<returns>Returning false will abort the traversal.</returns>
virtual bool for_each(xml_node&) = 0;
//<summary>Callback when traverse on a given root node ends.</summary>
//<returns>Returning false will abort the traversal.</returns>
//<remarks>Override this to implement your own custom behavior.</remarks>
virtual bool end(xml_node&){ return true; }
};
//<summary>Provides a light-weight wrapper for manipulating xml_attribute_struct structures.</summary>
//<remarks>
// Note: xml_attribute does not create any memory for the attribute it wraps;
// it only wraps a pointer to an existing xml_attribute_struct.
//</remarks>
class xml_attribute
{
//Internal Data Members
protected:
xml_attribute_struct* _attr; //The internal attribute pointer.
//Construction/Destruction
public:
xml_attribute() : _attr(NULL) {} //Default constructor.
xml_attribute(xml_attribute_struct* attr) : _attr(attr) {} //Initializing constructor.
xml_attribute(const xml_attribute& r) : _attr(r._attr) {} //Copy constructor.
virtual ~xml_attribute(){} //Destructor.
//Operators
public:
void attach(xml_attribute_struct* v){ _attr = v; }
xml_attribute& operator=(const xml_attribute& r){ _attr = r._attr; return *this; } //Assign internal pointer.
bool operator==(const xml_attribute& r){ return (_attr == r._attr); } //Compare internal pointer.
bool operator!=(const xml_attribute& r){ return (_attr != r._attr); }
operator xml_attribute_struct*(){ return _attr; }
//<summary>Cast attribute value as std::string. If not found, return empty.</summary>
//<returns>The std::string attribute value, or empty.</returns>
//<remarks>Note: Modifying this will not change the value, e.g. read only.</remarks>
operator std::string()
{
std::string temp;
if(!empty() && has_value())
{
#ifdef PUGOPT_NONSEG
temp.append(_attr->value,_attr->value_size);
#else
temp = _attr->value;
#endif
}
return temp;
}
//<summary>Cast attribute value as integral character string. If not found, return NULL.</summary>
//<returns>Integral character string attribute value, or NULL.</returns>
//<remarks>Warning: Modifying this may corrupt portions of the document tree.</remarks>
operator const TCHAR*()
{
if(empty() || !has_value()) return NULL;
return _attr->value;
}
//<summary>Cast attribute value as long. If not found, return 0.</summary>
//<returns>Attribute value as long, or 0.</returns>
//<remarks>Note: Modifying this will not change the value, e.g. read only.</remarks>
operator long()
{
if(empty() || !has_value()) return 0;
#ifdef PUGOPT_NONSEG
TCHAR temp[PUGDEF_ATTR_VALU_SIZE];
unsigned int valulen = sizeof(temp)-1;
const unsigned int maxlen = valulen ? min(valulen,_attr->value_size) : _attr->value_size;
_tcsncpy(temp,_attr->value,maxlen);
temp[maxlen] = 0;
return _tcstol(temp,NULL,10);
#else
return _tcstol(_attr->value,NULL,10);
#endif
}
//<summary>Cast attribute value as double. If not found, return 0.0.</summary>
//<returns>Attribute value as double, or 0.0.</returns>
//<remarks>Note: Modifying this will not change the value, e.g. read only.</remarks>
operator double()
{
if(empty() || !has_value()) return 0.0;
#ifdef PUGOPT_NONSEG
TCHAR temp[PUGDEF_ATTR_VALU_SIZE];
unsigned int valulen = sizeof(temp)-1;
const unsigned int maxlen = valulen ? min(valulen,_attr->value_size) : _attr->value_size;
_tcsncpy(temp,_attr->value,maxlen);
temp[maxlen] = 0;
return _tcstod(temp,0);
#else
return _tcstod(_attr->value,0);
#endif
}
//<summary>Cast attribute value as bool. If not found, return false.</summary>
//<returns>Attribute value as bool, or false.</returns>
//<remarks>Note: Modifying this will not change the value, e.g. read only.</remarks>
operator bool()
{
if(empty() || !has_value()) return false;
if(*(_attr->value))
{
return //Only look at first char:
(
*(_attr->value) == _T('1') || //1*
*(_attr->value) == _T('t') || //t* (true)
*(_attr->value) == _T('T') || //T* (True|true)
*(_attr->value) == _T('y') || //y* (yes)
*(_attr->value) == _T('Y') //Y* (Yes|YES)
)
? true : false; //Return true if matches above, else false.
}
}
//<summary>Set attribute to std::string.</summary>
//<param name="rhs">Value std::string to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator=(const std::string& rhs){ value(rhs.c_str()); return *this; }
//<summary>Set attribute to string.</summary>
//<param name="rhs">Value string to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator=(const TCHAR* rhs){ if(rhs) value(rhs); return *this; }
//<summary>Set attribute to long.</summary>
//<param name="rhs">Value long to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator=(long rhs)
{
TCHAR temp[32] = {0};
_stprintf(temp,_T("%ld"),rhs);
value(temp);
return *this;
}
//<summary>Set attribute to double.</summary>
//<param name="rhs">Value double to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator=(double rhs)
{
TCHAR temp[32] = {0};
_stprintf(temp,_T("%lf"),rhs);
value(temp);
return *this;
}
//<summary>Set attribute to bool.</summary>
//<param name="rhs">Value bool to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator=(bool rhs)
{
value(rhs?_T("true"):_T("false"));
return *this;
}
//<summary>Right-shift attribute value to std::string.</summary>
//<param name="rhs">Reference to std::string to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator>>(std::string& rhs)
{
#ifdef PUGOPT_NONSEG
rhs.clear();
rhs.append(_attr->value,_attr->value_size);
#else
rhs = value();
#endif
return *this;
}
//<summary>Right-shift attribute value to long.</summary>
//<param name="rhs">Reference to long to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator>>(long& rhs){ rhs = (long)*this; return *this; }
//<summary>Right-shift attribute value to double.</summary>
//<param name="rhs">Reference to double to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator>>(double& rhs){ rhs = (double)*this; return *this; }
//<summary>Right-shift attribute value to bool.</summary>
//<param name="rhs">Reference to bool to set.</param>
//<returns>Reference to xml_attribute.</returns>
xml_attribute& operator>>(bool& rhs){ rhs = (bool)*this; return *this; }
//<summary>Left-shift attribute value to long.</summary>
//<param name="lhs">Reference to long to set.</param>
//<param name="rhs">Reference to xml_attribute to read.</param>
//<returns>Reference to long.</returns>
friend long& operator<<(long& lhs,xml_attribute& rhs){ lhs = (long)rhs; return lhs; }
//<summary>Left-shift attribute value to double.</summary>
//<param name="lhs">Reference to double to set.</param>
//<param name="rhs">Reference to xml_attribute to read.</param>
//<returns>Reference to double.</returns>
friend double& operator<<(double& lhs,xml_attribute& rhs){ lhs = (double)rhs; return lhs; }
//<summary>Left-shift attribute value to bool.</summary>
//<param name="lhs">Reference to bool to set.</param>
//<param name="rhs">Reference to xml_attribute to read.</param>
//<returns>Reference to bool.</returns>
friend bool& operator<<(bool& lhs,xml_attribute& rhs){ lhs = (bool)rhs; return lhs; }
//<summary>Left-shift long to attribute value.</summary>
//<param name="lhs">Reference to xml_attribute to set.</param>
//<param name="rhs">Reference to long to read.</param>
//<returns>Reference to xml_attribute.</returns>
friend xml_attribute& operator<<(xml_attribute& lhs,const long rhs){ lhs = rhs; return lhs; }
//<summary>Left-shift double to attribute value.</summary>
//<param name="lhs">Reference to xml_attribute to set.</param>
//<param name="rhs">Reference to double to read.</param>
//<returns>Reference to xml_attribute.</returns>
friend xml_attribute& operator<<(xml_attribute& lhs,const double& rhs){ lhs = rhs; return lhs; }
//<summary>Left-shift bool to attribute value.</summary>
//<param name="lhs">Reference to xml_attribute to set.</param>
//<param name="rhs">Reference to bool to read.</param>
//<returns>Reference to xml_attribute.</returns>
friend xml_attribute& operator<<(xml_attribute& lhs,const bool& rhs){ lhs = rhs; return lhs; }
public:
bool empty(){ return (_attr == NULL); } //True if the internal xml_attribute_struct pointer is NULL.
bool has_name(){ return (!empty() && _attr->name); } //True if the attribute has a name.
bool has_value(){ return (!empty() && _attr->value); } //True if the attribute has a value.
#ifdef PUGOPT_NONSEG
bool has_name(const TCHAR* name) { return (name && !empty() && has_name() && _tcsncmp(_attr->name,name,_attr->name_size)==0); } //Is named 'name'.
bool has_value(const TCHAR* value) { return (value && !empty() && has_value() && _tcsncmp(_attr->value,value,_attr->value_size)==0); } //Has value 'value'.
#else
bool has_name(const TCHAR* name) { return (name && !empty() && has_name() && _tcscmp(_attr->name,name)==0); } //Is named 'name'.
bool has_value(const TCHAR* value) { return (value && !empty() && has_value() && _tcscmp(_attr->value,value)==0); } //Has value 'value'.
#endif
public:
const TCHAR* name(){ return (!empty() && _attr->name) ? _attr->name : _T(""); } //Access the attribute name.
#ifdef PUGOPT_NONSEG
const unsigned int name_size(){ return (!empty()) ? _attr->name_size : 0; } //Access the attribute name length (for PUGOPT_NONSEG).
#endif
bool name(TCHAR* new_name) //Set the attribute name.
{
if(!empty() && new_name)
#ifdef PUGOPT_NONSEG
return strcpyinsitu(&_attr->name,new_name,&_attr->name_insitu,_attr->name_size);
#else
return strcpyinsitu(&_attr->name,new_name,&_attr->name_insitu);
#endif
return false;
}
const TCHAR* value(){ return (!empty()) ? _attr->value : _T(""); } //Access the attribute value.
#ifdef PUGOPT_NONSEG
const unsigned int value_size(){ return (!empty()) ? _attr->value_size : 0; } //Access the attribute name length (for PUGOPT_NONSEG).
#endif
bool value(const TCHAR* new_value) //Set the attribute value.
{
if(!empty() && new_value)
#ifdef PUGOPT_NONSEG
return strcpyinsitu(&_attr->value,new_value,&_attr->value_insitu,_attr->value_size);
#else
return strcpyinsitu(&_attr->value,new_value,&_attr->value_insitu);
#endif
return false;
}
};
class xml_node; //Forward declaration.
//<summary>Forward wrapper for any as-yet undefined class.</summary>
//<remarks>
// Used by xml_node_iterator, and xml_attribute_iterator to assist with
// operator->(), and operator*() mapping to xml_node and xml_attribute
// types.
//</remarks>
template <typename TYPE> class forward_class
{
protected:
TYPE* _obj; //The class, internal.
public:
forward_class() : _obj(NULL) { _obj = new TYPE(); } //Default constructor.
forward_class(const TYPE& r) : _obj(NULL) { _obj = new TYPE(r); } //Copy constructor.
virtual ~forward_class(){ if(_obj) delete _obj; } //Destructor.
public:
TYPE& operator* (){ return *_obj; } //Dereference to the class.
TYPE* operator->(){ return _obj; } //Class member selection.
operator TYPE (){ return *_obj; } //Cast as class type.
operator TYPE&(){ return *_obj; } //Cast as class type reference.
operator TYPE*(){ return _obj; } //Cast as class type pointer.
};
//<summary>Provides a light-weight wrapper for manipulating xml_node_struct structures.</summary>
class xml_node
{
//Internal Data Members
protected:
xml_node_struct* _root; //Pointer to node root.
xml_node_struct _dummy; //Utility.
//Construction/Destruction
public:
//<summary>Default constructor.</summary>
//<remarks>
// Node root points to a dummy 'xml_node_struct' structure. Test for this
// with 'empty'.
//</remarks>
xml_node(): _root(0)
{
memset(&_dummy,0,sizeof(xml_node_struct));
_dummy.type = node_null;
_dummy.parent = &_dummy;
_root = &_dummy;
}
//<summary>Construct, wrapping the given 'xml_node_struct' pointer.</summary>
//<param name="p">Pointer to node to wrap.</param>
//<remarks>It is possible that 'p' is NULL, so test for this with 'empty'.</remarks>
xml_node(xml_node_struct* p): _root(p) { memset(&_dummy,0,sizeof(xml_node_struct)); }
//<summary>Copy constructor.</summary>
//<param name="r">Reference to node.</param>
//<remarks>
// Only the root pointer is assigned, so both classes now in fact point
// to the same structure.
//</remarks>
xml_node(const xml_node& r): _root(r._root) {}
//<summary>Destructor.</summary>
virtual ~xml_node(){}
//<summary>Attach to the given structure.</summary>
//<param name="p">Pointer to node structure to wrap.</param>
//<returns>Pointer to previous node structure.</returns>
xml_node_struct* attach(xml_node_struct* p)
{
xml_node_struct* prev = _root;
_root = p;
return prev;
}
//Iteration
public:
//<summary>Child node iterator.</summary>
class xml_node_iterator : public xml_iterator<xml_node,long,xml_node*,xml_node&>
{
protected:
forward_class<xml_node> _wrap; //Wrapper for xml_node.
public:
xml_node_iterator() : _wrap(), xml_iterator<xml_node,long,xml_node*,xml_node&>() {} //Default constructor.
xml_node_iterator(xml_node_struct* vref,long sscr = 0) : _wrap(), xml_iterator<xml_node,long,xml_node*,xml_node&>(vref,sscr) { } //Initializing constructor.
xml_node_iterator(const xml_node_iterator& r) : _wrap(), xml_iterator<xml_node,long,xml_node*,xml_node&>(r) { } //Copy constructor.
virtual bool good() //Internal validity.
{
if
(
_vref != 0 && //Pointing to some node.
_vref->child != 0 && //The node has an array of children.
_vref->children > 0 //There are 1 or more children in the array.
)
return true;
return false;
}
virtual bool oob() //Out of bounds check.
{
if
(
!good() || //There is no data over which to iterate.
_sscr < 0 || //Subscript is out of range.
_sscr >= (long)_vref->children
)
return true;
return false;
}
//<summary>Pointer dereference for current xml_node.<summary>
//<returns>
// Reference to the internal xml_node object, which wraps the
// xml_node_struct corresponding to the node at the
// current subscript.
//</returns>
virtual xml_node& operator*()
{
if(!oob()) _wrap->attach(_vref->child[_sscr]);
else _wrap->attach(NULL);
return (xml_node&)_wrap;
}
virtual xml_node* operator->() //Member selection for current xml_node.
{
if(!oob()) _wrap->attach(_vref->child[_sscr]);
else _wrap->attach(NULL);
return (xml_node*)_wrap;
}
};
//<summary>Attribute iterator.</summary>
class xml_attribute_iterator : public xml_iterator<xml_attribute,long,xml_attribute*,xml_attribute&>
{
protected:
forward_class<xml_attribute> _wrap;
public:
xml_attribute_iterator() : _wrap(), xml_iterator<xml_attribute,long,xml_attribute*,xml_attribute&>() {} //Default constructor.
xml_attribute_iterator(xml_node_struct* vref,long sscr = 0) : _wrap(), xml_iterator<xml_attribute,long,xml_attribute*,xml_attribute&>(vref,sscr) { } //Initializing constructor.
xml_attribute_iterator(const xml_attribute_iterator& r) : _wrap(), xml_iterator<xml_attribute,long,xml_attribute*,xml_attribute&>(r) { } //Copy constructor.
virtual bool good() //Internal validity check.
{
if
(
_vref != 0 && //Pointing to some node.
_vref->attribute != 0 && //The node has an array of children.
_vref->attributes > 0 //There are 1 or more children in the array.
)
return true;
return false;
}
virtual bool oob() //Out of bounds check.
{
if
(
!good() || //There is no data over which to iterate.
_sscr < 0 || //Subscript is out of range.
_sscr >= (long)_vref->attributes //For 'end'
)
return true;
return false;
}
//<summary>Pointer dereference for current xml_attribute.</summary>
//<returns>
// Reference to the internal xml_attribute object, which wraps the
// xml_attribute_struct corresponding to the attribute at the
// current subscript.
//</returns>
virtual xml_attribute& operator*()
{
if(!oob()) _wrap->attach(_vref->attribute[_sscr]);
else _wrap->attach(NULL);
return (xml_attribute&)_wrap;
}
//<summary>Member selection for current xml_attribute.</summary>
//<returns></returns>
virtual xml_attribute* operator->()
{
if(!oob()) _wrap->attach(_vref->attribute[_sscr]);
else _wrap->attach(NULL);
return (xml_attribute*)_wrap;
}
};
//<summary>Base iterator type (for child nodes). Same as 'child_iterator'.</summary>
typedef xml_node_iterator iterator;
//<summary>Base iterator type (for child nodes). Same as 'iterator'.</summary>
typedef xml_node_iterator child_iterator;
//<summary>Base iterator type (for sibling nodes). Same as 'iterator'.</summary>
typedef xml_node_iterator sibling_iterator;
//<summary>Attribute iterator type.</summary>
typedef xml_attribute_iterator attribute_iterator;
//<summary>Access the begin iterator for this node's collection of child nodes.</summary>
//<returns>The begin iterator for this node's collection of child nodes.</returns>
//<remarks>Same as 'children_begin'.</remarks>
iterator begin(){ return iterator(_root,0); }
//<summary>Access the end iterator for this node's collection of child nodes.</summary>
//<returns>The end iterator for this node's collection of child nodes.</returns>
//<remarks>Same as 'children_end'.</remarks>
iterator end(){ return iterator(_root,_root->children); }
//<summary>Erase the given node from node's collection of child nodes.</summary>
//<returns>The begin iterator for this node's collection of child nodes.</returns>
//<remarks>Same as 'children_erase'.</remarks>
iterator erase(iterator where){ remove_child((unsigned int)where.subscript()); return iterator(_root,0); }
//<summary>Access the begin iterator for this node's collection of child nodes.</summary>
//<returns>The begin iterator for this node's collection of child nodes.</returns>
//<remarks>Same as 'begin'.</remarks>
child_iterator children_begin(){ return child_iterator(_root,0); }
//<summary>Access the end iterator for this node's collection of child nodes.</summary>
//<returns>The end iterator for this node's collection of child nodes.</returns>
//<remarks>Same as 'end'.</remarks>
child_iterator children_end(){ return child_iterator(_root,_root->children); }
//<summary>Erase the given node from node's collection of child nodes.</summary>
//<returns>The begin iterator for this node's collection of child nodes.</returns>
//<remarks>Same as 'erase'.</remarks>
child_iterator children_erase(child_iterator where){ remove_child((unsigned int)where.subscript()); return child_iterator(_root,0); }
//<summary>Access the begin iterator for this node's collection of attributes.</summary>
//<returns>The begin iterator for this node's collection of attributes.</returns>
attribute_iterator attributes_begin(){ return attribute_iterator(_root,0); }
//<summary>Access the end iterator for this node's collection of attributes.</summary>
//<returns>The end iterator for this node's collection of attributes.</returns>
attribute_iterator attributes_end(){ return attribute_iterator(_root,_root->attributes); }
//<summary>Erase the given attribute from node's collection of attributes.</summary>
//<returns>The begin iterator for this node's collection of attributes.</returns>
attribute_iterator attributes_erase(attribute_iterator where){ remove_attribute((unsigned int)where.subscript()); return attribute_iterator(_root,0); }
//<summary>Access the begin iterator for this node's collection of siblings.</summary>
//<returns>The begin iterator for this node's collection of siblings.</returns>
sibling_iterator siblings_begin(){ if(!empty()) return sibling_iterator(_root->parent,0); return sibling_iterator(); }
//<summary>Access the end iterator for this node's collection of siblings.</summary>
//<returns>The end iterator for this node's collection of siblings.</returns>
sibling_iterator siblings_end(){ if(!empty()) return sibling_iterator(_root->parent,_root->parent->children); return sibling_iterator(); }
//<summary>Erase the given sibling from node's collection of siblings.</summary>
//<returns>The begin iterator for this node's collection of siblings.</returns>
sibling_iterator siblings_erase(sibling_iterator where){ parent().remove_child((unsigned int)where.subscript()); return iterator(_root->parent,0); }
//Overloaded Operators
public:
operator xml_node_struct*(){ return _root; } //Cast as xml_node_struct pointer.
operator void*(){ return (void*)_root; } //Cast root as void*.
xml_node& operator=(const xml_node& r){ _root = r._root; return *this; } //Assign to xml_node_struct pointer.
bool operator==(const xml_node& r){ return (_root == r._root); } //True if this has the same internal xml_node_struct pointer value.
xml_node operator[](unsigned int i){ return child(i); } //Access the child at subscript.
//Node Classification
public:
bool empty() { return (_root == 0 || _root->type == node_null); } //Node pointer is null, or type is node_null. Same as type_null.
bool type_null() { return empty(); } //Node pointer is null, or type is node_null. Same as empty.
bool type_document() { return (_root && _root == _root->parent && _root->type == node_document); } //Node is tree root.
bool type_element() { return (_root && _root->type == node_element); } //Node is an element.
bool type_comment() { return (_root && _root->type == node_comment); } //Node is a comment.
bool type_pcdata() { return (_root && _root->type == node_pcdata); } //Node is PCDATA.
bool type_cdata() { return (_root && _root->type == node_cdata); } //Node is CDATA.
bool type_include() { return (_root && _root->type == node_include); } //Node is INCLUDE.
bool type_pi() { return (_root && _root->type == node_pi); } //Node is a processing instruction.
bool type_doctype() { return (_root && _root->type == node_doctype); } //Node is DOCTYPE.
bool type_dtd_item() { return (_root && _root->type > node_doctype); } //Node is NODE_DTD_*.
bool type_dtd_attlist() { return (_root && _root->type == node_dtd_attlist); } //Node is node_dtd_attlist.
bool type_dtd_element() { return (_root && _root->type == node_dtd_element); } //Node is node_dtd_element.
bool type_dtd_entity() { return (_root && _root->type == node_dtd_entity); } //Node is node_dtd_entity.
bool type_dtd_notation() { return (_root && _root->type == node_dtd_notation); } //Node is node_dtd_notation.
//Member Inventory
public:
bool has_value() { return (!empty() && _root->value != 0); } //Node has data (comment, CDATA or PCDATA).
bool has_child_nodes() { return (!empty() && children() > 0); } //Node has 1 or more children.
bool has_attributes() { return (!empty() && attributes() > 0); } //Node has 1 or more attributes.
bool has_siblings() { return (!empty() && siblings() > 0); } //Node has one or more siblings.
bool has_name() { return (!empty() && _root->name != 0); } //Node has a name.
bool has_name(const std::string& name) const { return has_name(name.c_str()); } //Node is named 'name'.
bool has_attribute(const std::string& name) { return has_attribute(name.c_str()); } //Node has an attribute named 'name'.
#ifdef PUGOPT_NONSEG
bool has_name(const TCHAR* name) const { return (name && _root && _root->name && _tcsncmp(_root->name,name,_root->name_size)==0); } //Node is named 'name'.
#else
bool has_name(const TCHAR* name) const { return (name && _root && _root->name && strcmpwild(name,_root->name)==0); } //Node is named 'name'.
#endif
bool has_attribute(const TCHAR* name){ return (mapto_attribute_idx(name) > -1); } //Node has an attribute named name.
//Member Accessors
public:
#ifdef PUGOPT_NONSEG
//<summary>Access node name if any.</summary>
//<returns>Name, or dummy value if the no name.</returns>
//<remarks>Only returns up to 'PUGDEF_ELEM_NAME_SIZE' chars of name.</remarks>
const TCHAR* name()
{
static TCHAR temp[PUGDEF_ELEM_NAME_SIZE] = {0};
if(has_name())
{
_tcsncpy(temp,_root->name,_root->name_size);
temp[_root->name_size<PUGDEF_ELEM_NAME_SIZE?_root->name_size:(PUGDEF_ELEM_NAME_SIZE-1)] = 0;
return temp;
}
return _T("");
}
unsigned int name_size(){ return (has_name()) ? _root->name_size : 0; } //Get node name length if any, else 0.
unsigned int value_size(){ return (has_value()) ? _root->value_size : 0; } //Get node value length if any, else 0.
inline bool matches_attribute_name(const TCHAR* name,const unsigned int namelen,const int i) const { return (_tcsncmp(name,_root->attribute[i]->name,max(namelen,_root->attribute[i]->name_size))==0); } //There is an attribute at 'i' named 'name'.
inline bool matches_child_name(const TCHAR* name,const unsigned int namelen,const int i) const { return (_tcsncmp(name,_root->child[i]->name,max(namelen,_root->child[i]->name_size))==0); } //There is a child at 'i' named 'name'.
inline bool matches_name(const TCHAR* name,const unsigned int namelen,xml_node_struct* node) const { return (_tcsncmp(name,node->name,max(namelen,node->name_size))==0); } //This is named 'name'.
inline bool matches_value(const TCHAR* data,const unsigned int datalen,xml_node_struct* node) const { return (_tcsncmp(data,node->value,max(datalen,node->value_size))==0); } //This is valued 'value'.
inline bool matches_attribute_name(const TCHAR* name,const unsigned int namelen,xml_attribute_struct* attr) const { return (_tcsncmp(name,attr->name,max(namelen,attr->name_size))==0); } //The given attribute is named 'name'.
inline bool matches_attribute_name_value(const TCHAR* value,const unsigned int valulen,xml_attribute_struct* attr) const { return (_tcsncmp(value,attr->value,max(valulen,attr->value_size))==0); } //The given attribute is valued 'value'.
#else
const TCHAR* name(){ return (has_name()) ? _root->name : _T(""); } //Access pointer to node name if any, else empty string.
inline bool matches_attribute_name(const TCHAR* name,const unsigned int i) const { return (strcmpwild(name,_root->attribute[i]->name)==0); } //There is an attribute at 'i' named 'name'.
inline bool matches_child_name(const TCHAR* name,const unsigned int i) const { return (strcmpwild(name,_root->child[i]->name)==0); } //There is a child at 'i' named 'name'.
inline bool matches_name(const TCHAR* name,xml_node_struct* node) const { return (strcmpwild(name,node->name)==0); } //This is named 'name'.
inline bool matches_value(const TCHAR* data,xml_node_struct* node) const { return (strcmpwild(data,node->value)==0); } //This is valued 'value'.
inline bool matches_attribute_name(const TCHAR* attribute,xml_attribute_struct* attr) const { return (strcmpwild(attribute,attr->name)==0); } //The given attribute is named 'name'.
inline bool matches_attribute_name_value(const TCHAR* value,xml_attribute_struct* attr) const { return (strcmpwild(value,attr->value)==0); } //The given attribute is valued 'value'.
#endif
xml_node_type type() const { return (_root) ? (xml_node_type)_root->type : node_null; } //Access node entity type.
const TCHAR* value() { return (has_value()) ? _root->value : _T(""); } //Access pointer to data if any, else empty string.
unsigned int children() const { return _root->children; } //Access node's child count.
xml_node child(unsigned int i){ return (i < children()) ? xml_node(_root->child[i]) : xml_node(); } //Access child node at subscript as xml_node or xml_node(NULL) if bad subscript.
unsigned int attributes() const { return _root->attributes; } //Access node's attribute count.
xml_attribute attribute(unsigned int i){ return (i < attributes()) ? xml_attribute(_root->attribute[i]) : xml_attribute(); } //Access attribute at subscript if any, else empty attribute.
//<summary>Access or create the attribute having 'name'.</summary>
//<param name="name">Name of attribute to access/create.</param>
//<returns>Reference to xml_attribute wrapper.</returns>
xml_attribute attribute(const std::string& name){ return attribute(name.c_str()); }
//<summary>Access or create the attribute having 'name'.</summary>
//<param name="name">Name of attribute to access/create.</param>
//<returns>Reference to xml_attribute wrapper.</returns>
xml_attribute attribute(const TCHAR* name)
{
xml_attribute_struct* attr = mapto_attribute_ptr(name);
if(!attr) attr = append_attribute(name,_T(""));
return xml_attribute(attr);
}
const unsigned int siblings(){ return (!type_document()) ? _root->parent->children : 0; } //Access node's sibling count (parent's child count).
xml_node sibling(unsigned int i){ return (!type_document() && i < siblings()) ? xml_node(_root->parent->child[i]) : xml_node(); } //Access sibling node at subscript as xml_node or xml_node(NULL) if bad subscript.
xml_node parent(){ return (!type_document()) ? xml_node(_root->parent) : xml_node(); } //Access node's parent if any, else xml_node(NULL)
//<summary>Return the first child that has data's data. If none, return NULL.</summary>
//<param name="value">Returns a copy of the data.</param>
//<param name="valuelen">Specifies the maximum number of characters to copy into value.</param>
//<returns>Pointer to value if exists, else NULL.</returns>
//<remarks>
// Used to get the PCDATA for the current element. This handles elements
// like: <LINE><STAGEDIR>Aside</STAGEDIR>Thy father,
// Pompey, would ne'er have</LINE>, where 'this' points to <LINE>.
//</remarks>
TCHAR* child_value(TCHAR* value,const unsigned int valuelen)const
{
if(_root->children)
{
for(register unsigned int i=0; i < _root->children; ++i)
{
xml_node_struct* node = _root->child[i];
if(node->value)
{
const unsigned int n =
#ifdef PUGOPT_NONSEG
(std::min)(valuelen,node->value_size);
#else
(std::min)(valuelen,unsigned(_tcslen(node->value)));
#endif
_tcsncpy(value,node->value,n);
value[n] = 0;
break;
}
}
return value;
}
return NULL;
}
//Name-To-Object Mapping
public:
//<summary>Map an attribute name to a pointer to that attribute, if found.</summary>
//<param name="name">Reference to name of attribute to find.</param>
//<returns>Pointer to attribute, or NULL if not found.</returns>
//<remarks>Implement your own hash table if you have a great many attributes.</remarks>
xml_attribute_struct* mapto_attribute_ptr(const std::string& name){ return mapto_attribute_ptr(name.c_str()); }
//<summary>Map an attribute name to a pointer to that attribute, if found.</summary>
//<param name="name">Pointer to name of attribute to find.</param>
//<returns>Pointer to attribute, or NULL if not found.</returns>
//<remarks>Implement your own hash table if you have a great many attributes.</remarks>
xml_attribute_struct* mapto_attribute_ptr(const TCHAR* name)
{
if(!_root || !name) return NULL;
register unsigned int n = _root->attributes;
#ifdef PUGOPT_NONSEG
const int namelen = _tcslen(name);
#endif
for(register unsigned int i=0; i<n; ++i)
#ifdef PUGOPT_NONSEG
if(matches_attribute_name(name,namelen,i))
#else
if(matches_attribute_name(name,i))
#endif
return _root->attribute[i];
return NULL;
}
//<summary>Map an attribute name to the index of that attribute, if found.</summary>
//<param name="name">Pointer to name of attribute to find.</param>
//<returns>Index of attribute, or -1 if not found.</returns>
//<remarks>Implement your own hash table if you have a great many attributes.</remarks>
int mapto_attribute_idx(const TCHAR* name)
{
if(!_root || !name) return -1;
register unsigned int n = _root->attributes;
#ifdef PUGOPT_NONSEG
const int namelen = _tcslen(name);
#endif
for(register unsigned int i=0; i<n; ++i)
#ifdef PUGOPT_NONSEG
if(matches_attribute_name(name,namelen,i))
#else
if(matches_attribute_name(name,i))
#endif
return i;
return -1;
}
//<summary>Map a child name to a pointer to the first instance, if found.</summary>
//<param name="name">Reference to name of child to find.</param>
//<returns>Index of child, or -1 if not found.</returns>
//<remarks>Implement your own hash table if you have a great many children.</remarks>
xml_node_struct* mapto_child_ptr(const std::string& name){ return mapto_child_ptr(name.c_str()); }
//<summary>Map a child name to a pointer to the first instance, if found.</summary>
//<param name="name">Pointer to name of child to find.</param>
//<returns>Index of child, or -1 if not found.</returns>
//<remarks>Implement your own hash table if you have a great many children.</remarks>
xml_node_struct* mapto_child_ptr(const TCHAR* name)
{
if(!_root || !name) return NULL;
register unsigned int n = _root->children;
#ifdef PUGOPT_NONSEG
const int namelen = _tcslen(name);
#endif
for(register unsigned int i=0; i<n; ++i)
{
if
(
_root->child[i]->name &&
#ifdef PUGOPT_NONSEG
matches_child_name(name,namelen,i)
#else
matches_child_name(name,i)
#endif
)
return _root->child[i];
}
return NULL;
}
//<summary>Map a child name to the index of the first instance, if found.</summary>
//<param name="name">Reference to name of child to find.</param>
//<returns>Index of child, or -1 if not found.</returns>
//<remarks>Implement your own hash table if you have a great many children.</remarks>
int mapto_child_idx(const std::string& name){ return mapto_child_idx(name.c_str()); }
//<summary>Map a child name to the index of the first instance, if found.</summary>
//<param name="name">Pointer to name of child to find.</param>
//<returns>Index of child, or -1 if not found.</returns>
//<remarks>Implement your own hash table if you have a great many children.</remarks>
int mapto_child_idx(const TCHAR* name)
{
if(!_root || !name) return -1;
register unsigned int n = _root->children;
#ifdef PUGOPT_NONSEG
const int namelen = _tcslen(name);
#endif
for(register unsigned int i=0; i<n; ++i)
{
if
(
_root->child[i]->name &&
#ifdef PUGOPT_NONSEG
matches_child_name(name,namelen,i)
#else
matches_child_name(name,i)
#endif
)
return i;
}
return -1;
}
//Traversal Helpers
public:
//<summary>Find all elements having the given name.</summary>
//<param name="name">Reference to name of child to find.</param>
//<param name="found">Reference to xml_node_list or pointer_array to receive the matching elements.
void all_elements_by_name(const std::string& name,pointer_array& found){ all_elements_by_name(name.c_str(),found); }
//<summary>Find all elements having the given name.</summary>
//<param name="name">Pointer to name of child to find.</param>
//<param name="found">Reference to xml_node_list or pointer_array to receive the matching elements.</param>
void all_elements_by_name(const TCHAR* name,pointer_array& found)
{
if(empty() || !name) return; //Invalid node, so fail.
if(_root->children > 0) //Has children.
{
#ifdef PUGOPT_NONSEG
const unsigned int namelen = _tcslen(name);
#endif
register unsigned int n = _root->children; //For each child.
for(register unsigned int i=0; i<n; ++i)
{
if
(
_root->child[i] && //There is a child at i.
_root->child[i]->name && //The child has a name.
#ifdef PUGOPT_NONSEG
matches_child_name(name,namelen,i)
#else
matches_child_name(name,i)
#endif
)
found.push_back(_root->child[i]); //push_back it to the array.
if(_root->child[i]->children) //If there are children.
{
xml_node subsearch(_root->child[i]); //Wrap it up for ease.
subsearch.all_elements_by_name(name,found); //Find any matching children.
}
}
}
}
//<summary>
// Recursively-implemented depth-first find the first matching element.
// Use for shallow drill-downs.
//</summary>
//<param name="name">Const reference to name of element to find.</param>
//<returns>Valid xml_node if such element named 'name' is found.</returns>
//<remarks>xml_node may be invalid if not found; test with 'empty'.</remarks>
xml_node first_element_by_name(const std::string& name){ return first_element_by_name(name.c_str()); }
//<summary>
// Recursively-implemented depth-first find the first matching element.
// Use for shallow drill-downs.
//</summary>
//<param name="name">Pointer to name of element to find.</param>
//<returns>Valid xml_node if such element named 'name' is found.</returns>
//<remarks>xml_node may be invalid if not found; test with 'empty'.</remarks>
xml_node first_element_by_name(const TCHAR* name)
{
if(empty() || !name) return xml_node(); //Invalid node, so fail.
if(_root->children > 0) //Has children.
{
register unsigned int n = _root->children; //For each child.
#ifdef PUGOPT_NONSEG
const int namelen = _tcslen(name);
#endif
for(register unsigned int i=0; i<n; ++i)
{
if
(
_root->child[i]->name &&
#ifdef PUGOPT_NONSEG
matches_child_name(name,namelen,i)
#else
matches_child_name(name,i)
#endif
)
return xml_node(_root->child[i]);
else if(_root->child[i]->children)
{
xml_node subsearch(_root->child[i]); //Wrap it up for ease.
xml_node found = subsearch.first_element_by_name(name);
if(!found.empty()) return found; //Found.
}
}
}
return xml_node(); //Not found.
}
//<summary>
// Recursively-implemented depth-first find the first matching element
// also having matching PCDATA.
//</summary>
//<param name="name">Reference to name of element to find.</param>
//<param name="value">Reference to PCDATA to find.</param>
//<returns>Valid xml_node if such element named 'name' is found with PCDATA 'value'.</returns>
//<remarks>xml_node may be invalid if not found; test with 'empty'.</remarks>
xml_node first_element_by_value(const std::string& name,const std::string& value){ return first_element_by_value(name.c_str(),value.c_str()); }
//<summary>
// Recursively-implemented depth-first find the first matching element
// also having matching PCDATA.
//</summary>
//<param name="name">Pointer to name of element to find.</param>
//<param name="value">Pointer to PCDATA to find.</param>
//<returns>Valid xml_node if such element named 'name' is found with PCDATA 'value'.</returns>
//<remarks>xml_node may be invalid if not found; test with 'empty'.</remarks>
xml_node first_element_by_value(const TCHAR* name,const TCHAR* value)
{
if(empty() || !name || !value) return xml_node(); //Invalid node, so fail.
if(_root->children > 0) //Has children.
{
register unsigned int n = _root->children; //For each child.
#ifdef PUGOPT_NONSEG
const unsigned int namelen = _tcslen(name);
const unsigned int valulen = _tcslen(value);
#endif
for(register unsigned int i=0; i<n; ++i)
{
if
(
_root->child[i] && //There is a child at i.
_root->child[i]->name && //The child has a name.
#ifdef PUGOPT_NONSEG
matches_child_name(name,namelen,i)
#else
matches_child_name(name,i)
#endif
)
{
register unsigned int m = _root->child[i]->children; //For each child of child.
for(register unsigned int j=0; j<m; ++j)
{
if
(
_root->child[i]->child[j] && //There is a child at j.
_root->child[i]->child[j]->type == node_pcdata && //It is of the PCDATA type.
_root->child[i]->child[j]->value && //It has data.
#ifdef PUGOPT_NONSEG
matches_value(value,valulen,_root->child[i]->child[j])
#else
matches_value(value,_root->child[i]->child[j])
#endif
)
return xml_node(_root->child[i]); //Wrap it up and return.
}
}
else if(_root->child[i] && _root->child[i]->children) //The child has children.
{
xml_node subsearch(_root->child[i]); //Wrap it up for ease.
xml_node found = subsearch.first_element_by_value(name,value); //Search any children.
if(!found.empty()) return found; //Found.
}
}
}
return xml_node(); //Not found.
}
//<summary>
// Recursively-implemented depth-first find the first matching element
// also having matching attribute.
//</summary>
//<param name="name">Reference to name of element to find.</param>
//<param name="attr_name">Reference to name of attribute to find.</param>
//<param name="attr_value">Reference to attribute value to find.</param>
//<returns>Valid xml_node if such element named 'name' is found.</returns>
//<remarks>xml_node may be invalid if not found; test with 'empty'.</remarks>
xml_node first_element_by_attribute(const std::string& name,const std::string& attr_name,const std::string& attr_value){ return first_element_by_attribute(name.c_str(),attr_name.c_str(),attr_value.c_str()); }
//<summary>
// Recursively-implemented depth-first find the first matching element
// also having matching attribute.
//</summary>
//<param name="name">Pointer to name of element to find.</param>
//<param name="attr_name">Pointer to name of attribute to find.</param>
//<param name="attr_value">Pointer to attribute value to find.</param>
//<returns>Valid xml_node if such element named 'name' is found.</returns>
//<remarks>xml_node may be invalid if not found; test with 'empty'.</remarks>
xml_node first_element_by_attribute(const TCHAR* name,const TCHAR* attr_name,const TCHAR* attr_value)
{
if(empty() || !name || !attr_name || !attr_value) return xml_node(); //Invalid data, so fail.
if(_root->children > 0) //Has children.
{
#ifdef PUGOPT_NONSEG
const unsigned int namelen = _tcslen(name);
const unsigned int attrlen = _tcslen(attr_name);
const unsigned int valulen = _tcslen(attr_value);
#endif
register unsigned int n = _root->children; //For each child.
for(register unsigned int i=0; i<n; ++i)
{
if
(
_root->child[i] && //There is a child at i.
_root->child[i]->name && //The child has a name.
#ifdef PUGOPT_NONSEG
matches_name(name,namelen,_root->child[i])
#else
matches_name(name,_root->child[i])
#endif
)
{
register unsigned int m = _root->child[i]->attributes; //For each attribute of child.
for(register unsigned int j=0; j<m; ++j)
{
if
(
_root->child[i]->attribute[j] && //There is an attribute at j.
_root->child[i]->attribute[j]->name && //The attribute has a name.
#ifdef PUGOPT_NONSEG
matches_attribute_name(attr_name,attrlen,_root->child[i]->attribute[j]) &&
#else
matches_attribute_name(attr_name,_root->child[i]->attribute[j]) &&
#endif
_root->child[i]->attribute[j]->value && //The attribute has a value.
#ifdef PUGOPT_NONSEG
matches_attribute_name_value(attr_value,valulen,_root->child[i]->attribute[j])
#else
matches_attribute_name_value(attr_value,_root->child[i]->attribute[j])
#endif
)
return xml_node(_root->child[i]); //Wrap it up and return.
}
}
else if(_root->child[i] && _root->child[i]->children)
{
xml_node subsearch(_root->child[i]); //Wrap it up for ease.
xml_node found = subsearch.first_element_by_attribute(name,attr_name,attr_value); //Search any children.
if(!found.empty()) return found; //Found.
}
}
}
return xml_node(); //Not found.
}
//<summary>
// Recursively-implemented depth-first find the first matching entity.
// Use for shallow drill-downs.
//</summary>
//<param name="name">Pointer to name of element to find.</param>
//<returns>Valid xml_node if such element named 'name' is found.</returns>
//<remarks>xml_node may be invalid if not found; test with 'empty'.</remarks>
xml_node first_node(xml_node_type type)
{
if(!_root) return xml_node();
if(_root->children > 0) //Has children.
{
register unsigned int n = _root->children; //For each child.
for(register unsigned int i=0; i<n; ++i)
{
if(_root->child[i]->type==type)
return xml_node(_root->child[i]);
else if(_root->child[i]->children)
{
xml_node subsearch(_root->child[i]);
xml_node found = subsearch.first_node(type);
if(!found.empty()) return found; //Found.
}
}
}
return xml_node(); //Not found.
}
//<summary>Move to the absolute root of the document tree.</summary>
//<returns>True if the current node is valid.</returns>
//<remarks>Member '_root' may now point to absolute root of the document.</remarks>
bool moveto_root()
{
if(empty()) return false; //Nowhere to go.
while(!type_document()) _root = _root->parent; //Keep stepping out until we hit the root.
return true; //Success.
}
//<summary>Move to the current node's parent.</summary>
//<returns>true if there is a parent and cursor is not parent, and cursor points thereto.</returns>
//<remarks>'_root' may now point to parent.</remarks>
bool moveto_parent()
{
if(empty() || type_document()) return false; //Invalid, or at the root (has no parent).
_root = _root->parent; //Move to parent.
return true; //Success.
}
//<summary>
// Move to the current node's sibling at subscript. Equivalent to
// 'moveto_child' following 'moveto_parent'.
//</summary>
//<param name="i">Subscript of sibling to move cursor to.</param>
//<returns>True if valid subscript, and cursor points thereto.</returns>
//<remarks>If matching co-node was found, '_root' points thereto.</remarks>
bool moveto_sibling(unsigned int i)
{
if(empty()) return false; //Nowhere to go.
xml_node_struct* restore = _root; //Save position in case invalid subscript & we want to restore.
if(moveto_parent()) //Try to move to parent.
{
if(i < children()) //Subscript is in range. (Assume parent *does* have children.)
{
_root = _root->child[i]; //Move to child at subscript ('sibling').
return true; //Success.
}
}
_root = restore; //Bad subscript, or parent move; restore.
return false;
}
//<summary>Move to the current node's first sibling matching given name.</summary>
//<param name="name">Element name of sibling to move to.</param>
//<returns>True if sibling was found, and cursor points thereto.</returns>
//<remarks>If matching co-node was found, '_root' points thereto.</remarks>
bool moveto_first_sibling(const std::string& name){ return moveto_first_sibling(name.c_str()); }
//<summary>Move to the current node's first sibling matching given name.</summary>
//<param name="name">Element name of sibling to move to.</param>
//<returns>True if sibling was found, and cursor points thereto.</returns>
//<remarks>If matching co-node was found, '_root' points thereto.</remarks>
bool moveto_first_sibling(const TCHAR* name)
{
if(empty() || !name) return false; //Nowhere to go, or nothing to find.
xml_node_struct* restore = _root; //Save position in case invalid subscript & we want to restore.
if(moveto_parent()) //Try to move to parent.
{
#ifdef PUGOPT_NONSEG
const unsigned int namelen = _tcslen(name);
#endif
register unsigned int n = children(); //Search for matching name
for(register unsigned int i=0; i<n; ++i)
{
//NF 24 Jan 2003 Changed to get child(i) just once per iteration.
xml_node node = child(i); //Access child node at subscript as xml_node or xml_node(NULL) if bad subscript.
if(node.type_element()||node.type_pi()) //Other types won't have names.
{
#ifdef PUGOPT_NONSEG
if(_tcsncmp(name,node.name(),max(namelen,node.name_size()))==0) //Do names match?
#else
if(strcmpwild(name,node.name())==0) //Do names match?
#endif
{
_root = node; //Move there.
return true; //Success.
}
}
}
}
_root = restore; //Failed to locate any such sibling; restore position.
return false;
}
//<summary>Move to the current node's child at subscript.</summary>
//<param name="i">Subscript of child to move cursor to.</param>
//<returns>true if valid subscript, and cursor points thereto.</returns>
//<remarks>If matching sub-node was found, '_root' points thereto.</remarks>
bool moveto_child(unsigned int i)
{
if(empty()) return false; //Null, so no children.
if(has_child_nodes() && i < children()) //Has children and subscript is in bounds.
{
_root = child(i); //Move to the child at i.
return true; //Success.
}
return false; //Failure.
}
//<summary>Move to the current node's child matching given name.</summary>
//<param name="name">Element name of child to move to if found.</param>
//<returns>True if child was found, and cursor points thereto.</returns>
//<remarks>If matching sub-node was found, '_root' points thereto.</remarks>
bool moveto_child(const std::string& name){ return moveto_child(name.c_str()); }
//<summary>Move to the current node's child matching given name.</summary>
//<param name="name">Element name of child to move to if found.</param>
//<returns>True if child was found, and cursor points thereto.</returns>
//<remarks>If matching sub-node was found, '_root' points thereto.</remarks>
bool moveto_child(const TCHAR* name)
{
if(empty() || !name || !has_child_nodes()) return false; //The node is null, a name was not specified, or node has no children.
#ifdef PUGOPT_NONSEG
const unsigned int namelen = _tcslen(name);
#endif
register unsigned int n = children(); //For each child.
for(register unsigned int i=0; i<n; ++i)
{
//NF 24 Jan 2003: Changed to get child(i) just once per iteration.
xml_node node = child(i); //Access child node at subscript as xml_node or xml_node(NULL) if bad subscript.
#ifdef PUGOPT_NONSEG
if(_tcsncmp(name,node.name(),max(namelen,node.name_size()))==0) //Do names match?
#else
if(strcmpwild(name,node.name())==0) //If the name is identical with 'name'.
#endif
{
_root = node; //Move to it.
return true; //Success.
}
}
return false; //Failure.
}
//<summary>Move to the current node's next sibling by position and name.</summary>
//<param name="name">Name of sibling to move to if found.</param>
//<returns>True if there is a next sibling, and cursor points thereto.</returns>
bool moveto_next_sibling(const std::string& name){ return moveto_next_sibling(name.c_str()); }
//<summary>Move to the current node's next sibling by position and name.</summary>
//<param name="name">Name of sibling to move to if found.</param>
//<returns>True if there is a next sibling, and cursor points thereto.</returns>
bool moveto_next_sibling(const TCHAR* name)
{
if(empty() || type_document() || !_root->parent || !name) return false; //Null, or at root, or no name, so there are no valid matches.
#ifdef PUGOPT_NONSEG
const unsigned int namelen = _tcslen(name);
#endif
register unsigned int n = _root->parent->children; //For each child of parent.
for(register unsigned int i=0; i<(n-1); ++i)
{
if
(
_root->parent->child[i] && //There is a child at i.
_root->parent->child[i] == _root && //The child is identical with this node.
i < (n-1) //This is not the last child.
)
{
for(++i; i<n; ++i) //For each following child.
{
if
(
_root->parent->child[i] && //There is a child at i.
_root->parent->child[i]->name && //The child's name is not null.
#ifdef PUGOPT_NONSEG
matches_name(name,namelen,_root->parent->child[i])
#else
matches_name(name,_root->parent->child[i])
#endif
)
{
moveto_sibling(i); //Move to it.
return true; //Success.
}
}
}
}
return false; //Failure.
}
//<summary>Move to the current node's next sibling by position.</summary>
//<returns>True if there is a next sibling, and cursor points thereto.</returns>
bool moveto_next_sibling()
{
if(empty() || type_document() || !_root->parent) return false; //Null or at root, so there are no valid siblings.
register unsigned int n = _root->parent->children; //For each child of parent (each sibling).
for(register unsigned int i=0; i<(n-1); ++i)
{
if
(
_root->parent->child[i] && //There is a child at i.
_root->parent->child[i] == _root && //The child is identical with this node.
i < (n-1) //This is not the last child.
)
{
for(++i; i<n; ++i) //For each following child.
{
if(_root->parent->child[i]) //There is a child at i.
{
moveto_sibling(i); //Move to it.
return true; //Success.
}
}
}
}
return false; //Failure.
}
//<summary>Compile the absolute node path from root as a text string.</summary>
//<param name="delimiter">Delimiter string to insert between element names.</param>
//<returns>Path string (e.g. with '/' as delimiter, '/document/.../this'.</returns>
std::string path(const TCHAR* delimiter = _T("/"))
{
TCHAR* path = NULL; //Current path.
TCHAR* temp; //Temporary pointer.
xml_node cursor = *this; //Make a copy.
#ifdef PUGOPT_NONSEG
unsigned int destlen = 0;
strcatgrown_impl(&path,cursor.name(),destlen,cursor.name_size()); //Get this name.
#else
strcatgrow(&path,cursor.name()); //Get this name.
#endif
while(cursor.moveto_parent() && !cursor.type_document()) //Loop to parent (stopping on actual root because it has no name).
{
temp = NULL; //Mark as null so 'strcatgrow' will allocate memory.
#ifdef PUGOPT_NONSEG
destlen = 0;
strcatgrown_impl(&temp,cursor.name(),destlen,cursor.name_size()); //Append next element name.
#else
strcatgrow(&temp,cursor.name()); //Append next element name.
#endif
strcatgrow(&temp,delimiter); //Append delimiter.
strcatgrow(&temp,path); //Append current path.
free(path); //Free the old path.
path = temp; //Set path as new string.
}
temp = NULL;
strcatgrow(&temp,delimiter); //Prepend final delimiter.
strcatgrow(&temp,path); //Append current path.
free(path); //Free the old path.
std::string returns = temp; //Set path as new string.
free(temp);
return returns; //Return the path;
}
//<summary>Search for a node by path.</summary>
//<param name="path">
// Path string; e.g. './foo/bar' (relative to node), '/foo/bar' (relative
// to root), '../foo/bar' (pop relative position).
//</param>
//<param name="delimiter">Delimiter string to use in tokenizing path.</param>
//<returns>Matching node, or xml_node(NULL) if not found.</returns>
xml_node first_element_by_path(const std::string& path,const std::string& delimiter = _T("/")){ return first_element_by_path(path.c_str(),delimiter.c_str()); }
//<summary>Search for a node by path.</summary>
//<param name="path">
// Path string; e.g. './foo/bar' (relative to node), '/foo/bar' (relative
// to root), '../foo/bar' (pop relative to position).
//</param>
//<param name="delimiter">Delimiter string to use in tokenizing path.</param>
//<returns>Matching node, or xml_node(NULL) if not found.</returns>
//<remarks>To-do: Support XPath-style queries.</remarks>
xml_node first_element_by_path(const TCHAR* path,const TCHAR* delimiter = _T("/"))
{
if(!path) return xml_node();
TCHAR* temp = NULL;
pointer_array path_segments; //Array of path segments.
xml_node found = *this; //Current search context.
strcatgrow(&temp,path);
TCHAR* name = _tcstok(temp,delimiter);
while(name) //Tokenize the whole path.
{
path_segments.push_back((void*)name); //push_back it to array.
name = _tcstok(NULL,delimiter); //Get the next token,
}
register unsigned int n = path_segments.size();
if(n == 0) return xml_node(); //Return null node if no path segments.
if(path[0]==delimiter[0]) found.moveto_root(); //Absolute path; e.g. '/foo/bar'
for(register unsigned int i = 0; i<n; ++i) //For each path segment.
{
name = (TCHAR*)path_segments.at(i);
if(name)
{
if(*name==_T('.')) //Is '.' or '..'
{
if(_tcscmp(name,_T(".."))==0) found.moveto_parent(); //Pop.
else continue; //Ignore '.' since it is redundant if path is './path'.
}
else
{
register unsigned int j, m = found.children(); //For each child.
for(j=0; j<m; ++j)
{
if(found.child(j).has_name(name)) //Name matches?
{
found = found.child(j); //Move to this child.
goto NEXT_ELEM; //Search next path segment.
}
}
if(found.moveto_next_sibling(found.name())) //Find next sibling having same name.
{
if(i > 0) --i; //Try the previous path segment.
goto NEXT_ELEM;
}
else //Move to parent to search further.
{
if(!found.type_document() && found.moveto_parent() && !found.type_document()) //Not root and stepped to parent and parent is not root.
{
if(i > 0) --i; //Try the previous path segment.
if(found.moveto_next_sibling(found.name())) //Try to find next sibling having same name.
{
if(i > 0) --i; //Try the previous path segment.
goto NEXT_ELEM;
}
}
}
}
}
NEXT_ELEM:;
if(found.type_document()) //Can't move up any higher, so fail.
{
free(temp); //Got to free this.
return xml_node(); //Return null node.
}
}
free(temp); //Got to free this.
return found; //Return the matching node.
}
//<summary>Recursively traverse the tree.</summary>
//<param name="walker">Reference to tree walker derived from xml_tree_walker.</param>
//<returns>True if traversal was not halted by xml_tree_walker::for_each() callback.</returns>
bool traverse(xml_tree_walker& walker)
{
if(walker.depth() == 0 && !walker.begin(*this)) return false; //Send the callback for begin traverse if depth is zero.
if(!empty()) //Don't traveres if this is a null node.
{
walker.push(); //Increment the walker depth counter.
register unsigned int n = _root->children; //For each child.
for(register unsigned int i=0; i<n; ++i)
{
if(_root->child[i]) //There is a child at i.
{
xml_node subsearch(_root->child[i]); //Wrap it.
if(!(walker.for_each(subsearch) && subsearch.traverse(walker)))
return false; //Traversal was aborted.
}
}
walker.pop(); //Decrement the walker depth counter.
}
if(walker.depth() == 0 && !walker.end(*this)) return false; //Send the callback for end traverse if depth is zero.
return true;
}
//Editorial Helpers
public:
//<summary>Set element name.</summary>
//<param name="new_name">New element name.</param>
//<returns>Success.</returns>
bool name(const std::string& new_name){ return name(new_name.c_str()); }
//<summary>Set element name.</summary>
//<param name="new_name">New element name.</param>
//<returns>Success.</returns>
bool name(const TCHAR* new_name)
{
if((type_element() || type_pi()) && new_name)
#ifdef PUGOPT_NONSEG
return strcpyinsitu(&_root->name,new_name,&_root->name_insitu,_root->name_size );
#else
return strcpyinsitu(&_root->name,new_name,&_root->name_insitu);
#endif
return false;
}
//<summary>Set node data.</summary>
//<param name="value">New data (PCDATA, CDATA, or comment) value.</param>
//<returns>Success.</returns>
bool value(const std::string& new_value){ return value(new_value.c_str()); }
//<summary>Set node data.</summary>
//<param name="value">New data (PCDATA, CDATA, or comment) value.</param>
//<returns>Success.</returns>
bool value(const TCHAR* new_value)
{
if((type_pcdata() || type_cdata() || type_comment()) && new_value)
#ifdef PUGOPT_NONSEG
return strcpyinsitu(&_root->value,new_value,&_root->value_insitu,_root->value_size);
#else
return strcpyinsitu(&_root->value,new_value,&_root->value_insitu);
#endif
return false;
}
//<summary>Remove attribute at the given subscript.</summary>
//<param name="i">Subscript.</param>
//<returns>Success.</returns>
bool remove_attribute(unsigned int i)
{
unsigned int n = _root->attributes;
if(i < n)
{
xml_attribute_struct* temp = _root->attribute[i];
--n;
for(unsigned int j=i; j<n; ++j)
_root->attribute[j] = _root->attribute[j+1];
_root->attribute[n] = NULL;
if(!temp->name_insitu) free(temp->name);
if(!temp->value_insitu) free(temp->value);
free(temp);
--_root->attributes;
return true;
}
return false;
}
//<summary>Remove attribute having the given name.</summary>
//<param name="name">Name of attribute to delete.</param>
//<returns>Success.</returns>
bool remove_attribute(const std::string& name){ return remove_attribute(name.c_str()); }
//<summary>Remove attribute having the given name.</summary>
//<param name="name">Name of attribute to delete.</param>
//<returns>Success.</returns>
bool remove_attribute(const TCHAR* name)
{
int i = mapto_attribute_idx(name);
if(i > -1) return remove_attribute((unsigned int)i);
return false;
}
//<summary>Append a new attribute to the node list of attributes.</summary>
//<param name="name">Name.</param>
//<param name="value">Value thereof.</param>
//<returns>Attribute structure wrapper.</returns>
//<remarks>Pointer space may be grown, memory for name/value members allocated.</remarks>
xml_attribute append_attribute(const std::string& name,const std::string& value){ return append_attribute(name.c_str(),value.c_str()); }
//<summary>Append a new attribute to the node list of attributes.</summary>
//<param name="name">Name.</param>
//<param name="value">Value thereof.</param>
//<returns>Attribute structure wrapper.</returns>
//<remarks>Pointer space may be grown, memory for name/value members allocated.</remarks>
xml_attribute append_attribute(const TCHAR* name,const TCHAR* value)
{
if(!name || !value) return xml_attribute(); //We must have both to proceed.
xml_attribute_struct* p = pug::append_attribute(_root,1); //Append/allocate a new attribute structure.
if(p) //If append/allocate succeeded.
{
#ifdef PUGOPT_NONSEG
strcatgrown(&p->name,name,p->name_size); //Append the name.
strcatgrown(&p->value,value,p->value_size); //Append the name.
#else
strcatgrow(&p->name,name); //Append the name.
strcatgrow(&p->value,value); //Append the name.
#endif
p->name_insitu = p->value_insitu = false; //Mark as not part of original parse string.
return xml_attribute(p); //Success.
}
return xml_attribute(); //Failure; return an empty.
}
//<summary>Append a new attribute of type long to the node list of attributes.</summary>
//<param name="name">Name.</param>
//<param name="value">Value thereof.</param>
//<returns>Attribute structure wrapper.</returns>
//<remarks>Pointer space may be grown, memory for name/value members allocated.</remarks>
xml_attribute append_attribute(const TCHAR* name,long value)
{
if(!name) return false;
TCHAR temp[32] = {0};
_stprintf(temp,_T("%ld"),value);
return append_attribute(name,temp);
}
//<summary>Append a new attribute of type double to the node list of attributes.</summary>
//<param name="name">Name.</param>
//<param name="value">Value thereof.</param>
//<returns>Attribute structure wrapper.</returns>
//<remarks>Pointer space may be grown, memory for name/value members allocated.</remarks>
xml_attribute append_attribute(const TCHAR* name,double value)
{
if(!name) return false;
TCHAR temp[32] = {0};
_stprintf(temp,_T("%lf"),value);
return append_attribute(name,temp);
}
//<summary>Append a new attribute of type bool to the node list of attributes.</summary>
//<param name="name">Name.</param>
//<param name="value">Value thereof.</param>
//<returns>Attribute structure wrapper.</returns>
//<remarks>Pointer space may be grown, memory for name/value members allocated.</remarks>
xml_attribute append_attribute(const TCHAR* name,bool value)
{
if(!name) return false;
return append_attribute(name,((value)?_T("true"):_T("false")));
}
//<summary>Set the current node entity type.</summary>
//<param name="new_type">New type to set.</param>
//<returns>Previous type.</returns>
//<remarks>If has children and now is not node_element, children are obscured.</remarks>
xml_node_type type(xml_node_type new_type)
{
xml_node_type prev = _root->type; //Save old type.
_root->type = new_type; //Set new type.
return prev; //Return old type.
}
//<summary>
// Allocate & append a child node of the given type at the end of the
// current node array of children.
//</summary>
//<param name="type">New child node type.</param>
//<returns>xml_node wrapping the new child.</returns>
//<remarks>Pointer space may be grown. An xml_node_struct structure is allocated.</remarks>
xml_node append_child(xml_node_type type)
{
if(type_document()||type_element()) //Don't do anything if not an node_element or root.
{
xml_node_struct* p = pug::append_node(_root,1,type); //Append the node.
if(p)
{
p->name_insitu = p->value_insitu = false;
return xml_node(p); //If we have it, return wrapped.
}
}
return xml_node(); //Return dummy.
}
//<summary>Allocate & insert a child node of the given type at subscript.</summary>
//<param name="i">Subscript at which to insert.</param>
//<param name="type">New child node type.</param>
//<returns>xml_node wrapping the new child.</returns>
//<remarks>
// Pointer space may be grown. An xml_node_struct structure is allocated,
// and existing children are shifted in their array position.
//</remarks>
xml_node insert_child(unsigned int i,xml_node_type type)
{
if(!type_element()) return xml_node(); //Don't do anything if not an node_element.
unsigned int n = _root->children; //Get count of existing children.
if(type_element() && i >= n) return append_child(type); //If subscript at end of array then just append.
else if(type_element() && i < n)
{
xml_node_struct* p = pug::append_node(_root,1,type); //Append the new node (by default at last array position).
if(p) //Ensure we have it.
{
register int m = (i-1); //Stop at i.
for(register int j=(n-1); j>m; --j) //Starting at one less than end of array, reverse loop to i.
_root->child[j+1] = _root->child[j]; //Shift node to right.
_root->child[i] = p; //Set node at subscript to new node.
return xml_node(p); //Return new node.
}
}
return xml_node(); //Return dummy.
}
//<summary>Delete the child node at the given subscript.</summary>
//<param name="i">Subscript.</param>
//<returns>Success.</returns>
//<remarks>Shifts child array element positions. Frees entire tree under child to be deleted.</remarks>
bool remove_child(unsigned int i)
{
unsigned int n = _root->children;
if(i < n) //Ensure subscript is in bounds.
{
xml_node_struct* p = _root->child[i]; //Keep a pointer to this node so we can free it.
--n;
unsigned int j;
for(j=i; j<n; ++j) //Shift everything left from this point on.
_root->child[j] = _root->child[j+1];
_root->child[j] = NULL; //Mark the last element null.
--_root->children; //One less children.
p->parent = p; //This ensures we only free this node when calling 'free_node'.
pug::free_node(p); //Free the node tree.
return true; //Success.
}
return false; //Failure.
}
//Stream/Output Helpers
public:
//<summary>
// Stream output. Recursively writes the internal xml_node_struct structure
// to the given stream.
//</summary>
//<param name="os">Reference to output stream.</param>
//<param name="indent_char">Char to use for indent.</param>
//<param name="breaks">Use linebreaks?</param>
//<remarks>String data is written to stream.</remarks>
void outer_xml(std::basic_ostream<TCHAR,std::char_traits<TCHAR> >& os,TCHAR indent_char = _T('\t'),bool breaks = true)
{
if(empty()) return; //Make sure there is something to output.
indent_stack indent(indent_char); //Prepare the indent.
if(type_document()) //If this is the root, we don't want to output the root itself.
{
register unsigned int n = _root->children; //Output each child of the root.
for(register unsigned int i=0; i<n; ++i)
pug::outer_xml(os,indent,_root->child[i],breaks);
}
else pug::outer_xml(os,indent,_root,breaks); //Output the node.
}
//<summary>
// Stream output operator. Wraps 'outer_xml'. Recursively writes
// the given node to the given stream.
//</summary>
//<param name="os">Reference to output stream.</param>
//<param name="xml_node">Reference to tree node.</param>
//<returns>Reference to output stream.</returns>
//<remarks>String data is written to stream.</remarks>
friend std::basic_ostream<TCHAR,std::char_traits<TCHAR> >& operator<<(std::basic_ostream<TCHAR,std::char_traits<TCHAR> >& os,xml_node node)
{
if(!os.good()) return os;
if((os.flags()|std::ostream::skipws) == std::ostream::skipws)
node.outer_xml(os,0,false); //Skipping whitespace; suppress indents & linebreaks.
else node.outer_xml(os); //Default options.
return os;
}
};
//<summary>Provides a high-level interface to the XML parser.</summary>
class xml_parser
{
//Internal Data Members
protected:
xml_node_struct* _xmldoc; //Pointer to current XML document tree root.
long _growby; //Attribute & child pointer space growth increment.
bool _autdel; //Delete the tree on destruct?
TCHAR* _buffer; //Pointer to in-memory buffer (for 'parse_file').
TCHAR* _strpos; //Where parsing left off (for 'parse_file').
unsigned long _optmsk; //Parser options.
#ifdef PUGOPT_MEMFIL
HANDLE _mmfile; //File handle.
HANDLE _mmfmap; //Handle which maps the file.
void* _mmaddr; //Base address of map.
size_t _mfsize; //Size of memory-mapped file.
bool _addeos; //True if we had to add a 0 to then end of the file.
#endif
//Construction/Destruction
public:
//<summary>Constructor.</summary>
//<param name="optmsk">Options mask.</param>
//<param name="autdel">Delete tree on destruct?</param>
//<param name="growby">Parser pointer space growth increment.</param>
//<remarks>Root node structure is allocated.</remarks>
xml_parser(unsigned long optmsk = parse_default,bool autdel = true,long growby = parse_grow):
_xmldoc(0),
_growby(growby),
_autdel(autdel),
_optmsk(optmsk),
_buffer(0),
_strpos(0)
#ifdef PUGOPT_MEMFIL
,
_mmfile(0),
_mmfmap(0),
_mmaddr(0),
_mfsize(0),
_addeos(false)
#endif
{
}
//<summary>Direct parse constructor.</summary>
//<param name="xmlstr">
// XML-formatted string to parse. Note: String must persist for the
// life of the tree. String is zero-segmented, but not freed.
//</param>
//<param name="optmsk">Parser options.</param>
//<param name="autdel">Delete tree on destruct?</param>
//<param name="growby">Parser pointer space growth increment.</param>
//<remarks>Root node structure is allocated, string is parsed & tree may be grown.</remarks>
xml_parser(TCHAR* xmlstr,unsigned long optmsk = parse_default,bool autdel = true,long growby = parse_grow) :
_xmldoc(0),
_growby(growby),
_autdel(autdel),
_optmsk(optmsk),
_buffer(0),
_strpos(0)
#ifdef PUGOPT_MEMFIL
,
_mmfile(0),
_mmfmap(0),
_mmaddr(0),
_mfsize(0),
_addeos(false)
#endif
{
parse(xmlstr,_optmsk); //Parse it.
}
//<summary>Destructor.</summary>
//<remarks>Tree memory and string memory may be freed.</remarks>
virtual ~xml_parser()
{
if(_autdel && _xmldoc) free_node(_xmldoc);
if(_buffer) free(_buffer);
#ifdef PUGOPT_MEMFIL
close_memfile();
#endif
}
//Accessors/Operators
public:
operator xml_node_struct*() { return _xmldoc; } //Cast as xml_node_struct pointer to root.
operator xml_node() { return xml_node(_xmldoc); } //Cast as xml_node (same as document).
xml_node document(){ return xml_node(_xmldoc); } //Returns the root wrapped by an xml_node.
//Miscellaneous
public:
//<summary>Allocate a new, empty root.</summary>
//<remarks>Tree memory and string memory may be freed.</remarks>
void create()
{
clear(); //Free any allocated memory.
_xmldoc = new_node(node_document); //Allocate a new root.
_xmldoc->parent = _xmldoc; //Point to self.
}
//<summary>Clear any existing tree or string.</summary>
//<remarks>Tree memory and string memory may be freed.</remarks>
void clear()
{
if(_xmldoc){ free_node(_xmldoc); _xmldoc = 0; }
if(_buffer){ free(_buffer); _buffer = 0; }
#ifdef PUGOPT_MEMFIL
close_memfile();
#endif
}
#ifdef PUGOPT_MEMFIL
//Memory-Mapped File Support
protected:
//<summary>Closes any existing memory-mapped file.</summary>
void close_memfile()
{
if(_mmaddr != 0)
{
UnmapViewOfFile(_mmaddr);
_mmaddr = 0;
}
if(_mmfmap != 0)
{
CloseHandle(_mmfmap);
_mmfmap = 0;
}
if(_mmfile != 0)
{
if(_addeos) //Remove the 0 we added to the end of the file.
{
SetFilePointer(_mmfile,_mfsize,NULL,FILE_BEGIN);
SetEndOfFile(_mmfile);
_addeos = false;
}
CloseHandle(_mmfile);
_mmfile = 0;
}
_mfsize = 0;
}
public:
#endif
//<summary>Attach an externally-generated root to the parser.</summary>
//<param name="root">Pointer to node structure.</param>
//<returns>Pointer to old root if any.</returns>
//<remarks>New root may be deleted on dtor if autodelete set.</remarks>
xml_node_struct* attach(xml_node_struct* root)
{
xml_node_struct* t = _xmldoc; //Save this root.
_xmldoc = root; //Assign.
_xmldoc->parent = _xmldoc; //Ensure we are the root.
return t; //Return the old root if any.
}
//<summary>Detach the current root from the parser.</summary>
//<returns>Pointer to old root, if any.</returns>
xml_node_struct* detach()
{
xml_node_struct* t = _xmldoc; //Save this root.
_xmldoc = 0; //So we don't delete later on if autodelete set.
return t; //Return the old root if any.
}
//<summary>Get parser optsions mask.</summary>
//<returns>Options mask.</returns>
unsigned long options(){ return _optmsk; }
//<summary>Set parser options mask.</summary>
//<param name="optmsk">Options mask to set.</param>
//<returns>Old options mask.</returns>
unsigned long options(unsigned long optmsk)
{
unsigned long prev = _optmsk;
_optmsk = optmsk;
return prev;
}
//<summary>Get pointer space growth size increment.</summary>
//<returns>Grow size.</returns>
unsigned long growby(){ return _growby; }
//<summary>Set pointer space growth size increment.</summary>
//<param name="grow">Grow size to set.</param>
//<returns>Old size.</returns>
unsigned long growby(long grow)
{
long prev = _growby;
_growby = grow;
return prev;
}
//<summary>Get parse file buffer last string position.</summary>
//<returns>Last string position.</returns>
//<remarks>
// Use after parse_file, with parse_dtd_only set in order to recommence
// parse of document body.
//</remarks>
TCHAR* strpos()
{
return _strpos;
}
//Parsing Helpers
public:
//<summary>Parse the given XML string in-situ.</summary>
//<param name="s">Pointer to XML-formatted string.</param>
//<param name="optmsk">Parser options mask.</param>
//<returns>Last string position or null.</returns>
//<remarks>Input string is zero-segmented.</remarks>
TCHAR* parse(TCHAR* s,unsigned long optmsk = parse_noset)
{
if(!s) return s;
clear(); //Free any allocated memory.
_xmldoc = new_node(node_document); //Allocate a new root.
_xmldoc->parent = _xmldoc; //Point to self.
if(optmsk != parse_noset) _optmsk = optmsk;
return pug::parse(s,_xmldoc,_growby,_optmsk); //Parse the input string.
}
/*
//<summary>Load into memory and parse the contents of the file at the given path.</summary>
//<param name="path">File path.</param>
//<param name="optmsk">Parser options.</param>
//<returns>Success if the file was loaded.</returns>
//<remarks>
// The file contents is loaded and stored in the member '_buffer' until
// freed by calling 'Parse', 'parse_file', 'clear' or '~xml_parser'.
//</remarks>
bool parse_file(const TCHAR* path,unsigned long optmsk = parse_noset)
{
if(!path) return false;
clear(); //clear any existing data.
unsigned long bytes;
if(optmsk != parse_noset) _optmsk = optmsk;
if(load_file(path,&_buffer,&bytes) && bytes > 0)
{
_xmldoc = pug::new_node(node_document);
_xmldoc->parent = _xmldoc; //Point to self.
TCHAR* s = pug::parse(_buffer,_xmldoc,_growby,_optmsk);
_strpos = s;
return true;
}
return false;
}
*/
#ifdef PUGOPT_MEMFIL
//<summary>Parse the contents of the file at the given path, using a memory-mapped file.</summary>
//<param name="path">File path.</param>
//<param name="optmsk">Parser options.</param>
//<returns>
// True (1) if the file was parsed successfully, false (0) if open failed,
// and -1 if an exception occured.
//</returns>
//<remarks>
// The file contents are available until closed by calling 'parse',
// 'parse_file', 'clear' or '~xml_parser'.
//</remarks>
int parse_mmfile(const TCHAR* path,unsigned long optmsk = parse_noset)
{
int status = 0;
if(path)
{
clear(); //Clear any existing data.
if(optmsk != parse_noset) _optmsk = optmsk;
assert((optmsk & parse_wnorm) == 0); //Normalization isn't implemented for memory-mapped files, as of 23 Jan 2003.
const bool readonly = (optmsk & (parse_dtd|parse_dtd_only)) == 0;
if(open_mmfile(path,readonly,false))
{
//If the file has a 0 at the end we are ok to proceed, otherwise add one.
if
(
(
*(((TCHAR*)_mmaddr) + _mfsize) == 0
||
(
_mfsize > 0 &&
*(((TCHAR*)_mmaddr) + _mfsize - 1) == 0
)
)
||
open_mmfile(path,false,true) //Re-open and add 0 at EOF.
)
{
try
{
_xmldoc = new_node(node_document);
_xmldoc->parent = _xmldoc; //Point to self.
TCHAR* s = pug::parse((TCHAR*)_mmaddr,_xmldoc,_growby,_optmsk);
_strpos = s;
status = 1;
}
catch(...)
{
status = -1;
assert(false);
}
}
}
}
return status;
}
protected:
//<summary>Opens the specified memory-mapped file.</summary>
//<param name="path">File path.</param>
//<param name="readonly">True to open the file for read-only access.</param>
//<param name="addeos">True to add a 0 to the end of the file.</param>
//<returns>Success if the file was opened.</returns>
bool open_mmfile(const TCHAR* path,const bool readonly,const bool addeos)
{
clear(); //Close any existing MMF and clear any existing data.
assert(_mmfile == NULL && _mmfile == NULL && _mmaddr == NULL);
_addeos = false;
_mmfile = CreateFile(path,readonly?GENERIC_READ:GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); //Open read-only, no share, no security attrs, ..., no template.
if(_mmfile != INVALID_HANDLE_VALUE)
{
_mfsize = ::GetFileSize(_mmfile,NULL);
_mmfmap = CreateFileMapping(_mmfile,NULL,readonly?PAGE_READONLY:PAGE_READWRITE,0,_mfsize+(addeos?sizeof(TCHAR):0),NULL); //Create map: handle, no security attr, read|read/write, larger if addeos, anonymous.
if(_mmfmap != NULL)
{
assert(_mmaddr == NULL);
_mmaddr = MapViewOfFile(_mmfmap,readonly?FILE_MAP_READ:FILE_MAP_WRITE,0,0,0); //Map the view: handle, read|read/write, start at beginning, map entire file.
if(_mmaddr != NULL)
{
if(addeos) //Add a terminating 0 to the end of the file for 'parse()'.
{
assert(!readonly);
*(((TCHAR*)_mmaddr) + _mfsize) = 0;
_addeos = true;
}
}
else
{
CloseHandle(_mmfmap);
CloseHandle(_mmfile);
_mmfile = _mmfmap = 0;
}
}
else
{
CloseHandle(_mmfile);
_mmfile = 0;
}
}
return (_mmaddr != NULL);
}
#endif
};
//<summary>An array of nodes, used by xml_node queries.</summary>
class xml_node_list: public pointer_array
{
public:
xml_node_list(unsigned int grow = 4) : pointer_array(grow) { }
virtual ~xml_node_list(){ }
public:
xml_node at(long i){ return xml_node((xml_node_struct*)pointer_array::at((unsigned int)i)); } //Access xml_node at subscript.
xml_node operator[](long i){ return xml_node((xml_node_struct*)pointer_array::at((unsigned int)i)); } //Access xml_node at subscript.
friend std::ostream& operator<<(std::ostream& os,xml_node_list& list) //Output helper.
{
if(!os.good()) return os;
unsigned int n = list.size();
for(unsigned int i=0; i<n; ++i) os << list[i];
return os;
}
};
} } } }
// Undefine these horrible macros
#undef PUGOPT_MEMFIL
#undef PUGOPT_NONSEG
#undef PUGAPI_INTERNAL_VARIANT
#undef PUGAPI_INTERNAL_VERSION_MAJOR
#undef PUGAPI_INTERNAL_VERSION_MINOR
#undef PUGAPI_INTERNAL_VERSION
#undef PUGDEF_ATTR_NAME_SIZE
#undef PUGDEF_ATTR_VALU_SIZE
#undef PUGDEF_ELEM_NAME_SIZE
#undef SKIPWS
#undef OPTSET
#undef PUSHNODE
#undef POPNODE
#undef SCANFOR
#undef SCANWHILE
#ifdef UNDEF_LOHIWORD
#undef HIWORD
#undef LOWORD
#undef UNDEF_LOHIWORD
#endif
#ifdef UNDEF_TCHAR_AND_REST
#undef TCHAR
#undef _tcslen
#undef _istalnum
#undef _tcsncpy
#undef _tcscpy
#undef _tcscmp
#undef _tcstol
#undef _tcstod
#undef _tcstok
#undef _stprintf
#undef _T
#undef UNDEF_TCHAR_AND_REST
#endif
#endif
| 37.292366 | 247 | 0.638507 | [
"object"
] |
379f822a40c0826398e00bf8979bb22e736fd912 | 1,577 | cpp | C++ | Medium/letter-combinations-of-a-phone-number.cpp | utkarshavardhana/LeetCode-Problems | 1b574945c59d8050a55a9d1c922dde65e6bb7c75 | [
"MIT"
] | 1 | 2020-05-10T07:21:24.000Z | 2020-05-10T07:21:24.000Z | Medium/letter-combinations-of-a-phone-number.cpp | utkarshavardhana/LeetCode-Problems | 1b574945c59d8050a55a9d1c922dde65e6bb7c75 | [
"MIT"
] | null | null | null | Medium/letter-combinations-of-a-phone-number.cpp | utkarshavardhana/LeetCode-Problems | 1b574945c59d8050a55a9d1c922dde65e6bb7c75 | [
"MIT"
] | null | null | null | // Problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
//
// Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
//
// A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
//
// Example:
//
// Input: "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
// Note:
//
// Although the above answer is in lexicographical order, your answer could be in any order you want.
class Solution {
public:
void recur(string digits, unordered_map<char, string> m,
string temp, vector<string> &res, int n) {
if(temp.size() == n) {
res.push_back(temp);
return;
}
for(int i=0; i<digits.size(); i++) {
char x = digits[i];
string s = m[x];
digits.erase(i, 1);
for(char chr : s) {
recur(digits, m, temp+chr, res, n);
}
// digits.insert(digits.begin()+i, x);
}
}
vector<string> letterCombinations(string digits) {
unordered_map<char, string> m = {
{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"},
{'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}
};
vector<string> res;
if(digits.size() == 0) return res;
string temp;
recur(digits, m, temp, res, digits.size());
return res;
}
};
| 33.553191 | 129 | 0.513633 | [
"vector"
] |
37a2605e2b10fc811171fae5b96f10cf60bd7531 | 6,047 | hpp | C++ | UNPEX/hws/hw1/calculate.hpp | MU001999/codeex | 23e300f9121a8d6bf4f4c9ec103510193808e9ba | [
"MIT"
] | 2 | 2019-01-27T14:16:09.000Z | 2019-05-25T10:05:24.000Z | UNPEX/hws/hw1/calculate.hpp | MU001999/codeex | 23e300f9121a8d6bf4f4c9ec103510193808e9ba | [
"MIT"
] | null | null | null | UNPEX/hws/hw1/calculate.hpp | MU001999/codeex | 23e300f9121a8d6bf4f4c9ec103510193808e9ba | [
"MIT"
] | 1 | 2020-11-05T05:17:28.000Z | 2020-11-05T05:17:28.000Z | #include <string>
#include <memory>
#include <vector>
#include <cctype>
#include <iterator>
namespace detail
{
struct Token
{
enum class TOKEN
{
INTEGER, // [0-9]+
ADD, SUB, MUL, DIV, MOD, // + - & / %
LPAREN, RPAREN, // ( )
END // $
} token_id;
std::string value;
Token(TOKEN token_id) : token_id(token_id) {}
Token(std::string value) : token_id(TOKEN::INTEGER), value(value) {}
};
using TOKEN = Token::TOKEN;
struct Node
{
virtual ~Node() {}
virtual int run_code() = 0;
};
struct NumberNode : Node
{
int value;
NumberNode(int value) : value(value) {}
virtual int run_code()
{
return value;
}
};
struct BinaryOperatorNode : Node
{
std::shared_ptr<Node> lhs, rhs;
TOKEN op;
BinaryOperatorNode(std::shared_ptr<Node> lhs, TOKEN op, std::shared_ptr<Node> rhs) :
lhs(lhs), rhs(rhs), op(op) {}
virtual int run_code()
{
switch (op)
{
case TOKEN::ADD:
return lhs->run_code() + rhs->run_code();
case TOKEN::SUB:
return lhs->run_code() - rhs->run_code();
case TOKEN::MUL:
return lhs->run_code() * rhs->run_code();
case TOKEN::DIV:
return lhs->run_code() / rhs->run_code();
case TOKEN::MOD:
return lhs->run_code() % rhs->run_code();
default: break;
}
exit(0);
}
};
inline decltype(auto) tokenizer(const std::string &expr)
{
std::vector<Token> tokens;
auto reading = expr.c_str();
enum {
BEGIN,
IN_INTEGER
} state = BEGIN;
std::string value;
while (*reading)
{
if (state == BEGIN)
{
switch (*reading)
{
case '$':
tokens.push_back(TOKEN::END);
case '(':
tokens.push_back(TOKEN::LPAREN);
break;
case ')':
tokens.push_back(TOKEN::RPAREN);
break;
case '+':
tokens.push_back(TOKEN::ADD);
break;
case '-':
tokens.push_back(TOKEN::SUB);
break;
case '*':
tokens.push_back(TOKEN::MUL);
break;
case '/':
tokens.push_back(TOKEN::DIV);
break;
case '%':
tokens.push_back(TOKEN::MOD);
break;
case '0': case '1': case '2':
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9':
state = IN_INTEGER;
value += *reading;
break;
default:
break;
}
}
else if (isdigit(*reading)) value += *reading;
else
{
tokens.push_back(value);
state = BEGIN;
value.clear();
--reading;
}
++reading;
}
return tokens;
}
struct Parser
{
std::vector<Token>::iterator iToken;
std::shared_ptr<Node> gen_number()
{
return std::make_shared<NumberNode>(std::stoi(iToken++->value));
}
std::shared_ptr<Node> gen_term()
{
if (iToken->token_id == TOKEN::LPAREN)
{
++iToken;
auto node = gen_expr();
if (iToken->token_id != TOKEN::RPAREN) return nullptr;
++iToken;
return node;
}
else if (iToken->token_id == TOKEN::INTEGER) return gen_number();
else return nullptr;
}
std::shared_ptr<Node> gen_term_rest(std::shared_ptr<Node> lhs)
{
auto node = lhs;
TOKEN op;
switch (iToken->token_id)
{
case TOKEN::MUL:
case TOKEN::DIV:
case TOKEN::MOD:
op = iToken++->token_id;
break;
default:
return node;
}
return gen_term_rest(std::make_shared<BinaryOperatorNode>(lhs, op, gen_term()));
}
std::shared_ptr<Node> gen_factor()
{
return gen_term_rest(gen_term());
}
std::shared_ptr<Node> gen_factor_rest(std::shared_ptr<Node> lhs)
{
auto node = lhs;
TOKEN op;
switch (iToken->token_id)
{
case TOKEN::ADD:
case TOKEN::SUB:
op = iToken++->token_id;
break;
default:
return node;
}
return gen_factor_rest(std::make_shared<BinaryOperatorNode>(lhs, op, gen_factor()));
}
std::shared_ptr<Node> gen_expr()
{
return iToken->token_id == TOKEN::END ? nullptr : gen_factor_rest(gen_factor());
}
decltype(auto) parse(const std::string &expr)
{
auto &&tokens = tokenizer(expr + "$");
iToken = tokens.begin();
return gen_expr();
}
};
}
inline std::string calculate(const std::string &expr)
{
auto node = detail::Parser().parse(expr);
return node ? std::to_string(node->run_code()) : "error input";
}
| 26.995536 | 96 | 0.412601 | [
"vector"
] |
37a2712592772fe166b18c5145d655cf696cff73 | 1,036 | cpp | C++ | Source/Urho3D/EffekseerUrho3D/LoaderUrho3D/EffekseerUrho3D.ModelLoader.cpp | aimoonchen/rbfx | de4f1fd795f4f42009693a71b6f887a221aa19db | [
"MIT"
] | null | null | null | Source/Urho3D/EffekseerUrho3D/LoaderUrho3D/EffekseerUrho3D.ModelLoader.cpp | aimoonchen/rbfx | de4f1fd795f4f42009693a71b6f887a221aa19db | [
"MIT"
] | null | null | null | Source/Urho3D/EffekseerUrho3D/LoaderUrho3D/EffekseerUrho3D.ModelLoader.cpp | aimoonchen/rbfx | de4f1fd795f4f42009693a71b6f887a221aa19db | [
"MIT"
] | null | null | null | //#include <ResourceLoader.hpp>
#include "EffekseerUrho3D.ModelLoader.h"
#include <EASTL/string.h>
#include "../RendererUrho3D/EffekseerUrho3D.RenderResources.h"
#include "../Utils/EffekseerUrho3D.Utils.h"
#include "../EffekseerResource.h"
#include "../../Core/Context.h"
#include "../../Resource/ResourceCache.h"
#include "../../Cocos2D/Urho3DContext.h"
namespace EffekseerUrho3D
{
Effekseer::ModelRef ModelLoader::Load(const char16_t* path)
{
static auto cache = GetUrho3DContext()->GetSubsystem<Urho3D::ResourceCache>();
auto urho3dPath = ToGdString(path);
auto urhoFile = cache->GetFile(urho3dPath);
auto dataSize = urhoFile->GetSize();
auto data = std::make_unique<char[]>(dataSize);
if (urhoFile->Read(data.get(), dataSize) != dataSize) {
return nullptr;
}
return Load(data.get(), dataSize);
}
Effekseer::ModelRef ModelLoader::Load(const void* data, int32_t size)
{
return Effekseer::MakeRefPtr<Model>(data, size);
}
void ModelLoader::Unload(Effekseer::ModelRef data)
{
}
} // namespace EffekseerUrho3D
| 27.263158 | 79 | 0.72973 | [
"model"
] |
37afd12897f62b9a0c9d7ad186ed935da9392802 | 4,389 | cc | C++ | euler/core/kernels/id_unique_op.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 2,829 | 2019-01-12T09:16:03.000Z | 2022-03-29T14:00:58.000Z | euler/core/kernels/id_unique_op.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 331 | 2019-01-17T21:07:49.000Z | 2022-03-30T06:38:17.000Z | euler/core/kernels/id_unique_op.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 578 | 2019-01-16T10:48:53.000Z | 2022-03-21T13:41:34.000Z | /* Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <vector>
#include <string>
#include <unordered_map>
#include "euler/core/framework/op_kernel.h"
#include "euler/core/framework/dag_node.pb.h"
#include "euler/core/framework/tensor.h"
#include "euler/common/str_util.h"
#include "euler/common/logging.h"
#include "euler/common/data_types.h"
namespace euler {
class IdUnique: public OpKernel {
public:
explicit IdUnique(const std::string& name) : OpKernel(name) {}
void Compute(const DAGNodeProto& node_def,
OpKernelContext* ctx) override;
};
void IdUnique::Compute(const DAGNodeProto& node_def,
OpKernelContext* ctx) {
// get ids tensor
Tensor* ids_tensor = nullptr;
ctx->tensor(node_def.inputs(0), &ids_tensor);
if (ids_tensor->Shape().Size() == 1) { // node ids
std::unordered_map<uint64_t, int32_t> ids_map;
ids_map.reserve(ids_tensor->NumElements());
std::vector<uint64_t> unique_vec;
unique_vec.reserve(ids_tensor->NumElements());
int32_t cnt = 0;
for (int32_t i = 0; i < ids_tensor->NumElements(); ++i) {
if (ids_map.find(ids_tensor->Raw<uint64_t>()[i]) == ids_map.end()) {
ids_map[ids_tensor->Raw<uint64_t>()[i]] = cnt++;
unique_vec.push_back(ids_tensor->Raw<uint64_t>()[i]);
}
}
// output
std::string unique_id_name = OutputName(node_def, 0);
std::string gather_idx_name = OutputName(node_def, 1);
TensorShape unique_id_shape({ids_map.size()});
TensorShape gather_idx_shape(
{static_cast<uint64_t>(ids_tensor->NumElements())});
Tensor* unique_id_t = nullptr, *gather_idx_t = nullptr;
ctx->Allocate(unique_id_name, unique_id_shape, kUInt64, &unique_id_t);
ctx->Allocate(gather_idx_name, gather_idx_shape, kInt32, &gather_idx_t);
std::copy(unique_vec.begin(), unique_vec.end(),
unique_id_t->Raw<uint64_t>());
for (int32_t i = 0; i < ids_tensor->NumElements(); ++i) {
gather_idx_t->Raw<int32_t>()[i] = ids_map.at(
ids_tensor->Raw<uint64_t>()[i]);
}
} else { // edge ids
std::vector<euler::common::EdgeID> eids(ids_tensor->NumElements() / 3);
for (size_t i = 0; i < eids.size(); ++i) {
eids[i] = euler::common::EdgeID(
ids_tensor->Raw<uint64_t>()[i * 3],
ids_tensor->Raw<uint64_t>()[i * 3 + 1],
static_cast<int32_t>(ids_tensor->Raw<uint64_t>()[i * 3 + 2]));
}
std::unordered_map<euler::common::EdgeID, int32_t,
euler::common::EdgeIDHashFunc, euler::common::EdgeIDEqualKey> ids_map;
ids_map.reserve(ids_tensor->NumElements() / 3);
std::vector<uint64_t> unique_vec;
unique_vec.reserve(ids_tensor->NumElements());
for (size_t i = 0; i < eids.size(); ++i) {
if (ids_map.find(eids[i]) == ids_map.end()) {
size_t cnt = ids_map.size();
ids_map[eids[i]] = cnt;
unique_vec.push_back(std::get<0>(eids[i]));
unique_vec.push_back(std::get<1>(eids[i]));
unique_vec.push_back(std::get<2>(eids[i]));
}
}
// output
std::string unique_id_name = OutputName(node_def, 0);
std::string gather_idx_name = OutputName(node_def, 1);
TensorShape unique_id_shape({ids_map.size(), 3});
TensorShape gather_idx_shape({eids.size()});
Tensor* unique_id_t = nullptr, *gather_idx_t = nullptr;
ctx->Allocate(unique_id_name, unique_id_shape, kUInt64, &unique_id_t);
ctx->Allocate(gather_idx_name, gather_idx_shape, kInt32, &gather_idx_t);
std::copy(unique_vec.begin(), unique_vec.end(),
unique_id_t->Raw<uint64_t>());
for (size_t i = 0; i < eids.size(); ++i) {
gather_idx_t->Raw<int32_t>()[i] = ids_map.at(eids[i]);
}
}
}
REGISTER_OP_KERNEL("ID_UNIQUE", IdUnique);
} // namespace euler
| 40.638889 | 80 | 0.656414 | [
"shape",
"vector"
] |
37b0e268a972f37995eb91febe1184c8cfd78d42 | 16,132 | cpp | C++ | inventory/inventorychanger.cpp | DomesticTerrorist/Doubletap.Space-v3-SRC | caa2e09fc5e15a268ed735debe811a19fe96a08c | [
"MIT"
] | 3 | 2021-08-18T10:19:25.000Z | 2021-08-31T04:45:26.000Z | inventory/inventorychanger.cpp | DomesticTerrorist/Doubletap.Space-v3-SRC | caa2e09fc5e15a268ed735debe811a19fe96a08c | [
"MIT"
] | null | null | null | inventory/inventorychanger.cpp | DomesticTerrorist/Doubletap.Space-v3-SRC | caa2e09fc5e15a268ed735debe811a19fe96a08c | [
"MIT"
] | 4 | 2021-08-18T06:57:26.000Z | 2021-09-02T15:22:36.000Z | #include "../includes.hpp"
#include "inventorychanger.h"
#include "../protobuffs/Protobuffs.h"
#include "../protobuffs/ProtoWriter.h"
#include "../protobuffs/Messages.h"
#include "../skinchanger/enrage parser, thanks!/parserz.hpp"
static void apply_medals(ProtoWriter& object)
{
uint32_t steamid = SteamUser->GetSteamID().GetAccountID();
for (auto MedalIndex : g_MedalSkins)
{
ProtoWriter medal(19);
medal.add(Field(CSOEconItem::account_id, TYPE_UINT32, (int64_t)steamid));
medal.add(Field(CSOEconItem::origin, TYPE_UINT32, (int64_t)9));
medal.add(Field(CSOEconItem::rarity, TYPE_UINT32, (int64_t)6));
medal.add(Field(CSOEconItem::quantity, TYPE_UINT32, (int64_t)1));
medal.add(Field(CSOEconItem::quality, TYPE_UINT32, (int64_t)4));
medal.add(Field(CSOEconItem::level, TYPE_UINT32, (int64_t)1));
auto _time = (uint32_t)std::time(0);
auto _timeval = std::string{ reinterpret_cast<const char*>((void*)&_time), 4 };
ProtoWriter Time(3);
Time.add(Field(CSOEconItemAttribute::def_index, TYPE_UINT32, (int64_t)222));
Time.add(Field(CSOEconItemAttribute::value_bytes, TYPE_STRING, _timeval));
medal.add(Field(CSOEconItem::attribute, TYPE_STRING, Time.serialize()));
medal.add(Field(CSOEconItem::def_index, TYPE_UINT64, (int64_t)MedalIndex.second.paintKit));
medal.add(Field(CSOEconItem::inventory, TYPE_UINT64, (int64_t)MedalIndex.first));
medal.add(Field(CSOEconItem::id, TYPE_UINT64, (int64_t)MedalIndex.first));
if (MedalIndex.second.equip_state == 1)
{
ProtoWriter eqip_state(3);
eqip_state.add(Field(CSOEconItemEquipped::new_class, TYPE_UINT64, (int64_t)(0)));
eqip_state.add(Field(CSOEconItemEquipped::new_slot, TYPE_UINT64, (int64_t)(55)));
medal.add(Field(CSOEconItem::equipped_state, TYPE_STRING, eqip_state.serialize()));
}
object.add(Field(SubscribedType::object_data, TYPE_STRING, medal.serialize()));
}
}
std::string Inventory::Changer(void* pubDest, uint32_t* pcubMsgSize)
{
ProtoWriter msg((void*)((DWORD)pubDest + 8), *pcubMsgSize - 8, 11);
if (msg.getAll(CMsgClientWelcome::outofdate_subscribed_caches).empty())
return msg.serialize();
ProtoWriter cache(msg.get(CMsgClientWelcome::outofdate_subscribed_caches).String(), 4);
// If not have items in inventory, Create null inventory
FixNullInventory(cache);
// Add custom items
auto objects = cache.getAll(CMsgSOCacheSubscribed::objects);
for (size_t i = 0; i < objects.size(); i++)
{
ProtoWriter object(objects[i].String(), 2);
if (!object.has(SubscribedType::type_id))
continue;
if (object.get(SubscribedType::type_id).Int32() == 1)
{
object.clear(SubscribedType::object_data);
ClearEquipState(object);
apply_medals(object);
AddAllItems(object);
cache.replace(Field(CMsgSOCacheSubscribed::objects, TYPE_STRING, object.serialize()), i);
}
}
msg.replace(Field(CMsgClientWelcome::outofdate_subscribed_caches, TYPE_STRING, cache.serialize()), 0);
return msg.serialize();
}
void Inventory::FixNullInventory(ProtoWriter& cache)
{
bool inventory_exist = false;
auto objects = cache.getAll(CMsgSOCacheSubscribed::objects);
for (size_t i = 0; i < objects.size(); i++)
{
ProtoWriter object(objects[i].String(), 2);
if (!object.has(SubscribedType::type_id))
continue;
if (object.get(SubscribedType::type_id).Int32() != 1)
continue;
inventory_exist = true;
break;
}
if (!inventory_exist)
{
ProtoWriter null_object(2);
null_object.add(Field(SubscribedType::type_id, TYPE_INT32, (int64_t)1));
cache.add(Field(CMsgSOCacheSubscribed::objects, TYPE_STRING, null_object.serialize()));
}
}
void Inventory::ClearEquipState(ProtoWriter& object)
{
auto object_data = object.getAll(SubscribedType::object_data);
for (size_t j = 0; j < object_data.size(); j++)
{
ProtoWriter item(object_data[j].String(), 19);
if (item.getAll(CSOEconItem::equipped_state).empty())
continue;
// create NOT equiped state for item
ProtoWriter null_equipped_state(2);
null_equipped_state.replace(Field(CSOEconItemEquipped::new_class, TYPE_UINT32, (int64_t)0));
null_equipped_state.replace(Field(CSOEconItemEquipped::new_slot, TYPE_UINT32, (int64_t)0));
// unequip all
auto equipped_state = item.getAll(CSOEconItem::equipped_state);
for (size_t k = 0; k < equipped_state.size(); k++)
item.replace(Field(CSOEconItem::equipped_state, TYPE_STRING, null_equipped_state.serialize()), k);
object.replace(Field(SubscribedType::object_data, TYPE_STRING, item.serialize()), j);
}
}
static auto fis_knife(const int i) -> bool
{
return (i >= 500 && i < 5027) || i == 59 || i == 42;
}
static auto fis_glove(const int i) -> bool
{
return (i >= 5027 && i <= 5035 || i == 4725); //hehe boys
}
void Inventory::AddAllItems(ProtoWriter& object)
{
for (auto& x : g_InventorySkins)
{
if (x.second.in_use_ct && x.second.in_use_t)
AddItem(object, x.first, x.second.wId, x.second.quality, x.second.paintKit, x.second.seed, x.second.wear, x.second.name, x.second.sicker, 4);
else if (x.second.in_use_ct)
AddItem(object, x.first, x.second.wId, x.second.quality, x.second.paintKit, x.second.seed, x.second.wear, x.second.name, x.second.sicker, 3);
else if (x.second.in_use_t)
AddItem(object, x.first, x.second.wId, x.second.quality, x.second.paintKit, x.second.seed, x.second.wear, x.second.name, x.second.sicker, 2);
else
AddItem(object, x.first, x.second.wId, x.second.quality, x.second.paintKit, x.second.seed, x.second.wear, x.second.name, x.second.sicker );
//write.EquipWeapon(x.second.wId, _inv.inventory.skinInfo[x.second.paintKit].rarity, Protobuffs::GetSlotID(x.second.wId));
}
}
bool is_uncommon(int index)
{
switch (index)
{
case WEAPON_DEAGLE:
case WEAPON_GLOCK:
case WEAPON_AK47:
case WEAPON_AWP:
case WEAPON_M4A1:
case WEAPON_M4A1_SILENCER:
case WEAPON_HKP2000:
case WEAPON_USP_SILENCER:
return true;
default:
return false;
}
}
void Inventory::AddItem(ProtoWriter& object, int index, int itemIndex, int rarity, int paintKit, int seed, float wear, std::string name, int ctickers[4], int inusefix)
{
uint32_t steamid = SteamUser->GetSteamID().GetAccountID();
if (!steamid)
return;
ProtoWriter item(19);
item.add(Field(CSOEconItem::id, TYPE_UINT64, (int64_t)index));
item.add(Field(CSOEconItem::account_id, TYPE_UINT32, (int64_t)steamid));
item.add(Field(CSOEconItem::def_index, TYPE_UINT32, (int64_t)itemIndex));
item.add(Field(CSOEconItem::inventory, TYPE_UINT32, (int64_t)index));
item.add(Field(CSOEconItem::origin, TYPE_UINT32, (int64_t)24));
item.add(Field(CSOEconItem::quantity, TYPE_UINT32, (int64_t)1));
item.add(Field(CSOEconItem::level, TYPE_UINT32, (int64_t)1));
item.add(Field(CSOEconItem::style, TYPE_UINT32, (int64_t)0));
item.add(Field(CSOEconItem::flags, TYPE_UINT32, (int64_t)0));
item.add(Field(CSOEconItem::in_use, TYPE_BOOL, (int64_t)false));
item.add(Field(CSOEconItem::original_id, TYPE_UINT64, (int64_t)itemIndex));
if (is_uncommon(itemIndex))
rarity++;
if (fis_knife(itemIndex) || fis_glove(itemIndex))
{
item.add(Field(CSOEconItem::quality, TYPE_UINT32, (int64_t)3));
rarity = 6;
}
if (paintKit == 309)
item.add(Field(CSOEconItem::rarity, TYPE_UINT32, (int64_t)7));
else
if (itemIndex == 4725)
item.add(Field(CSOEconItem::rarity, TYPE_UINT32, (int64_t)7));
else
if (g_cfg.inventory.autorarity && (!fis_knife(itemIndex) && !fis_glove(itemIndex)))
item.add(Field(CSOEconItem::rarity, TYPE_UINT32, (int64_t)rarity_skins[paintKit].rarity));
else
item.add(Field(CSOEconItem::rarity, TYPE_UINT32, (int64_t)rarity));
if (name.length() > 0)
item.add(Field(CSOEconItem::custom_name, TYPE_STRING, name));
enum TeamID : int
{
TEAM_UNASSIGNED,
TEAM_SPECTATOR,
TEAM_TERRORIST,
TEAM_COUNTER_TERRORIST,
};
if (inusefix == 4)
{
ProtoWriter eqip_state(3);
eqip_state.add(Field(CSOEconItemEquipped::new_class, TYPE_UINT64, (int64_t)(inusefix - 1)));
eqip_state.add(Field(CSOEconItemEquipped::new_slot, TYPE_UINT64, (int64_t)(Protobuffs::GetSlotID(itemIndex))));
item.add(Field(CSOEconItem::equipped_state, TYPE_STRING, eqip_state.serialize()));
ProtoWriter zeqip_state(3);
zeqip_state.add(Field(CSOEconItemEquipped::new_class, TYPE_UINT64, (int64_t)(inusefix - 2)));
zeqip_state.add(Field(CSOEconItemEquipped::new_slot, TYPE_UINT64, (int64_t)(Protobuffs::GetSlotID(itemIndex))));
item.add(Field(CSOEconItem::equipped_state, TYPE_STRING, zeqip_state.serialize()));
}
else if (inusefix)
{
ProtoWriter eqip_state(3);
eqip_state.add(Field(CSOEconItemEquipped::new_class, TYPE_UINT64, (int64_t)(inusefix)));
eqip_state.add(Field(CSOEconItemEquipped::new_slot, TYPE_UINT64, (int64_t)(Protobuffs::GetSlotID(itemIndex))));
item.add(Field(CSOEconItem::equipped_state, TYPE_STRING, eqip_state.serialize()));
}
// Paint Kit
float _PaintKitAttributeValue = (float)paintKit;
auto PaintKitAttributeValue = std::string{ reinterpret_cast<const char*>((void*)&_PaintKitAttributeValue), 4 };
ProtoWriter PaintKitAttribute(3);
PaintKitAttribute.add(Field(CSOEconItemAttribute::def_index, TYPE_UINT32, (int64_t)6));
PaintKitAttribute.add(Field(CSOEconItemAttribute::value_bytes, TYPE_STRING, PaintKitAttributeValue));
item.add(Field(CSOEconItem::attribute, TYPE_STRING, PaintKitAttribute.serialize()));
// Paint Seed
float _SeedAttributeValue = (float)seed;
auto SeedAttributeValue = std::string{ reinterpret_cast<const char*>((void*)&_SeedAttributeValue), 4 };
ProtoWriter SeedAttribute(3);
SeedAttribute.add(Field(CSOEconItemAttribute::def_index, TYPE_UINT32, (int64_t)7));
SeedAttribute.add(Field(CSOEconItemAttribute::value_bytes, TYPE_STRING, SeedAttributeValue));
item.add(Field(CSOEconItem::attribute, TYPE_STRING, SeedAttribute.serialize()));
// Paint Wear
float _WearAttributeValue = wear;
auto WearAttributeValue = std::string{ reinterpret_cast<const char*>((void*)&_WearAttributeValue), 4 };
ProtoWriter WearAttribute(3);
WearAttribute.add(Field(CSOEconItemAttribute::def_index, TYPE_UINT32, (int64_t)8));
WearAttribute.add(Field(CSOEconItemAttribute::value_bytes, TYPE_STRING, WearAttributeValue));
item.add(Field(CSOEconItem::attribute, TYPE_STRING, WearAttribute.serialize()));
// Stickers
for (int j = 0; j < 4; j++)
{
int _StickerAtributeValue = ctickers[j];
auto StickerAtributeValue = std::string{ reinterpret_cast<const char*>((void*)&_StickerAtributeValue), 4 };
ProtoWriter WearAttribute(3);
WearAttribute.add(Field(CSOEconItemAttribute::def_index, TYPE_UINT32, (int64_t)113 + 4 * j));
WearAttribute.add(Field(CSOEconItemAttribute::value_bytes, TYPE_STRING, StickerAtributeValue));
item.add(Field(CSOEconItem::attribute, TYPE_STRING, WearAttribute.serialize()));
float _AttributeValue = 1.0f;
auto AttributeValue = std::string{ reinterpret_cast<const char*>((void*)&_AttributeValue), 4 };
ProtoWriter Attribute(3);
Attribute.add(Field(CSOEconItemAttribute::def_index, TYPE_UINT32, (int64_t)115 + 4 * j));
Attribute.add(Field(CSOEconItemAttribute::value_bytes, TYPE_STRING, AttributeValue));
item.add(Field(CSOEconItem::attribute, TYPE_STRING, Attribute.serialize()));
//item.attribute().add(make_econ_item_attribute(113 + 4 * j, uint32_t(289 + j))); // Sticker Kit
//item.attribute().add(make_econ_item_attribute(114 + 4 * j, float(0.001f))); // Sticker Wear
//item.attribute().add(make_econ_item_attribute(115 + 4 * j, float(1.f))); // Sticker Scale
//item.attribute().add(make_econ_item_attribute(116 + 4 * j, float(0.f))); // Sticker Rotation
}
object.add(Field(SubscribedType::object_data, TYPE_STRING, item.serialize()));
}
uint8_t* ssdgfadefault(HMODULE hModule, const char* szSignature)
{
static auto pattern_to_byte = [](const char* pattern) {
auto bytes = std::vector<int>{};
auto start = const_cast<char*>(pattern);
auto end = const_cast<char*>(pattern) + strlen(pattern);
for (auto current = start; current < end; ++current) {
if (*current == '?') {
++current;
if (*current == '?')
++current;
bytes.push_back(-1);
}
else {
bytes.push_back(strtoul(current, ¤t, 16));
}
}
return bytes;
};
//auto Module = GetModuleHandleA(szModule);
auto dosHeader = (PIMAGE_DOS_HEADER)hModule;
auto ntHeaders = (PIMAGE_NT_HEADERS)((std::uint8_t*)hModule + dosHeader->e_lfanew);
auto sizeOfImage = ntHeaders->OptionalHeader.SizeOfImage;
auto patternBytes = pattern_to_byte(szSignature);
auto scanBytes = reinterpret_cast<std::uint8_t*>(hModule);
auto s = patternBytes.size();
auto d = patternBytes.data();
for (auto i = 0ul; i < sizeOfImage - s; ++i) {
bool found = true;
for (auto j = 0ul; j < s; ++j) {
if (scanBytes[i + j] != d[j] && d[j] != -1) {
found = false;
break;
}
}
if (found) {
return &scanBytes[i];
}
}
return nullptr;
};
template<class T>
static T* FindHudElement(const char* name)
{
static auto pThis = *reinterpret_cast<DWORD**>(ssdgfadefault(GetModuleHandleA("client.dll"), ("B9 ? ? ? ? E8 ? ? ? ? 8B 5D 08")) + 1);
static auto find_hud_element = reinterpret_cast<DWORD(__thiscall*)(void*, const char*)>(ssdgfadefault(GetModuleHandleA("client.dll"), ("55 8B EC 53 8B 5D 08 56 57 8B F9 33 F6 39 77 28")));
return (T*)find_hud_element(pThis, name);
}
struct hud_weapons_t {
std::int32_t* get_weapon_count() {
return reinterpret_cast<std::int32_t*>(std::uintptr_t(this) + 0x80);
}
};
void Inventory::force_full_update()
{
static auto fn = reinterpret_cast<std::int32_t(__thiscall*)(void*, std::int32_t)>(ssdgfadefault(GetModuleHandleA("client.dll"), ("55 8B EC 51 53 56 8B 75 08 8B D9 57 6B FE 2C")));
auto element = FindHudElement<std::uintptr_t*>(("CCSGO_HudWeaponSelection"));
auto hud_weapons = reinterpret_cast<hud_weapons_t*>(std::uintptr_t(element) - 0xA0);
if (hud_weapons == nullptr)
return;
if (!*hud_weapons->get_weapon_count())
return;
for (std::int32_t i = 0; i < *hud_weapons->get_weapon_count(); i++)
i = fn(hud_weapons, i);
}
bool Inventory::Presend(uint32_t& unMsgType, void* pubData, uint32_t& cubData)
{
uint32_t MessageType = unMsgType & 0x7FFFFFFF;
if (MessageType == k_EMsgGCAdjustItemEquippedState) {
ProtoWriter msg((void*)((DWORD)pubData + 8), cubData - 8, 19);
if (!msg.has(CMsgAdjustItemEquippedState::item_id)
|| !msg.has(CMsgAdjustItemEquippedState::new_class)
|| !msg.has(CMsgAdjustItemEquippedState::new_slot))
return true;
uint32_t item_id = msg.get(CMsgAdjustItemEquippedState::item_id).UInt32();
uint32_t new_class = msg.get(CMsgAdjustItemEquippedState::new_class).UInt32();
if (item_id > 200000)
{
for (auto& f : g_MedalSkins)
f.second.equip_state = 0;
auto medals = g_MedalSkins[item_id];
g_MedalSkins[item_id].equip_state = 1;
}
if (item_id > 20000 && item_id < 200000)
{
auto weapon = g_InventorySkins[item_id];
if (new_class == 2)
{
for (auto& skins : g_InventorySkins)
{
if (Protobuffs::GetSlotID(skins.second.wId) == Protobuffs::GetSlotID(weapon.wId))
skins.second.in_use_t = false;
}
g_InventorySkins[item_id].in_use_t = true;
}
else if (new_class == 3)
{
for (auto& skins : g_InventorySkins)
{
if (Protobuffs::GetSlotID(skins.second.wId) == Protobuffs::GetSlotID(weapon.wId))
skins.second.in_use_ct = false;
}
g_InventorySkins[item_id].in_use_ct = true;
}
}
m_engine()->ExecuteClientCmd("econ_clear_inventory_images");
write.SendClientHello();
write.SendMatchmakingClient2GCHello();
m_clientstate()->iDeltaTick = -1;
force_full_update();
return false;
}
return true;
}
| 31.81854 | 190 | 0.698178 | [
"object",
"vector"
] |
37b3d7ec6cd2a6f67840524b4106aa0a31da66a4 | 41,792 | cpp | C++ | admin/snapin/dsadmin/newobjcr.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/snapin/dsadmin/newobjcr.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/snapin/dsadmin/newobjcr.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1997 - 1999
//
// File: newobjcr.cpp
//
//--------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////
// newobjcr.cpp
//
// This file contains implementation of functions to create
// new ADs objects.
//
// HISTORY
// 19-Aug-97 Dan Morin Creation.
//
/////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "newobj.h"
#include "dlgcreat.h"
#include "gencreat.h"
#include "querysup.h" // CDSSearch
extern "C"
{
#ifdef FRS_CREATE
#include "dsquery.h" // CLSID_DsFindFrsMembers
#endif // FRS_CREATE
#include <schedule.h>
}
#define BREAK_ON_TRUE(b) if (b) { ASSERT(FALSE); break; }
#define BREAK_ON_FAIL BREAK_ON_TRUE(FAILED(hr))
#define RETURN_IF_FAIL if (FAILED(hr)) { ASSERT(FALSE); return hr; }
//
// The schedule block has been redefined to have 1 byte for every hour.
// CODEWORK These should be defined in SCHEDULE.H. JonN 2/9/98
//
#define INTERVAL_MASK 0x0F
#define RESERVED 0xF0
#define FIRST_15_MINUTES 0x01
#define SECOND_15_MINUTES 0x02
#define THIRD_15_MINUTES 0x04
#define FORTH_15_MINUTES 0x08
// The dialog has one bit per hour, the DS schedule has one byte per hour
#define cbDSScheduleArrayLength (24*7)
#define HeadersSizeNum(NumberOfSchedules) \
(sizeof(SCHEDULE) + ((NumberOfSchedules)-1)*sizeof(SCHEDULE_HEADER))
inline ULONG HeadersSize(SCHEDULE* psched)
{
return HeadersSizeNum(psched->NumberOfSchedules);
}
/////////////////////////////////////////////////////////////////////
// HrCreateADsUser()
//
// Create a new user.
//
HRESULT HrCreateADsUser(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
#ifdef INETORGPERSON
ASSERT(0 == lstrcmp(L"user", pNewADsObjectCreateInfo->m_pszObjectClass) || 0 == lstrcmp(L"inetOrgPerson", pNewADsObjectCreateInfo->m_pszObjectClass));
#else
ASSERT(0 == lstrcmp(L"user", pNewADsObjectCreateInfo->m_pszObjectClass));
#endif
CCreateNewUserWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
} // HrCreateADsUser()
/////////////////////////////////////////////////////////////////////
// HrCreateADsVolume()
//
// Create a new volume.
//
HRESULT
HrCreateADsVolume(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"volume", pNewADsObjectCreateInfo->m_pszObjectClass));
CCreateNewVolumeWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
} // HrCreateADsVolume()
/////////////////////////////////////////////////////////////////////
// HrCreateADsComputer()
//
// Create a new computer.
//
HRESULT
HrCreateADsComputer(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"computer", pNewADsObjectCreateInfo->m_pszObjectClass));
CCreateNewComputerWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
} // HrCreateADsComputer()
/////////////////////////////////////////////////////////////////////
// HrCreateADsPrintQueue()
//
// Create a new print queue object.
//
HRESULT
HrCreateADsPrintQueue(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"printQueue", pNewADsObjectCreateInfo->m_pszObjectClass));
CCreateNewPrintQWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
} // HrCreateADsPrintQueue()
/////////////////////////////////////////////////////////////////////
// HrCreateADsNtDsConnection()
//
// Create a new NTDS-Connection object. Note that this is not supported
// if the parent is an FRS object.
//
HRESULT
HrCreateADsNtDsConnection(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"nTDSConnection", pNewADsObjectCreateInfo->m_pszObjectClass));
// do not allow this in the standalone case
if (pNewADsObjectCreateInfo->IsStandaloneUI())
{
ASSERT(FALSE);
return E_INVALIDARG;
}
// determine whether this is an NTDS connection or an FRS connection
// CODEWORK this code can probably be removed
CPathCracker pathCracker;
HRESULT hr = S_OK;
CString strConfigPath;
CComBSTR sbstrParentPath;
bool fParentIsFrs = false;
{
// determine whether this is an FRS instance
CComQIPtr<IADs, &IID_IADs> spIADsParent( pNewADsObjectCreateInfo->m_pIADsContainer );
ASSERT( !!spIADsParent );
CComBSTR sbstrClass;
hr = spIADsParent->get_ADsPath( &sbstrParentPath );
RETURN_IF_FAIL;
hr = spIADsParent->get_Class( &sbstrClass );
RETURN_IF_FAIL;
hr = DSPROP_IsFrsObject( sbstrClass, &fParentIsFrs );
RETURN_IF_FAIL;
// Determine which subtree should be searched
if (fParentIsFrs)
{
#ifndef FRS_CREATE
// We shouldn't have seen the option to create a connection here
ASSERT(FALSE);
return S_FALSE;
#else
sbstrClass.Empty();
hr = spIADsParent->get_ADsPath( &sbstrClass );
RETURN_IF_FAIL;
hr = DSPROP_RemoveX500LeafElements( 1, &sbstrClass );
RETURN_IF_FAIL;
strConfigPath = sbstrClass;
#endif // FRS_CREATE
}
else
{
pNewADsObjectCreateInfo->GetBasePathsInfo()->GetConfigPath(strConfigPath);
}
}
CCreateNewObjectConnectionWizard wiz(pNewADsObjectCreateInfo);
// Get the target server path from the user. The path is stored in a BSTR variant.
CComBSTR sbstrTargetServer;
#ifdef FRS_CREATE
if (fParentIsFrs)
{
hr = DSPROP_DSQuery(
pNewADsObjectCreateInfo->GetParentHwnd(),
strConfigPath,
const_cast<CLSID*>(&CLSID_DsFindFrsMembers),
&sbstrTargetServer );
}
else
#endif // FRS_CREATE
{
hr = DSPROP_PickNTDSDSA(
pNewADsObjectCreateInfo->GetParentHwnd(),
strConfigPath,
&sbstrTargetServer );
}
if (hr == S_FALSE)
{
// User canceled the dialog
return S_FALSE;
}
RETURN_IF_FAIL;
if (sbstrTargetServer == sbstrParentPath)
{
// 6231: Shouldn't be able to create a connection to "yourself"
ReportMessageEx( pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_CONNECTION_TO_SELF );
return S_FALSE;
}
CComBSTR sbstrTargetServerX500DN;
hr = pathCracker.Set( sbstrTargetServer, ADS_SETTYPE_FULL );
RETURN_IF_FAIL;
hr = pathCracker.SetDisplayType( ADS_DISPLAY_FULL );
RETURN_IF_FAIL;
hr = pathCracker.Retrieve( ADS_FORMAT_X500_DN, &sbstrTargetServerX500DN );
RETURN_IF_FAIL;
// 33881: prevent duplicate connection objects
{
CDSSearch Search;
Search.Init(sbstrParentPath);
CString filter;
filter.Format(L"(fromServer=%s)", sbstrTargetServerX500DN);
Search.SetFilterString(const_cast<LPTSTR>((LPCTSTR) filter));
LPWSTR pAttrs[1] =
{
L"name"
};
Search.SetAttributeList(pAttrs, 1);
Search.SetSearchScope(ADS_SCOPE_SUBTREE);
hr = Search.DoQuery();
if (SUCCEEDED(hr))
{
hr = Search.GetNextRow();
if (SUCCEEDED(hr) && S_ADS_NOMORE_ROWS != hr)
{
DWORD dwRetval = ReportMessageEx(
pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_DUPLICATE_CONNECTION,
MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING );
if (IDYES != dwRetval)
return S_FALSE;
}
}
}
hr = pNewADsObjectCreateInfo->HrAddVariantBstr(
CComBSTR(L"fromServer"), sbstrTargetServerX500DN, TRUE );
RETURN_IF_FAIL;
{
// NTDS: set default name to RDN of parent of target NTDS-DSA
// FRS: set default name to RDN of target NTFRS-Member
CComBSTR bstrDefaultRDN;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_VALUE_ONLY);
RETURN_IF_FAIL;
hr = pathCracker.GetElement( (fParentIsFrs) ? 0 : 1, &bstrDefaultRDN );
RETURN_IF_FAIL;
ASSERT( !!bstrDefaultRDN && TEXT('\0') != *bstrDefaultRDN );
pNewADsObjectCreateInfo->m_strDefaultObjectName = bstrDefaultRDN;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_FULL);
RETURN_IF_FAIL;
}
//
// Must do this before DoModal, OnOK will try to actually create the object
//
hr = pNewADsObjectCreateInfo->HrAddVariantLong(CComBSTR(L"options"), 0, TRUE);
RETURN_IF_FAIL;
hr = pNewADsObjectCreateInfo->HrAddVariantBoolean(CComBSTR(L"enabledConnection"), TRUE, TRUE);
RETURN_IF_FAIL;
{
//
// Store initial schedule
//
BYTE abyteSchedule[ HeadersSizeNum(1) + cbDSScheduleArrayLength ];
ZeroMemory( abyteSchedule, sizeof(abyteSchedule) );
PSCHEDULE pNewScheduleBlock = (PSCHEDULE) abyteSchedule;
pNewScheduleBlock->Size = sizeof(abyteSchedule);
pNewScheduleBlock->NumberOfSchedules = 1;
pNewScheduleBlock->Schedules[0].Type = SCHEDULE_INTERVAL;
pNewScheduleBlock->Schedules[0].Offset = HeadersSizeNum(1);
memset( ((BYTE*)pNewScheduleBlock)+pNewScheduleBlock->Schedules[0].Offset,
INTERVAL_MASK,
cbDSScheduleArrayLength ); // turn on all intervals
CComVariant varSchedule;
hr = BinaryToVariant( sizeof(abyteSchedule), abyteSchedule, &varSchedule );
RETURN_IF_FAIL;
hr = pNewADsObjectCreateInfo->HrAddVariantCopyVar(CComBSTR(L"schedule"), IN varSchedule, TRUE);
RETURN_IF_FAIL;
}
// CODEWORK: Need to set the dialog caption
hr = wiz.DoModal();
return hr;
} // HrCreateADsNtDsConnection()
HRESULT
HrCreateADsFixedName(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
// Store the object name in the temporary storage
LPCWSTR pcsz = reinterpret_cast<LPCWSTR>(pNewADsObjectCreateInfo->QueryCreationParameter());
ASSERT( NULL != pcsz );
pNewADsObjectCreateInfo->HrCreateNew(pcsz);
// Create and persist the object
HRESULT hr = pNewADsObjectCreateInfo->HrSetInfo(TRUE /*fSilentError*/);
if (SUCCEEDED(hr)) {
CString csCaption, csMsg;
csCaption.LoadString(IDS_CREATE_NEW_OBJECT_TITLE);
csMsg.Format(IDS_s_CREATE_NEW_OBJECT_NOTICE, pNewADsObjectCreateInfo->GetName());
::MessageBox(
pNewADsObjectCreateInfo->GetParentHwnd(),
csMsg,
csCaption,
MB_OK | MB_SETFOREGROUND | MB_ICONINFORMATION);
}
return hr;
}
HRESULT
HrCreateADsSiteLink(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(gsz_siteLink, pNewADsObjectCreateInfo->m_pszObjectClass));
// load list of sites
DSPROP_BSTR_BLOCK bstrblock;
CComQIPtr<IADs, &IID_IADs> container(pNewADsObjectCreateInfo->m_pIADsContainer);
if (container)
{
CComBSTR container_path;
container->get_ADsPath(&container_path);
HRESULT hr = DSPROP_RemoveX500LeafElements( 2, &container_path );
if ( SUCCEEDED(hr) )
{
hr = DSPROP_ShallowSearch(
&bstrblock,
container_path,
L"site" );
}
if ( FAILED(hr) )
{
ReportErrorEx (pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_SITELINKERROR_READING_SITES,
hr,
MB_OK, NULL, 0);
return S_FALSE;
}
}
if ( 2 > bstrblock.QueryCount() )
{
ReportMessageEx(pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_SITELINK_NOT_ENOUGH_SITES,
MB_OK | MB_ICONSTOP);
// allow wizard to continue, CODEWORK note that this
// doesn't quite work right when zero sites are detected
}
// set default cost to 100 (by request of JeffParh)
HRESULT hr = pNewADsObjectCreateInfo->HrAddVariantLong(CComBSTR(L"cost"), 100L, TRUE);
RETURN_IF_FAIL;
// set default replInterval to 180 (by request of JeffParh)
hr = pNewADsObjectCreateInfo->HrAddVariantLong(CComBSTR(L"replInterval"), 180L, TRUE);
RETURN_IF_FAIL;
CCreateNewSiteLinkWizard wiz(pNewADsObjectCreateInfo,bstrblock);
return wiz.DoModal();
}
HRESULT
HrCreateADsSiteLinkBridge(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(gsz_siteLinkBridge, pNewADsObjectCreateInfo->m_pszObjectClass));
// load list of site links
DSPROP_BSTR_BLOCK bstrblock;
CComQIPtr<IADs, &IID_IADs> container(pNewADsObjectCreateInfo->m_pIADsContainer);
if (container)
{
CComBSTR container_path;
container->get_ADsPath(&container_path);
HRESULT hr = DSPROP_ShallowSearch(
&bstrblock,
container_path,
L"siteLink" );
if ( FAILED(hr) )
{
ReportErrorEx (pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_SITELINKBRIDGEERROR_READING_SITELINKS,
hr,
MB_OK, NULL, 0);
return S_FALSE;
}
}
if ( 2 > bstrblock.QueryCount() )
{
ReportMessageEx(pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_SITELINKBRIDGE_NOT_ENOUGH_SITELINKS,
MB_OK | MB_ICONSTOP);
return S_FALSE; // do not allow wizard to continue
}
CCreateNewSiteLinkBridgeWizard wiz(pNewADsObjectCreateInfo,bstrblock);
return wiz.DoModal();
}
#ifdef FRS_CREATE
HRESULT
HrCreateADsNtFrsMember(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(gsz_nTFRSMember, pNewADsObjectCreateInfo->m_pszObjectClass));
//
// set up Frs-Computer-Reference attribute
//
CComBSTR sbstrComputerPath;
// pNewADsObjectCreateInfo->m_strDefaultObjectName = sbstrComputerRDN;
HRESULT hr = DSPROP_PickComputer( pNewADsObjectCreateInfo->GetParentHwnd(), &sbstrComputerPath );
RETURN_IF_FAIL;
// Allow user to quit if user hit Cancel
if (hr == S_FALSE)
return S_FALSE;
// set default name to RDN of target Computer
hr = pathCracker.Set(sbstrComputerPath, ADS_SETTYPE_FULL);
RETURN_IF_FAIL;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_VALUE_ONLY);
RETURN_IF_FAIL;
sbstrComputerPath.Empty();
hr = pathCracker.GetElement( 0, &sbstrComputerPath );
RETURN_IF_FAIL;
pNewADsObjectCreateInfo->m_strDefaultObjectName = sbstrComputerPath;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_FULL);
RETURN_IF_FAIL;
// set frsComputerReference for new object
sbstrComputerPath.Empty();
hr = pathCracker.Retrieve( ADS_FORMAT_X500_DN, &sbstrComputerPath );
RETURN_IF_FAIL;
hr = pNewADsObjectCreateInfo->HrAddVariantBstr(
L"frsComputerReference", sbstrComputerPath, TRUE );
RETURN_IF_FAIL;
hr = HrCreateADsSimpleObject(pNewADsObjectCreateInfo);
return hr;
}
HRESULT
HrCreateADsNtFrsSubscriber(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(gsz_nTFRSSubscriber, pNewADsObjectCreateInfo->m_pszObjectClass));
// User finds target nTFRSMember object
CComBSTR sbstrTargetMember;
HRESULT hr = DSPROP_DSQuery(
pNewADsObjectCreateInfo->GetParentHwnd(),
NULL, // any member
const_cast<CLSID*>(&CLSID_DsFindFrsMembers),
&sbstrTargetMember );
if (hr == S_FALSE)
{
// User canceled the dialog
return S_FALSE;
}
RETURN_IF_FAIL;
// set default name of new nTFRSSubscriber to RDN of target nTFRSMember
hr = pathCracker.Set( sbstrTargetMember, ADS_SETTYPE_FULL );
RETURN_IF_FAIL;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_VALUE_ONLY);
RETURN_IF_FAIL;
sbstrTargetMember.Empty();
hr = pathCracker.GetElement( 0, &sbstrTargetMember );
RETURN_IF_FAIL;
pNewADsObjectCreateInfo->m_strDefaultObjectName = sbstrTargetMember;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_FULL);
RETURN_IF_FAIL;
// set fRSMemberReference attribute to target nTFRSMember
sbstrTargetMember.Empty();
hr = pathCracker.Retrieve( ADS_FORMAT_X500_DN, &sbstrTargetMember );
RETURN_IF_FAIL;
hr = pNewADsObjectCreateInfo->HrAddVariantBstr(
L"fRSMemberReference", sbstrTargetMember, TRUE );
RETURN_IF_FAIL;
CCreateNewFrsSubscriberWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
}
//+----------------------------------------------------------------------------
//
// Function: CreateADsNtFrsSubscriptions
//
// Purpose: Create an NT-FRS-Subscriptions object and then grant its parent
// (a computer object) full access.
//
//-----------------------------------------------------------------------------
HRESULT
CreateADsNtFrsSubscriptions(CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
LPCWSTR pcsz = reinterpret_cast<LPCWSTR>(pNewADsObjectCreateInfo->QueryCreationParameter());
ASSERT( NULL != pcsz );
pNewADsObjectCreateInfo->HrCreateNew(pcsz);
//
// Create and persist the object. This must be done before attempting to modify
// the Security Descriptor.
//
HRESULT hr = pNewADsObjectCreateInfo->HrSetInfo();
if (FAILED(hr))
{
TRACE(_T("pNewADsObjectCreateInfo->HrSetInfo failed!\n"));
return hr;
}
//
// Create a new ACE on this object granting the parent full control. First, get the
// parent's SID.
//
CComVariant varSID;
CComPtr <IADs> pADS;
hr = pNewADsObjectCreateInfo->m_pIADsContainer->QueryInterface(IID_IADs, (PVOID*)&pADS);
if (FAILED(hr))
{
TRACE(_T("QueryInterface(IID_IADs) failed!\n"));
return hr;
}
hr = pADS->Get(L"objectSid", &varSID);
if (FAILED(hr))
{
TRACE(_T("Get(\"objectSid\") failed!\n"));
return hr;
}
ASSERT((varSID.vt & ~VT_ARRAY) == VT_UI1); // this better be an array of BYTEs.
ASSERT(varSID.parray->cbElements && varSID.parray->pvData);
//
// Get this object's Security Descriptor.
//
CComPtr <IDirectoryObject> pDirObj;
hr = pNewADsObjectCreateInfo->PGetIADsPtr()->QueryInterface(IID_IDirectoryObject, (PVOID*)&pDirObj);
if (FAILED(hr))
{
TRACE(_T("QueryInterface(IID_IDirectoryObject) failed!\n"));
return hr;
}
const PWSTR wzSecDescriptor = L"nTSecurityDescriptor";
PADS_ATTR_INFO pAttrs = NULL;
DWORD cAttrs = 0;
LPWSTR rgpwzAttrNames[] = {wzSecDescriptor};
hr = pDirObj->GetObjectAttributes(rgpwzAttrNames, 1, &pAttrs, &cAttrs);
if (FAILED(hr))
{
TRACE(_T("GetObjectAttributes(wzSecDescriptor) failed!\n"));
return hr;
}
ASSERT(cAttrs == 1); // SD is a required attribute. Blow chunks if missing.
ASSERT(pAttrs != NULL);
ASSERT(pAttrs->pADsValues != NULL);
if (!pAttrs->pADsValues->SecurityDescriptor.lpValue ||
!pAttrs->pADsValues->SecurityDescriptor.dwLength)
{
TRACE(_T("IADS return bogus SD!\n"));
FreeADsMem(pAttrs);
return E_UNEXPECTED;
}
if (!IsValidSecurityDescriptor(pAttrs->pADsValues->SecurityDescriptor.lpValue))
{
TRACE(_T("IsValidSecurityDescriptor failed!\n"));
FreeADsMem(pAttrs);
return HRESULT_FROM_WIN32(GetLastError());
}
//
// Can't modify a self-relative SD so convert it to an absolute one.
//
PSECURITY_DESCRIPTOR pAbsSD = NULL, pNewSD;
PACL pDacl = NULL, pSacl = NULL;
PSID pOwnerSid = NULL, pPriGrpSid = NULL;
DWORD cbSD = 0, cbDacl = 0, cbSacl = 0, cbOwner = 0, cbPriGrp = 0;
if (!MakeAbsoluteSD(pAttrs->pADsValues->SecurityDescriptor.lpValue,
pAbsSD, &cbSD, pDacl, &cbDacl,
pSacl, &cbSacl, pOwnerSid, &cbOwner,
pPriGrpSid, &cbPriGrp))
{
DWORD dwErr = GetLastError();
if (dwErr != ERROR_INSUFFICIENT_BUFFER)
{
TRACE(_T("MakeAbsoluteSD failed to return buffer sizes!\n"));
FreeADsMem(pAttrs);
return HRESULT_FROM_WIN32(GetLastError());
}
}
if (!cbDacl)
{
TRACE(_T("SD missing DACL!\n"));
FreeADsMem(pAttrs);
return E_UNEXPECTED;
}
WORD wSizeNeeded = (WORD)(sizeof(ACCESS_ALLOWED_ACE) + // the last element of
GetLengthSid(varSID.parray->pvData) - // the ACE struct is the
sizeof(DWORD)); // first DWORD of the SID.
CSmartBytePtr spAbsSD(cbSD), spSacl(cbSacl);
CSmartBytePtr spDacl(cbDacl + wSizeNeeded);
CSmartBytePtr spOwnerSid(cbOwner), spPriGrpSid(cbPriGrp);
pAbsSD = spAbsSD;
pDacl = (PACL)(PBYTE)spDacl;
pSacl = (PACL)(PBYTE)spSacl;
pOwnerSid = spOwnerSid;
pPriGrpSid = spPriGrpSid;
if (!(pAbsSD && pDacl && pSacl && pOwnerSid && pPriGrpSid))
{
TRACE(_T("SD allocation failed!\n"));
FreeADsMem(pAttrs);
return E_OUTOFMEMORY;
}
if (!MakeAbsoluteSD(pAttrs->pADsValues->SecurityDescriptor.lpValue,
pAbsSD, &cbSD, pDacl, &cbDacl,
pSacl, &cbSacl, pOwnerSid, &cbOwner,
pPriGrpSid, &cbPriGrp))
{
TRACE(_T("MakeAbsoluteSD failed!\n"));
FreeADsMem(pAttrs);
return HRESULT_FROM_WIN32(GetLastError());
}
FreeADsMem(pAttrs);
//
// Add ACE. First tell the DACL that there is enough room.
//
ACL_SIZE_INFORMATION asi;
if (!GetAclInformation(pDacl, &asi, sizeof(asi), AclSizeInformation))
{
TRACE(_T("GetAclInformation failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
if (asi.AclBytesFree < wSizeNeeded)
{
pDacl->AclSize += wSizeNeeded;
}
if (!AddAccessAllowedAce(pDacl,
ACL_REVISION_DS,
STANDARD_RIGHTS_ALL | ACTRL_DS_OPEN |
ACTRL_DS_CREATE_CHILD | ACTRL_DS_DELETE_CHILD |
ACTRL_DS_LIST | ACTRL_DS_SELF |
ACTRL_DS_READ_PROP | ACTRL_DS_WRITE_PROP |
ACTRL_DS_DELETE_TREE | ACTRL_DS_LIST_OBJECT,
varSID.parray->pvData))
{
TRACE(_T("AddAccessAllowedAce failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
//
// Put the SD back together again (sort of like Humpty Dumpty)...
//
SECURITY_DESCRIPTOR_CONTROL sdc;
DWORD dwRev;
if (!GetSecurityDescriptorControl(pAbsSD, &sdc, &dwRev))
{
TRACE(_T("GetSecurityDescriptorControl failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
SECURITY_DESCRIPTOR sd;
if (!InitializeSecurityDescriptor(&sd, dwRev))
{
TRACE(_T("InitializeSecurityDescriptor failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
if (!SetSecurityDescriptorOwner(&sd, pOwnerSid, sdc & SE_OWNER_DEFAULTED))
{
TRACE(_T("SetSecurityDescriptorOwner failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
if (!SetSecurityDescriptorGroup(&sd, pPriGrpSid, sdc & SE_GROUP_DEFAULTED))
{
TRACE(_T("SetSecurityDescriptorOwner failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
if (!SetSecurityDescriptorSacl(&sd, sdc & SE_SACL_PRESENT, pSacl, sdc & SE_SACL_DEFAULTED))
{
TRACE(_T("SetSecurityDescriptorOwner failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
if (!SetSecurityDescriptorDacl(&sd, sdc & SE_DACL_PRESENT, pDacl, sdc & SE_DACL_DEFAULTED))
{
TRACE(_T("SetSecurityDescriptorOwner failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
DWORD dwSDlen = GetSecurityDescriptorLength(&sd);
CSmartBytePtr spNewSD(dwSDlen);
if (!spNewSD)
{
TRACE(_T("SD allocation failed!\n"));
return E_OUTOFMEMORY;
}
pNewSD = (PSECURITY_DESCRIPTOR)spNewSD;
if (!MakeSelfRelativeSD(&sd, pNewSD, &dwSDlen))
{
DWORD dwErr = GetLastError();
if (dwErr != ERROR_INSUFFICIENT_BUFFER)
{
TRACE(_T("MakeSelfRelativeSD failed, err: %d!\n"), dwErr);
return HRESULT_FROM_WIN32(GetLastError());
}
if (!spNewSD.ReAlloc(dwSDlen))
{
TRACE(_T("Unable to re-alloc SD buffer!\n"));
return E_OUTOFMEMORY;
}
if (!MakeSelfRelativeSD(&sd, pNewSD, &dwSDlen))
{
TRACE(_T("MakeSelfRelativeSD failed, err: %d!\n"), GetLastError());
return HRESULT_FROM_WIN32(GetLastError());
}
}
dwSDlen = GetSecurityDescriptorLength(pNewSD);
if (dwSDlen < SECURITY_DESCRIPTOR_MIN_LENGTH)
{
TRACE(_T("Bad computer security descriptor length!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
if (!IsValidSecurityDescriptor(pNewSD))
{
TRACE(_T("IsValidSecurityDescriptor failed!\n"));
return HRESULT_FROM_WIN32(GetLastError());
}
//
// Save the modified SD back to this object.
//
DWORD cModified;
ADSVALUE ADsValueSecurityDesc = {ADSTYPE_NT_SECURITY_DESCRIPTOR, NULL};
ADS_ATTR_INFO AttrInfoSecurityDesc = {wzSecDescriptor, ADS_ATTR_UPDATE,
ADSTYPE_NT_SECURITY_DESCRIPTOR,
&ADsValueSecurityDesc, 1};
ADsValueSecurityDesc.SecurityDescriptor.dwLength = dwSDlen;
ADsValueSecurityDesc.SecurityDescriptor.lpValue = (PBYTE)pNewSD;
ADS_ATTR_INFO rgAttrs[1];
rgAttrs[0] = AttrInfoSecurityDesc;
hr = pDirObj->SetObjectAttributes(rgAttrs, 1, &cModified);
if (FAILED(hr))
{
TRACE(_T("SetObjectAttributes on SecurityDescriptor failed!\n"));
return hr;
}
return S_OK;
}
#endif // FRS_CREATE
HRESULT
HrCreateADsSubnet(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"subnet", pNewADsObjectCreateInfo->m_pszObjectClass));
CreateNewSubnetWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
}
// Note that this assumes that the site is the "grandparent" of the server.
// If it isn't, the wrong name will appear in the site field.
HRESULT ExtractServerAndSiteName(
IN LPWSTR pwszServerDN,
OUT BSTR* pbstrServerName,
OUT BSTR* pbstrSiteName )
{
CPathCracker pathCracker;
*pbstrServerName = NULL;
*pbstrSiteName = NULL;
if ( NULL == pwszServerDN || L'\0' == *pwszServerDN )
return S_OK;
HRESULT hr = pathCracker.Set( CComBSTR(pwszServerDN), ADS_SETTYPE_DN );
RETURN_IF_FAIL;
hr = pathCracker.SetDisplayType( ADS_DISPLAY_VALUE_ONLY );
RETURN_IF_FAIL;
hr = pathCracker.GetElement( 0, pbstrServerName );
RETURN_IF_FAIL;
hr = pathCracker.GetElement( 2, pbstrSiteName );
RETURN_IF_FAIL;
hr = pathCracker.SetDisplayType( ADS_DISPLAY_FULL );
RETURN_IF_FAIL;
return S_OK;
}
HRESULT
HrCreateADsServer(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
HRESULT hr = S_OK;
#ifdef SERVER_COMPUTER_REFERENCE
CComBSTR sbstrComputerPath;
CComBSTR sbstrX500DN;
CComBSTR sbstrComputerRDN;
CComBSTR sbstrTemp;
CComVariant svarServerReference;
CComPtr<IADs> spIADsComputer;
bool fSkipComputerModify = false;
do
{
hr = DSPROP_PickComputer( pNewADsObjectCreateInfo->GetParentHwnd(), &sbstrComputerPath );
BREAK_ON_FAIL;
// Allow user to quit if user hit Cancel
if (hr == S_FALSE)
{
DWORD dwRetval = ReportMessageEx(
pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_SKIP_SERVER_REFERENCE,
MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING );
if (IDYES != dwRetval)
{
hr = S_FALSE;
break;
}
fSkipComputerModify=true;
}
else
{ // prepare to modify computer object
/*
// Since the dialog was in single-select mode and the user was able
// to hit OK, there should be exactly one selection.
BREAK_ON_TRUE(1 != pSelection->cItems);
*/
// retrieve the ADsPath to the selected computer
// hr = pathCracker.Set(pSelection->aDsSelection[0].pwzADsPath, ADS_SETTYPE_FULL);
hr = pathCracker.Set(sbstrComputerPath, ADS_SETTYPE_FULL);
sbstrComputerPath.Empty();
BREAK_ON_FAIL;
// if this is a GC: path, the server might have a read-only copy of
// this object. Change the path to an LDAP: path and remove the server.
hr = pathCracker.Retrieve(ADS_FORMAT_PROVIDER,&sbstrTemp);
BREAK_ON_FAIL;
long lnFormatType = ADS_FORMAT_WINDOWS;
if ( lstrcmp(sbstrTemp, TEXT("LDAP")) )
{
ASSERT( !lstrcmp(sbstrTemp, TEXT("GC")) );
#error CODEWORK this usage of ADS_SETTYPE_PROVIDER will no longer work! JonN 2/12/99
hr = pathCracker.Set(TEXT("LDAP"),ADS_SETTYPE_PROVIDER);
BREAK_ON_FAIL;
lnFormatType = ADS_FORMAT_WINDOWS_NO_SERVER;
}
sbstrTemp.Empty();
hr = pathCracker.Retrieve(lnFormatType,&sbstrComputerPath);
BREAK_ON_FAIL;
// We preserve the servername in case Computer Picker returns one.
// Extract the name of the computer object and make that the default name
// of the new server object
hr = pathCracker.SetDisplayType(ADS_DISPLAY_VALUE_ONLY);
BREAK_ON_FAIL;
hr = pathCracker.GetElement(0,&sbstrComputerRDN);
BREAK_ON_FAIL;
BREAK_ON_TRUE( !sbstrComputerRDN || TEXT('\0') == *sbstrComputerRDN );
pNewADsObjectCreateInfo->m_strDefaultObjectName = sbstrComputerRDN;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_FULL);
BREAK_ON_FAIL;
// Now check whether the computer already references a server.
// Note that we may be using a serverless path, ADSI will try to find a
// replica on the same domain as the computer object.
hr = DSAdminOpenObject(sbstrComputerPath,
IID_IADs,
(PVOID*)&spIADsComputer,
FALSE /*bServer*/
);
// DSAdminOpenObject might fail if the initial path chosen by Computer Picker
// is a GC: path. The code above would munge the GC: path to an LDAP:
// serverless path, and ADSI might choose a replica which hasn't
// replicated this object yet.
if ( SUCCEEDED(hr) )
{
hr = spIADsComputer->Get( L"serverReference", &svarServerReference );
}
if ( E_ADS_PROPERTY_NOT_FOUND == hr )
{
hr = S_OK;
}
else if ( FAILED(hr) )
{
PVOID apv[1] = { (BSTR)sbstrComputerRDN };
DWORD dwRetval = ReportErrorEx(
pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_12_SERVER_REFERENCE_FAILED,
hr,
MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING,
apv,
1 );
if (IDYES != dwRetval)
{
hr = S_FALSE;
break;
}
fSkipComputerModify=TRUE;
hr = S_OK;
}
else
{
if ( VT_BSTR == V_VT(&svarServerReference) && NULL != V_BSTR(&svarServerReference) )
{
CComBSTR sbstrServerName;
CComBSTR sbstrSiteName;
hr = ExtractServerAndSiteName(
V_BSTR(&svarServerReference), &sbstrServerName, &sbstrSiteName );
BREAK_ON_FAIL;
PVOID apv[3];
apv[0] = (BSTR)sbstrComputerRDN;
apv[1] = (BSTR)sbstrServerName;
apv[2] = (BSTR)sbstrSiteName;
DWORD dwRetval = ReportMessageEx(
pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_123_COMPUTER_OBJECT_ALREADY_USED,
MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING,
apv,
3 );
if (IDYES != dwRetval)
{
hr = S_FALSE;
break;
}
}
}
} // prepare to modify computer object
#endif // SERVER_COMPUTER_REFERENCE
// This is the standard UI to create a simple object
hr = HrCreateADsSimpleObject(pNewADsObjectCreateInfo);
#ifdef SERVER_COMPUTER_REFERENCE
if ( FAILED(hr) || S_FALSE == hr )
{
break;
}
// If an error occurs after the server was successfully created, we use a
// special error message.
do { // false loop
if (fSkipComputerModify)
break; // CODEWORK also display a fancy message?
// Get the path to the new Server object in X500 format
hr = pNewADsObjectCreateInfo->PGetIADsPtr()->get_ADsPath(&sbstrTemp);
BREAK_ON_FAIL;
hr = pathCracker.Set(sbstrTemp,ADS_SETTYPE_FULL);
BREAK_ON_FAIL;
hr = pathCracker.SetDisplayType(ADS_DISPLAY_FULL);
BREAK_ON_FAIL;
hr = pathCracker.Retrieve(ADS_FORMAT_X500_DN,&sbstrX500DN);
BREAK_ON_FAIL;
// Set the computer object's serverReference attribute
// to point to the new Server object
svarServerReference = sbstrX500DN;
hr = spIADsComputer->Put( L"serverReference", svarServerReference );
BREAK_ON_FAIL;
hr = spIADsComputer->SetInfo();
BREAK_ON_FAIL;
} while (false); // false loop
if ( FAILED(hr) )
{
// The server was created but the computer could not be updated
CComBSTR sbstrServerName;
CComBSTR sbstrSiteName;
(void) ExtractServerAndSiteName(
V_BSTR(&svarServerReference), &sbstrServerName, &sbstrSiteName );
PVOID apv[3];
apv[0] = (BSTR)sbstrComputerRDN;
apv[1] = (BSTR)sbstrServerName;
apv[2] = (BSTR)sbstrSiteName;
(void) ReportErrorEx(
pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_1234_SERVER_REFERENCE_ERROR,
hr,
MB_OK | MB_ICONEXCLAMATION,
apv,
3 );
hr = S_OK;
}
} while (false); // false loop
#endif // SERVER_COMPUTER_REFERENCE
// cleanup
return hr;
}
HRESULT
HrCreateADsSite(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
HRESULT hr = CreateNewSiteWizard(pNewADsObjectCreateInfo).DoModal();
if ( !SUCCEEDED(hr) || S_FALSE == hr )
return hr;
// need to create sub objects
IADs* pIADs = pNewADsObjectCreateInfo->PGetIADsPtr();
ASSERT(pIADs != NULL);
IADsContainer* pIADsContainer = NULL;
hr = pIADs->QueryInterface(IID_IADsContainer, (void**)&pIADsContainer);
ASSERT(SUCCEEDED(hr));
if (FAILED(hr))
{
ASSERT(FALSE);
return S_OK; // should never happen
}
LPCWSTR lpszAttrString = L"cn=";
hr = HrCreateFixedNameHelper(gsz_nTDSSiteSettings, lpszAttrString, pIADsContainer);
ASSERT(SUCCEEDED(hr));
hr = HrCreateFixedNameHelper(gsz_serversContainer, lpszAttrString, pIADsContainer);
ASSERT(SUCCEEDED(hr));
hr = HrCreateFixedNameHelper(gsz_licensingSiteSettings, lpszAttrString, pIADsContainer);
ASSERT(SUCCEEDED(hr));
pIADsContainer->Release();
LPCWSTR pcszSiteName = pNewADsObjectCreateInfo->GetName();
static bool g_DisplayedWarning = false;
if (!g_DisplayedWarning)
{
g_DisplayedWarning = true;
(void) ReportMessageEx(
pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_NEW_SITE_INFO,
MB_OK | MB_ICONINFORMATION | MB_HELP,
(PVOID*)(&pcszSiteName),
1,
0,
L"sag_ADsite_checklist_2.htm"
);
}
return S_OK;
}
HRESULT
HrCreateADsOrganizationalUnit(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"organizationalUnit", pNewADsObjectCreateInfo->m_pszObjectClass));
CCreateNewOUWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
}
HRESULT
HrCreateADsGroup(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"group", pNewADsObjectCreateInfo->m_pszObjectClass));
CCreateNewGroupWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
}
HRESULT
HrCreateADsContact(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
ASSERT(0 == lstrcmp(L"contact", pNewADsObjectCreateInfo->m_pszObjectClass));
CCreateNewContactWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
}
/////////////////////////////////////////////////////////////////////
// HrCreateADsSimpleObject()
//
// Create a simple object which "cn" is the
// only mandatory attribute.
//
// IMPLEMENTATION NOTES
// Invoke a dialog asking for the cannonical name.
//
HRESULT HrCreateADsSimpleObject(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
CCreateNewObjectCnWizard wiz(pNewADsObjectCreateInfo);
return wiz.DoModal();
} // HrCreateADsSimpleObject()
/////////////////////////////////////////////////////////////////////
// HrCreateADsObjectGenericWizard()
//
// Create an object invoking a "Generic Create" wizard.
// The wizard will have as many pages as the number of mandatory attributes.
//
// INTERFACE NOTES
// This routine must have the same interface as PFn_HrCreateADsObject().
//
// IMPLEMENTATION NOTES
// The wizard will look into the Directory Schema and determine what are
// the mandatory attributes.
//
// REMARKS
// Although the wizard is the most versatile tool to create a new
// object, it is the least user-friendly way of doing so. The wizard
// has no understanding how the attributes relates. Therefore it
// is suggested to provide your own HrCreateADs*() routine to provide
// a friendlier dialog to the user.
//
HRESULT
HrCreateADsObjectGenericWizard(INOUT CNewADsObjectCreateInfo * pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
ASSERT(pNewADsObjectCreateInfo != NULL);
// cannot have a Generic Wizard when running as standalone object
ASSERT(!pNewADsObjectCreateInfo->IsStandaloneUI());
if (pNewADsObjectCreateInfo->IsStandaloneUI())
return E_INVALIDARG;
CCreateNewObjectGenericWizard dlg;
if (dlg.FDoModal(INOUT pNewADsObjectCreateInfo))
return S_OK;
return S_FALSE;
} // HrCreateADsObjectGenericWizard()
/////////////////////////////////////////////////////////////////////
// HrCreateADsObjectOverride()
//
// handler for object creation using a replacement dialog
HRESULT
HrCreateADsObjectOverride(INOUT CNewADsObjectCreateInfo* pNewADsObjectCreateInfo)
{
CThemeContextActivator activator;
BOOL bHandled = FALSE;
HRESULT hr = E_INVALIDARG;
if (!pNewADsObjectCreateInfo->IsStandaloneUI())
{
// try to create the dialog creation handler (full UI replacement)
// this functionality is not exposed by the standalone UI
IDsAdminCreateObj* pCreateObj = NULL;
hr = ::CoCreateInstance(pNewADsObjectCreateInfo->GetCreateInfo()->clsidWizardPrimaryPage,
NULL, CLSCTX_INPROC_SERVER,
IID_IDsAdminCreateObj, (void**)&pCreateObj);
if (SUCCEEDED(hr))
{
// try to initialize handler
hr = pCreateObj->Initialize(pNewADsObjectCreateInfo->m_pIADsContainer,
pNewADsObjectCreateInfo->GetCopyFromObject(),
pNewADsObjectCreateInfo->m_pszObjectClass);
if (SUCCEEDED(hr))
{
// execute call for creation
IADs* pADsObj = NULL;
bHandled = TRUE;
hr = pCreateObj->CreateModal(pNewADsObjectCreateInfo->GetParentHwnd(), &pADsObj);
// can have S_OK, S_FALSE, and error
if ((hr == S_OK) && pADsObj != NULL)
{
// hold to the returned, newly created object
pNewADsObjectCreateInfo->SetIADsPtr(pADsObj); // it will addref
pADsObj->Release();
}
}
pCreateObj->Release();
}
} // not standalone UI
// check if the dialog creation handler was properly called
if (bHandled)
return hr;
// try to create a primary extension handler (partial UI replacement)
CCreateNewObjectWizardBase wiz(pNewADsObjectCreateInfo);
hr = wiz.InitPrimaryExtension();
if (SUCCEEDED(hr))
{
bHandled = TRUE;
hr = wiz.DoModal();
}
// check if the dialog creation handler was properly called
if (bHandled)
return hr;
// The handler failed, need to recover, trying our internal creation UI
PFn_HrCreateADsObject pfnCreateObject = NULL;
PVOID pVoid = NULL;
// we try to find a better handler than the generic wizard
// by looking in our table
if (!FindHandlerFunction(pNewADsObjectCreateInfo->m_pszObjectClass,
&pfnCreateObject, &pVoid))
{
// failed any match
if (pNewADsObjectCreateInfo->IsStandaloneUI())
{
// cannot have generic wizard on standalone UI
return E_INVALIDARG;
}
else
{
// set the default to point to the "Generic Create" wizard
ReportErrorEx(pNewADsObjectCreateInfo->GetParentHwnd(),
IDS_NO_CREATION_WIZARD,
S_OK,
MB_OK | MB_ICONWARNING,
NULL,
0);
pfnCreateObject = HrCreateADsObjectGenericWizard;
}
}
pNewADsObjectCreateInfo->SetCreationParameter(pVoid);
ASSERT(pfnCreateObject != NULL);
// call the function handler as last resort
return pfnCreateObject(pNewADsObjectCreateInfo);
} // HrCreateADsObjectOverride()
| 31.975516 | 152 | 0.657231 | [
"object"
] |
37b4be5e497af8808d5eae82423a560bc9f50e37 | 6,561 | cpp | C++ | segment_util/segmentation_boundary.cpp | ayghor/video_segment | c930c4555ff171e5013d525e218a4d8201ed0d51 | [
"BSD-3-Clause"
] | 159 | 2015-01-14T21:24:12.000Z | 2021-08-29T19:38:27.000Z | segment_util/segmentation_boundary.cpp | Robotertechnik/video_segment | c930c4555ff171e5013d525e218a4d8201ed0d51 | [
"BSD-3-Clause"
] | 21 | 2015-01-06T15:51:10.000Z | 2020-06-21T18:58:01.000Z | segment_util/segmentation_boundary.cpp | Robotertechnik/video_segment | c930c4555ff171e5013d525e218a4d8201ed0d51 | [
"BSD-3-Clause"
] | 86 | 2015-01-14T21:25:29.000Z | 2020-06-21T18:52:19.000Z | // Copyright (c) 2010-2014, The Video Segmentation Project
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * 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 The Video Segmentation Project 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 "segment_util/segmentation_boundary.h"
#include "base/base_impl.h"
namespace segmentation {
namespace {
// Sets buffer to one for each pixel of the scanline.
// Returns x-range of rendered pixels.
pair<int, int> RenderScanInterval(const ScanInterval& scan_inter,
uint8_t* buffer) {
pair<int, int> range(1e6, -1e6);
const int interval_sz = scan_inter.right_x() - scan_inter.left_x() + 1;
range.first = std::min<int>(range.first, scan_inter.left_x());
range.second = std::max<int>(range.second, scan_inter.right_x());
memset(buffer + scan_inter.left_x(), 1, interval_sz);
return range;
}
// Renders all scanlines for a specific y coordinate for all passed rasterizations.
// Returns x-range of rendered pixels.
pair<int, int> RenderScanlines(const vector<const Rasterization*>& rasters,
int y,
uint8_t* buffer) {
pair<int, int> range(1e6, -1e6);
for (const auto r_ptr : rasters) {
auto s = LocateScanLine(y, *r_ptr);
while (s != r_ptr->scan_inter().end() && s->y() == y) {
pair<int, int> ret_range = RenderScanInterval(*s++, buffer);
range.first = std::min<int>(range.first, ret_range.first);
range.second = std::max<int>(range.second, ret_range.second);
}
}
return range;
}
} // namespace.
void GetBoundary(const Rasterization& raster,
int frame_width,
bool inner_boundary,
vector<uchar>* buffer,
RegionBoundary* boundary) {
vector<const SegmentationDesc::Rasterization*> rasters;
rasters.push_back(&raster);
GetBoundary(rasters, frame_width, inner_boundary, buffer, boundary);
}
void GetBoundary(const vector<const Rasterization*>& rasters,
int frame_width,
bool inner_boundary,
vector<uint8_t>* buffer,
RegionBoundary* boundary) {
CHECK_NOTNULL(boundary);
CHECK_NOTNULL(buffer);
if (rasters.empty()) {
return;
}
const int rad = 1;
const int width_step = frame_width + 2 * rad;
if (buffer->size() < 3 * width_step) {
LOG(WARNING) << "Buffer too small, resize to " << 3 * width_step;
buffer->resize(3 * width_step);
}
// Zero buffer.
std::fill(buffer->begin(), buffer->end(), 0);
// Set up scanline pointers.
uint8_t* prev_ptr = &(*buffer)[rad];
uint8_t* curr_ptr = &(*buffer)[rad + width_step];
uint8_t* next_ptr = &(*buffer)[rad + 2 * width_step];
// Determine min and max y.
int min_y = 1e7;
int max_y = -1e7;
for (const auto raster_ptr : rasters) {
CHECK_NOTNULL(raster_ptr);
if (raster_ptr->scan_inter_size() == 0) {
LOG(WARNING) << "Empty rasterization passed to GetBoundary.";
} else {
min_y = std::min<int>(raster_ptr->scan_inter(0).y(), min_y);
max_y = std::max<int>(raster_ptr->scan_inter(raster_ptr->scan_inter_size() - 1).y(),
max_y);
}
}
// Render first scanline.
vector<pair<int, int> > ranges;
if (inner_boundary) {
ranges.push_back(RenderScanlines(rasters, min_y, curr_ptr));
} else {
ranges.push_back(RenderScanlines(rasters, min_y, next_ptr));
}
int shift = inner_boundary ? 0 : 1;
const int range_size = inner_boundary ? 1 : 3;
for (int y = min_y - shift; y <= max_y + shift; ++y) {
// Clear buffer.
memset(next_ptr, 0, frame_width);
if (y < max_y) {
ranges.push_back(RenderScanlines(rasters, y + 1, next_ptr));
}
int min_range = 1e7;
int max_range = -1e7;
for (int k = 0; k < ranges.size(); ++k) {
min_range = std::min(min_range, ranges[k].first);
max_range = std::max(max_range, ranges[k].second);
}
if (min_range <= max_range) {
const uint8_t* prev_x_ptr = prev_ptr + min_range - shift;
const uint8_t* curr_x_ptr = curr_ptr + min_range - shift;
const uint8_t* next_x_ptr = next_ptr + min_range - shift;
for (int x = min_range;
x <= max_range + 2 * shift;
++x, ++prev_x_ptr, ++curr_x_ptr, ++next_x_ptr) {
// A point is a boundary point if the current value for it is set,
// but one of its 4 neighbors is not (inner_boundary, else inverted criteria).
if (inner_boundary) {
if (curr_x_ptr[0] &&
(!curr_x_ptr[-1] || !curr_x_ptr[1] || !prev_x_ptr[0] || !next_x_ptr[0])) {
boundary->push_back(BoundaryPoint(x, y));
}
} else {
if (!curr_x_ptr[0] &&
(curr_x_ptr[-1] || curr_x_ptr[1] || prev_x_ptr[0] || next_x_ptr[0])) {
boundary->push_back(BoundaryPoint(x, y));
}
}
}
}
// Swap with wrap around.
std::swap(prev_ptr, curr_ptr);
std::swap(curr_ptr, next_ptr);
if (ranges.size() >= range_size) {
ranges.erase(ranges.begin());
}
}
}
} // namespace segmentation.
| 36.049451 | 90 | 0.641823 | [
"render",
"vector"
] |
37b511d31504a6f70637ab6469a772ad6f4c543b | 3,219 | cpp | C++ | mainapp/Classes/Games/LetterTrace/Models/LetterTraceLevelData.cpp | JaagaLabs/GLEXP-Team-KitkitSchool | f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0 | [
"Apache-2.0"
] | 45 | 2019-05-16T20:49:31.000Z | 2021-11-05T21:40:54.000Z | mainapp/Classes/Games/LetterTrace/Models/LetterTraceLevelData.cpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 123 | 2019-05-28T14:03:04.000Z | 2019-07-12T04:23:26.000Z | pehlaschool/Classes/Games/LetterTrace/Models/LetterTraceLevelData.cpp | maqsoftware/Pehla-School-Hindi | 61aeae0f1d91952b44eaeaff5d2f6ec1d5aa3c43 | [
"Apache-2.0"
] | 29 | 2019-05-16T17:49:26.000Z | 2021-12-30T16:36:24.000Z | //
// LevelData.cpp -- A collection of Worksheets
// TodoSchool on Oct 14, 2016
//
// Copyright (c) 2016 Enuma, Inc. All rights reserved.
// See LICENSE.md for more details.
//
#include "LetterTraceLevelData.h"
#include "../Utils/LetterTraceMainDepot.h"
#include <Common/Basic/CommentStream.h>
// for data checking
#include "Managers/UserManager.hpp"
#include "3rdParty/CCNativeAlert.h"
#include "Common/Sounds/CommonSound.hpp"
BEGIN_NS_LETTERTRACE
vector<int> LevelData::levelIDsFor(const string& LanguageTag) {
vector<int> IDs;
for (auto LevelItem : Levels) {
auto& Key = LevelItem.first;
if (Key.first != LanguageTag) { continue; }
IDs.push_back((int)Key.second);
}
stable_sort(IDs.begin(), IDs.end());
return IDs;
}
Worksheet& LevelData::randomSheetFor(const string& LanguageTag, size_t LevelID, int *workSheetID) {
auto K = LevelKey(LanguageTag, LevelID);
auto& L = Levels[K];
*workSheetID = random(L.begin_index(), L.end_index()-1);
return L.at( *workSheetID);
}
LevelData LevelData::defaultData() {
LevelData It;
string P = MainDepot().assetPrefix() + "/LetterTrace_Levels.tsv";
string S = FileUtils::getInstance()->getStringFromFile(P);
CommentStream IS(S);
IS >> It;
if (UserManager::getInstance()->isDebugMode()) {
It.checkData();
}
return It;
}
void LevelData::checkData()
{
string errorList = "";
for (auto it : Levels ) {
auto key = it.first;
auto sheets = it.second;
auto lang = it.first.first;
auto level = it.first.second;
for (auto sheet : sheets) {
for (int i = sheet.beginProblemID(); i<sheet.endProblemID(); i++) {
auto p = sheet.problemByID(i);
SoundEffect s1, s2;
string v = "LetterTrace/BonusVideos/" + p.VideoFileName;
if (p.TraceText!="-") s1 = CommonSound().soundForLetterName(p.TraceText);
if (p.FullText!="-") s2 = CommonSound().soundForWord(p.FullText);
if (p.TraceText!="-" && s1.bad()) errorList += "missing sound for letter : ["+p.TraceText+"] ("+lang+")\n";
if (p.FullText!="-" && s2.bad()) {
errorList += "missing sound for word : ["+p.FullText+"] ("+lang+")\n";
}
if (p.VideoFileName!="-" && !FileUtils::getInstance()->isFileExist(v)) errorList += "missing video : ["+p.VideoFileName+"] ("+lang+")\n";
}
}
}
if (errorList.length()>0) {
NativeAlert::show("Error in LetterTrace_Levels.tsv", errorList, "OK");
}
}
istream& operator>>(istream& IS, LevelData& LD) {
string LanguageTag;
size_t LevelID;
while (IS >> LanguageTag >> LevelID)
{
auto K = LevelData::LevelKey(LanguageTag, LevelID);
auto& L = LD.Levels[K];
size_t SheetID;
if (IS >> SheetID) {
L.resize_for_index(SheetID);
auto& S = L.at(SheetID);
IS >> S;
}
}
return IS;
}
END_NS_LETTERTRACE
| 26.385246 | 153 | 0.561354 | [
"vector"
] |
37b5a6cda0000b79ed272edc76ea0d8d6d6bccef | 2,788 | hpp | C++ | include/System/GC.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/GC.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/GC.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Runtime.CompilerServices.Ephemeron
#include "System/Runtime/CompilerServices/Ephemeron.hpp"
// Completed includes
// Type namespace: System
namespace System {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: System.GC
class GC : public ::Il2CppObject {
public:
// Creating value type constructor for type: GC
GC() noexcept {}
// Get static field: static readonly System.Object EPHEMERON_TOMBSTONE
static ::Il2CppObject* _get_EPHEMERON_TOMBSTONE();
// Set static field: static readonly System.Object EPHEMERON_TOMBSTONE
static void _set_EPHEMERON_TOMBSTONE(::Il2CppObject* value);
// static private System.Int32 GetMaxGeneration()
// Offset: 0x1796F64
static int GetMaxGeneration();
// static private System.Void InternalCollect(System.Int32 generation)
// Offset: 0x1796F68
static void InternalCollect(int generation);
// static System.Void register_ephemeron_array(System.Runtime.CompilerServices.Ephemeron[] array)
// Offset: 0x1796F6C
static void register_ephemeron_array(::Array<System::Runtime::CompilerServices::Ephemeron>* array);
// static private System.Object get_ephemeron_tombstone()
// Offset: 0x1796F70
static ::Il2CppObject* get_ephemeron_tombstone();
// static public System.Void Collect()
// Offset: 0x1796F74
static void Collect();
// static public System.Void KeepAlive(System.Object obj)
// Offset: 0x1797030
static void KeepAlive(::Il2CppObject* obj);
// static public System.Int32 get_MaxGeneration()
// Offset: 0x1796FD4
static int get_MaxGeneration();
// static private System.Void _SuppressFinalize(System.Object o)
// Offset: 0x1797034
static void _SuppressFinalize(::Il2CppObject* o);
// static public System.Void SuppressFinalize(System.Object obj)
// Offset: 0x1797038
static void SuppressFinalize(::Il2CppObject* obj);
// static private System.Void _ReRegisterForFinalize(System.Object o)
// Offset: 0x17970DC
static void _ReRegisterForFinalize(::Il2CppObject* o);
// static public System.Void ReRegisterForFinalize(System.Object obj)
// Offset: 0x17970E0
static void ReRegisterForFinalize(::Il2CppObject* obj);
// static private System.Void .cctor()
// Offset: 0x1797184
static void _cctor();
}; // System.GC
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::GC*, "System", "GC");
| 43.5625 | 104 | 0.696915 | [
"object"
] |
37b83ae6a768201602a3b64dafca7c0108982456 | 4,310 | cc | C++ | src/easytest_main.cc | akiyamalab/restretto | bc683bbb06fc5c1e4eb9f8c8d32ddddaac8f6c5b | [
"MIT"
] | null | null | null | src/easytest_main.cc | akiyamalab/restretto | bc683bbb06fc5c1e4eb9f8c8d32ddddaac8f6c5b | [
"MIT"
] | 2 | 2020-06-11T21:48:29.000Z | 2020-06-11T22:02:04.000Z | src/easytest_main.cc | akiyamalab/restretto | bc683bbb06fc5c1e4eb9f8c8d32ddddaac8f6c5b | [
"MIT"
] | null | null | null | #include "common.hpp"
#include "utils.hpp"
#include "OBMol.hpp"
#include "infile_reader.hpp"
#include "EnergyCalculator.hpp"
#include <iostream>
#include <iomanip>
#include <string>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include <sys/stat.h>
#include <chrono>
#include <unordered_map>
namespace {
format::DockingConfiguration parseArgs(int argc, char **argv){
using namespace boost::program_options;
options_description options("Options");
options_description hidden("Hidden options");
positional_options_description pos_desc;
hidden.add_options()
("conf-file", value<std::string>(), "configuration file");
pos_desc.add("conf-file", 1);
options.add_options()
("help,h", "show help")
("output,o", value<std::string>(), "output file (.mol2 file)")
("ligand,l", value<std::vector<std::string> >()->multitoken(), "ligand file")
("receptor,r", value<std::string>(), "receptor file (.pdb file)")
("grid,g", value<std::string>(), "grid folder")
("memsize,m", value<int64_t>(), "fragment grid's memory size[MB]");
options_description desc;
desc.add(options).add(hidden);
variables_map vmap;
store(command_line_parser(argc, argv).
options(desc).positional(pos_desc).run(), vmap);
notify(vmap);
if (!vmap.count("conf-file") || vmap.count("help")){
if (!vmap.count("conf-file") && !vmap.count("help")){
std::cout << "too few arguments" << std::endl;
}
std::cout << "Usage: ligandock conf-file [options]\n"
<< options << std::endl;
std::exit(0);
}
format::DockingConfiguration conf = format::ParseInFile(vmap["conf-file"].as<std::string>().c_str());
if (vmap.count("ligand")) conf.ligand_files = vmap["ligand"].as<std::vector<std::string> >();
if (vmap.count("receptor")) conf.receptor_file = vmap["receptor"].as<std::string>();
if (vmap.count("output")) conf.output_file = vmap["output"].as<std::string>();
if (vmap.count("grid")) conf.grid_folder = vmap["grid"].as<std::string>();
if (vmap.count("memsize")) conf.mem_size = vmap["memsize"].as<int64_t>();
return conf;
}
} // namespace
int main(int argc, char **argv){
using namespace std;
using namespace fragdock;
format::DockingConfiguration config = parseArgs(argc, argv);
// parse receptor file
OpenBabel::OBMol receptor = format::ParseFileToOBMol(config.receptor_file.c_str())[0];
Molecule receptor_mol = format::toFragmentMol(receptor);
// parse ligands file
vector<OpenBabel::OBMol> ligands = format::ParseFileToOBMol(config.ligand_files);
int ligs_sz = ligands.size();
vector<Molecule> ligands_mol(ligs_sz);
EnergyCalculator calc(1.0, 0.0);
for (int lig_ind = 0; lig_ind < ligs_sz; ++lig_ind) {
OpenBabel::OBMol& ligand = ligands[lig_ind];
ligand.AddHydrogens();
ligands_mol[lig_ind] = format::toFragmentMol(ligand);
ligand.DeleteHydrogens();
Molecule& mol = ligands_mol[lig_ind];
mol.deleteHydrogens();
mol.setIntraEnergy(calc.getIntraEnergy(mol));
// mol.deleteHydrogens();
// mol.calcRadius();
fltype score = calc.getEnergy(mol, receptor_mol);
fltype final_score = score / (1 + 0.05846 * mol.getNrots());
cout << final_score << '\n';
Vector3d center = mol.getCenter();
// mol.translate(-ofst);
const fltype pi = acos(-1.0);
const int NEAREST_NUM = 200;
fltype trans_step = 0.5;
fltype rotate_step = pi / 30.0;
for(int i = 0; i < NEAREST_NUM; i++) {
Vector3d dv = Vector3d(utils::randf(-trans_step, trans_step),
utils::randf(-trans_step, trans_step),
utils::randf(-trans_step, trans_step));
fltype th = utils::randf(-rotate_step, rotate_step);
fltype phi = utils::randf(-rotate_step, rotate_step);
fltype psi = utils::randf(-rotate_step, rotate_step);
Molecule tmp_mol = mol;
tmp_mol.translate(-center);
tmp_mol.rotate(th, phi, psi);
tmp_mol.translate(center + dv);
// tmp_mol.translate(dv);
fltype val = calc.getEnergy(tmp_mol, receptor_mol);
fltype final_val = val / (1 + 0.05846 * tmp_mol.getNrots());
cout << final_val << '\n';
}
}
return 0;
}
| 34.206349 | 105 | 0.650812 | [
"vector"
] |
37b9184c8c493c6019c7dc38141b417e34c50787 | 1,283 | cpp | C++ | BGE/Lab3.cpp | Confkins/Games-Engines | 1690fa44c227ebab857e04c66fe4bb17cbb1358b | [
"MIT"
] | null | null | null | BGE/Lab3.cpp | Confkins/Games-Engines | 1690fa44c227ebab857e04c66fe4bb17cbb1358b | [
"MIT"
] | null | null | null | BGE/Lab3.cpp | Confkins/Games-Engines | 1690fa44c227ebab857e04c66fe4bb17cbb1358b | [
"MIT"
] | null | null | null | #include "Lab3.h"
#include "Content.h"
#include "VectorDrawer.h"
#include "LazerBeam.h"
using namespace BGE;
Lab3::Lab3(void)
{
elapsed = 10000;
}
bool Lab3::Initialise()
{
std::shared_ptr<GameComponent> ground = make_shared<Ground>();
Attach(ground);
ship1 = make_shared<GameComponent>(true);
ship1->Attach(Content::LoadModel("cobramk3", glm::rotate(glm::mat4(1), 180.0f, glm::vec3(0,1,0))));
ship1->Attach(make_shared<VectorDrawer>(glm::vec3(5,5,5)));
ship1->transform->position = glm::vec3(-10, 2, -10);
Attach(ship1);
ship2 = make_shared<GameComponent>(true);
ship2->Attach(Content::LoadModel("python", glm::rotate(glm::mat4(1), 180.0f, glm::vec3(0,1,0))));
ship2->Attach(make_shared<VectorDrawer>(glm::vec3(5,5,5)));
ship2->transform->position = glm::vec3(10, 2, -10);
Attach(ship2);
Game::Initialise();
camera->transform->position = glm::vec3(0, 4, 20);
return true;
}
void Lab3::Update(float timeDelta)
{
static float timeToFire = 1.0f / 2.0f;
// Movement of ship2
if (keyState[SDL_SCANCODE_UP])
{
ship2->transform->position += ship2->transform->look * speed * timeDelta;
}
if (keyState[SDL_SCANCODE_DOWN])
{
ship2->transform->position -= ship2->transform->look * speed * timeDelta;
}
elapsed += timeDelta;
Game::Update(timeDelta);
}
| 23.759259 | 100 | 0.688231 | [
"transform"
] |
37c258badd986cfa4aa0fd805168170013e13b8d | 2,156 | cpp | C++ | cpp/problems/33_Search_in_Rotated_Sorted_Array/solution.cpp | zerdzhong/LeetCode | a293a4ae3ac32f416c5361f386d027f558a67954 | [
"MIT"
] | null | null | null | cpp/problems/33_Search_in_Rotated_Sorted_Array/solution.cpp | zerdzhong/LeetCode | a293a4ae3ac32f416c5361f386d027f558a67954 | [
"MIT"
] | null | null | null | cpp/problems/33_Search_in_Rotated_Sorted_Array/solution.cpp | zerdzhong/LeetCode | a293a4ae3ac32f416c5361f386d027f558a67954 | [
"MIT"
] | null | null | null | //
// Created by zhongzhendong on 2018-12-28.
//
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <vector>
using namespace std;
/*
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
18 19 20 30 31 0 1 5 8 9 10 11 12 13
18 19 20 30 31 32 33 1 2 3
*/
class Solution {
public:
//binary search like solution
int search(vector<int>& nums, int target) {
size_t nums_size = nums.size();
if (nums_size == 0) return -1;
if (nums_size == 1) return nums[0] == target ? 0 : -1;
int mid = 0, mid_index = 0, start_index = 0, end_index = static_cast<int>(nums_size - 1);
int first_value = nums[0];
while (start_index <= end_index) {
mid_index = start_index + (end_index - start_index) / 2;
mid = nums[mid_index];
if (mid < target) {
if (mid < first_value && target >= first_value) {
end_index = mid_index - 1;
} else {
start_index = mid_index + 1;
}
} else if (mid > target) {
if (mid >= first_value && target < first_value) {
start_index = mid_index + 1;
} else {
end_index = mid_index - 1;
}
} else {
return mid_index;
}
}
return -1;
}
};
static const auto speedup = []()
{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return 0;
}();
TEST_CASE("SearchRotatedSortedArray") {
vector<int> nums = {4,5,6,7,0,1,2};
auto res = Solution().search(nums, 0);
REQUIRE( res == 4);
nums = {4,5,6,7,0,1,2};
res = Solution().search(nums, 7);
REQUIRE( res == 3);
nums = {5,1,3};
res = Solution().search(nums, 5);
REQUIRE( res == 0);
}
| 25.666667 | 100 | 0.54731 | [
"vector"
] |
37cae059d9b62956f57abe7c2ec35fceeb5a2a8a | 23,229 | hpp | C++ | networking-ts-impl-master/include/experimental/__net_ts/impl/read_until.hpp | mjcaisse/cppnow-2017-network-ts-material | 128bcf2a718e8f13c2991520a56ddc41b3ccb28b | [
"BSL-1.0"
] | 5 | 2017-05-19T23:03:26.000Z | 2021-05-03T13:40:19.000Z | networking-ts-impl-master/include/experimental/__net_ts/impl/read_until.hpp | mjcaisse/cppnow-2017-network-ts-material | 128bcf2a718e8f13c2991520a56ddc41b3ccb28b | [
"BSL-1.0"
] | 1 | 2018-05-15T18:40:33.000Z | 2018-05-15T18:40:33.000Z | networking-ts-impl-master/include/experimental/__net_ts/impl/read_until.hpp | mjcaisse/cppnow-2017-network-ts-material | 128bcf2a718e8f13c2991520a56ddc41b3ccb28b | [
"BSL-1.0"
] | 2 | 2017-10-03T13:23:34.000Z | 2018-04-23T16:19:11.000Z | //
// impl/read_until.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef NET_TS_IMPL_READ_UNTIL_HPP
#define NET_TS_IMPL_READ_UNTIL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <algorithm>
#include <string>
#include <vector>
#include <utility>
#include <experimental/__net_ts/associated_allocator.hpp>
#include <experimental/__net_ts/associated_executor.hpp>
#include <experimental/__net_ts/buffer.hpp>
#include <experimental/__net_ts/buffers_iterator.hpp>
#include <experimental/__net_ts/detail/bind_handler.hpp>
#include <experimental/__net_ts/detail/handler_alloc_helpers.hpp>
#include <experimental/__net_ts/detail/handler_cont_helpers.hpp>
#include <experimental/__net_ts/detail/handler_invoke_helpers.hpp>
#include <experimental/__net_ts/detail/handler_type_requirements.hpp>
#include <experimental/__net_ts/detail/limits.hpp>
#include <experimental/__net_ts/detail/throw_error.hpp>
#include <experimental/__net_ts/detail/push_options.hpp>
namespace std {
namespace experimental {
namespace net {
inline namespace v1 {
template <typename SyncReadStream, typename DynamicBuffer>
inline std::size_t read_until(SyncReadStream& s,
NET_TS_MOVE_ARG(DynamicBuffer) buffers, char delim)
{
std::error_code ec;
std::size_t bytes_transferred = read_until(s,
NET_TS_MOVE_CAST(DynamicBuffer)(buffers), delim, ec);
std::experimental::net::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer>
std::size_t read_until(SyncReadStream& s,
NET_TS_MOVE_ARG(DynamicBuffer) buffers,
char delim, std::error_code& ec)
{
typename decay<DynamicBuffer>::type b(
NET_TS_MOVE_CAST(DynamicBuffer)(buffers));
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = b.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
iterator iter = std::find(start_pos, end, delim);
if (iter != end)
{
// Found a match. We're done.
ec = std::error_code();
return iter - begin + 1;
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
b.commit(s.read_some(b.prepare(bytes_to_read), ec));
if (ec)
return 0;
}
}
template <typename SyncReadStream, typename DynamicBuffer>
inline std::size_t read_until(SyncReadStream& s,
NET_TS_MOVE_ARG(DynamicBuffer) buffers,
NET_TS_STRING_VIEW_PARAM delim)
{
std::error_code ec;
std::size_t bytes_transferred = read_until(s,
NET_TS_MOVE_CAST(DynamicBuffer)(buffers), delim, ec);
std::experimental::net::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
namespace detail
{
// Algorithm that finds a subsequence of equal values in a sequence. Returns
// (iterator,true) if a full match was found, in which case the iterator
// points to the beginning of the match. Returns (iterator,false) if a
// partial match was found at the end of the first sequence, in which case
// the iterator points to the beginning of the partial match. Returns
// (last1,false) if no full or partial match was found.
template <typename Iterator1, typename Iterator2>
std::pair<Iterator1, bool> partial_search(
Iterator1 first1, Iterator1 last1, Iterator2 first2, Iterator2 last2)
{
for (Iterator1 iter1 = first1; iter1 != last1; ++iter1)
{
Iterator1 test_iter1 = iter1;
Iterator2 test_iter2 = first2;
for (;; ++test_iter1, ++test_iter2)
{
if (test_iter2 == last2)
return std::make_pair(iter1, true);
if (test_iter1 == last1)
{
if (test_iter2 != first2)
return std::make_pair(iter1, false);
else
break;
}
if (*test_iter1 != *test_iter2)
break;
}
}
return std::make_pair(last1, false);
}
} // namespace detail
template <typename SyncReadStream, typename DynamicBuffer>
std::size_t read_until(SyncReadStream& s,
NET_TS_MOVE_ARG(DynamicBuffer) buffers,
NET_TS_STRING_VIEW_PARAM delim, std::error_code& ec)
{
typename decay<DynamicBuffer>::type b(
NET_TS_MOVE_CAST(DynamicBuffer)(buffers));
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = b.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = detail::partial_search(
start_pos, end, delim.begin(), delim.end());
if (result.first != end)
{
if (result.second)
{
// Full match. We're done.
ec = std::error_code();
return result.first - begin + delim.length();
}
else
{
// Partial match. Next search needs to start from beginning of match.
search_position = result.first - begin;
}
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
b.commit(s.read_some(b.prepare(bytes_to_read), ec));
if (ec)
return 0;
}
}
namespace detail
{
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
class read_until_delim_op
{
public:
template <typename BufferSequence>
read_until_delim_op(AsyncReadStream& stream,
NET_TS_MOVE_ARG(BufferSequence) buffers,
char delim, ReadHandler& handler)
: stream_(stream),
buffers_(NET_TS_MOVE_CAST(BufferSequence)(buffers)),
delim_(delim),
start_(0),
search_position_(0),
handler_(NET_TS_MOVE_CAST(ReadHandler)(handler))
{
}
#if defined(NET_TS_HAS_MOVE)
read_until_delim_op(const read_until_delim_op& other)
: stream_(other.stream_),
buffers_(other.buffers_),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
handler_(other.handler_)
{
}
read_until_delim_op(read_until_delim_op&& other)
: stream_(other.stream_),
buffers_(NET_TS_MOVE_CAST(DynamicBuffer)(other.buffers_)),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
handler_(NET_TS_MOVE_CAST(ReadHandler)(other.handler_))
{
}
#endif // defined(NET_TS_HAS_MOVE)
void operator()(const std::error_code& ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t bytes_to_read;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = buffers_.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
iterator iter = std::find(start_pos, end, delim_);
if (iter != end)
{
// Found a match. We're done.
search_position_ = iter - begin + 1;
bytes_to_read = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read = 0;
}
// Need to read some more data.
else
{
// Next search can start with the new data.
search_position_ = end - begin;
bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read == 0)
break;
// Start a new asynchronous read operation to obtain more data.
stream_.async_read_some(buffers_.prepare(bytes_to_read),
NET_TS_MOVE_CAST(read_until_delim_op)(*this));
return; default:
buffers_.commit(bytes_transferred);
if (ec || bytes_transferred == 0)
break;
}
const std::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
handler_(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer buffers_;
char delim_;
int start_;
std::size_t search_position_;
ReadHandler handler_;
};
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void* networking_ts_handler_allocate(std::size_t size,
read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
return networking_ts_handler_alloc_helpers::allocate(
size, this_handler->handler_);
}
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void networking_ts_handler_deallocate(void* pointer, std::size_t size,
read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
networking_ts_handler_alloc_helpers::deallocate(
pointer, size, this_handler->handler_);
}
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline bool networking_ts_handler_is_continuation(
read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: networking_ts_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Function, typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void networking_ts_handler_invoke(Function& function,
read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
networking_ts_handler_invoke_helpers::invoke(
function, this_handler->handler_);
}
template <typename Function, typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void networking_ts_handler_invoke(const Function& function,
read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
networking_ts_handler_invoke_helpers::invoke(
function, this_handler->handler_);
}
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename AsyncReadStream, typename DynamicBuffer,
typename ReadHandler, typename Allocator>
struct associated_allocator<
detail::read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>,
Allocator>
{
typedef typename associated_allocator<ReadHandler, Allocator>::type type;
static type get(
const detail::read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>& h,
const Allocator& a = Allocator()) NET_TS_NOEXCEPT
{
return associated_allocator<ReadHandler, Allocator>::get(h.handler_, a);
}
};
template <typename AsyncReadStream, typename DynamicBuffer,
typename ReadHandler, typename Executor>
struct associated_executor<
detail::read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>,
Executor>
{
typedef typename associated_executor<ReadHandler, Executor>::type type;
static type get(
const detail::read_until_delim_op<AsyncReadStream,
DynamicBuffer, ReadHandler>& h,
const Executor& ex = Executor()) NET_TS_NOEXCEPT
{
return associated_executor<ReadHandler, Executor>::get(h.handler_, ex);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
NET_TS_INITFN_RESULT_TYPE(ReadHandler,
void (std::error_code, std::size_t))
async_read_until(AsyncReadStream& s,
NET_TS_MOVE_ARG(DynamicBuffer) buffers,
char delim, NET_TS_MOVE_ARG(ReadHandler) handler)
{
// If you get an error on the following line it means that your handler does
// not meet the documented type requirements for a ReadHandler.
NET_TS_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
async_completion<ReadHandler,
void (std::error_code, std::size_t)> init(handler);
detail::read_until_delim_op<AsyncReadStream,
typename decay<DynamicBuffer>::type,
NET_TS_HANDLER_TYPE(ReadHandler,
void (std::error_code, std::size_t))>(
s, NET_TS_MOVE_CAST(DynamicBuffer)(buffers),
delim, init.completion_handler)(std::error_code(), 0, 1);
return init.result.get();
}
namespace detail
{
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
class read_until_delim_string_op
{
public:
template <typename BufferSequence>
read_until_delim_string_op(AsyncReadStream& stream,
NET_TS_MOVE_ARG(BufferSequence) buffers,
const std::string& delim, ReadHandler& handler)
: stream_(stream),
buffers_(NET_TS_MOVE_CAST(BufferSequence)(buffers)),
delim_(delim),
start_(0),
search_position_(0),
handler_(NET_TS_MOVE_CAST(ReadHandler)(handler))
{
}
#if defined(NET_TS_HAS_MOVE)
read_until_delim_string_op(const read_until_delim_string_op& other)
: stream_(other.stream_),
buffers_(other.buffers_),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
handler_(other.handler_)
{
}
read_until_delim_string_op(read_until_delim_string_op&& other)
: stream_(other.stream_),
buffers_(NET_TS_MOVE_CAST(DynamicBuffer)(other.buffers_)),
delim_(NET_TS_MOVE_CAST(std::string)(other.delim_)),
start_(other.start_),
search_position_(other.search_position_),
handler_(NET_TS_MOVE_CAST(ReadHandler)(other.handler_))
{
}
#endif // defined(NET_TS_HAS_MOVE)
void operator()(const std::error_code& ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t bytes_to_read;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = buffers_.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = detail::partial_search(
start_pos, end, delim_.begin(), delim_.end());
if (result.first != end && result.second)
{
// Full match. We're done.
search_position_ = result.first - begin + delim_.length();
bytes_to_read = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read = 0;
}
// Need to read some more data.
else
{
if (result.first != end)
{
// Partial match. Next search needs to start from beginning of
// match.
search_position_ = result.first - begin;
}
else
{
// Next search can start with the new data.
search_position_ = end - begin;
}
bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read == 0)
break;
// Start a new asynchronous read operation to obtain more data.
stream_.async_read_some(buffers_.prepare(bytes_to_read),
NET_TS_MOVE_CAST(read_until_delim_string_op)(*this));
return; default:
buffers_.commit(bytes_transferred);
if (ec || bytes_transferred == 0)
break;
}
const std::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
handler_(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer buffers_;
std::string delim_;
int start_;
std::size_t search_position_;
ReadHandler handler_;
};
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void* networking_ts_handler_allocate(std::size_t size,
read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
return networking_ts_handler_alloc_helpers::allocate(
size, this_handler->handler_);
}
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void networking_ts_handler_deallocate(void* pointer, std::size_t size,
read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
networking_ts_handler_alloc_helpers::deallocate(
pointer, size, this_handler->handler_);
}
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline bool networking_ts_handler_is_continuation(
read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: networking_ts_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Function, typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void networking_ts_handler_invoke(Function& function,
read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
networking_ts_handler_invoke_helpers::invoke(
function, this_handler->handler_);
}
template <typename Function, typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
inline void networking_ts_handler_invoke(const Function& function,
read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>* this_handler)
{
networking_ts_handler_invoke_helpers::invoke(
function, this_handler->handler_);
}
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename AsyncReadStream, typename DynamicBuffer,
typename ReadHandler, typename Allocator>
struct associated_allocator<
detail::read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>,
Allocator>
{
typedef typename associated_allocator<ReadHandler, Allocator>::type type;
static type get(
const detail::read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>& h,
const Allocator& a = Allocator()) NET_TS_NOEXCEPT
{
return associated_allocator<ReadHandler, Allocator>::get(h.handler_, a);
}
};
template <typename AsyncReadStream, typename DynamicBuffer,
typename ReadHandler, typename Executor>
struct associated_executor<
detail::read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>,
Executor>
{
typedef typename associated_executor<ReadHandler, Executor>::type type;
static type get(
const detail::read_until_delim_string_op<AsyncReadStream,
DynamicBuffer, ReadHandler>& h,
const Executor& ex = Executor()) NET_TS_NOEXCEPT
{
return associated_executor<ReadHandler, Executor>::get(h.handler_, ex);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
template <typename AsyncReadStream,
typename DynamicBuffer, typename ReadHandler>
NET_TS_INITFN_RESULT_TYPE(ReadHandler,
void (std::error_code, std::size_t))
async_read_until(AsyncReadStream& s,
NET_TS_MOVE_ARG(DynamicBuffer) buffers,
NET_TS_STRING_VIEW_PARAM delim,
NET_TS_MOVE_ARG(ReadHandler) handler)
{
// If you get an error on the following line it means that your handler does
// not meet the documented type requirements for a ReadHandler.
NET_TS_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
async_completion<ReadHandler,
void (std::error_code, std::size_t)> init(handler);
detail::read_until_delim_string_op<AsyncReadStream,
typename decay<DynamicBuffer>::type,
NET_TS_HANDLER_TYPE(ReadHandler,
void (std::error_code, std::size_t))>(
s, NET_TS_MOVE_CAST(DynamicBuffer)(buffers),
static_cast<std::string>(delim),
init.completion_handler)(std::error_code(), 0, 1);
return init.result.get();
}
} // inline namespace v1
} // namespace net
} // namespace experimental
} // namespace std
#include <experimental/__net_ts/detail/pop_options.hpp>
#endif // NET_TS_IMPL_READ_UNTIL_HPP
| 32.579243 | 79 | 0.66813 | [
"vector"
] |
56cceaec95d5483119282b689650e18521cb036c | 8,517 | cpp | C++ | custom_glv/src/glv_layout.cpp | mntmn/produce | 5c7d9c4045992996c1333b1ec608044f4fbd3498 | [
"MIT"
] | 52 | 2015-02-22T22:12:17.000Z | 2021-02-23T15:13:22.000Z | custom_glv/src/glv_layout.cpp | mntmn/produce | 5c7d9c4045992996c1333b1ec608044f4fbd3498 | [
"MIT"
] | 1 | 2016-04-24T21:47:20.000Z | 2016-04-24T21:47:20.000Z | custom_glv/src/glv_layout.cpp | mntmn/produce | 5c7d9c4045992996c1333b1ec608044f4fbd3498 | [
"MIT"
] | null | null | null | /* Graphics Library of Views (GLV) - GUI Building Toolkit
See COPYRIGHT file for authors and license information */
#include "glv_layout.h"
namespace glv{
Placer::Placer(space_t absX, space_t absY)
: x(absX), y(absY), rx(0), ry(0), ax(0), ay(0), fw(0), fh(0), mAnchor((Place::t)0), parent(0)
{}
Placer::Placer(View& parent, Direction dir, Place::t ali, space_t x, space_t y, space_t pad)
: x(x), y(y), rx(1), ry(1), mAnchor((Place::t)0), parent(&parent)
{
flow(dir, pad);
align(ali);
}
Placer& Placer::operator<< (View& v){
v.Rect::pos(x - v.w * fw, y - v.h * fh);
x += rx * v.w + ax;
y += ry * v.h + ay;
if(mAnchor) v.anchor(mAnchor);
if(parent) (*parent) << v;
return *this;
}
Placer& Placer::operator<< (View* v){
return v ? (*this)<<*v : *this;
}
Placer& Placer::abs(space_t vx, space_t vy){ ax=vx; ay=vy; return *this; }
Placer& Placer::align(space_t vx, space_t vy){ fw=vx; fh=vy; return *this; }
Placer& Placer::align(Place::t p){
switch(p){
case Place::TL: return align(0.0, 0.0);
case Place::TC: return align(0.5, 0.0);
case Place::TR: return align(1.0, 0.0);
case Place::CL: return align(0.0, 0.5);
case Place::CC: return align(0.5, 0.5);
case Place::CR: return align(1.0, 0.5);
case Place::BL: return align(0.0, 1.0);
case Place::BC: return align(0.5, 1.0);
case Place::BR: return align(1.0, 1.0);
default: return *this;
}
}
Placer& Placer::anchor(Place::t p){ mAnchor = p; return *this; }
Placer& Placer::flow(Direction d){
ax < 0 ? ax = -ax : 0;
ay < 0 ? ay = -ay : 0;
rx < 0 ? rx = -rx : 0;
ry < 0 ? ry = -ry : 0;
return flow(d, ax > ay ? ax : ay, rx > ry ? rx : ry);
}
Placer& Placer::flow(Direction d, space_t va, space_t vr){
switch(d){
case Direction::S: return abs( 0, va).rel( 0, vr);
case Direction::E: return abs( va, 0).rel( vr, 0);
case Direction::N: return abs( 0,-va).rel( 0,-vr);
case Direction::W: return abs(-va, 0).rel(-vr, 0);
default: return *this;
}
}
Placer& Placer::pos(space_t vx, space_t vy){ x=vx; y=vy; return *this; }
Placer& Placer::posX(space_t v){ x=v; return *this; }
Placer& Placer::posY(space_t v){ y=v; return *this; }
Placer& Placer::rel(space_t vx, space_t vy){ rx=vx; ry=vy; return *this; }
LayoutFunc::LayoutFunc(space_t w, space_t h, const Rect& bounds)
: elem(0,0,w,h), bounds(bounds), parent(0)
{}
LayoutFunc::~LayoutFunc()
{}
void LayoutFunc::layoutChildren(View& pv){
View * cv = pv.child;
while(cv){
cv->set((*this)());
cv = cv->sibling;
}
}
LayoutGrid::LayoutGrid(space_t w, space_t h, const Rect& b, int numV, int numH)
: LayoutFunc(w,h, b), numV(numV), numH(numH), cntV(0), cntH(0)
{}
LayoutGrid::LayoutGrid(space_t pad, const Rect& b, int numV, int numH)
: LayoutFunc((b.w - pad)/numH - pad, (b.h - pad)/numV - pad, b),
numV(numV), numH(numH), cntV(0), cntH(0)
{
bounds.l += pad;
bounds.t += pad;
bounds.w -= pad;
bounds.h -= pad;
}
LayoutGrid::LayoutGrid(View& p, int numH, int numV, space_t pad)
: LayoutFunc((p.w - pad)/numH - pad, (p.h - pad)/numV - pad, Rect(p.w, p.h)),
numV(numV), numH(numH), cntV(0), cntH(0)
{
bounds.l += pad;
bounds.t += pad;
bounds.w -= pad;
bounds.h -= pad;
parent = &p;
}
LayoutGrid::~LayoutGrid()
{}
Rect& LayoutGrid::operator()(){
elem.l = cntH/(float)numH * bounds.w + bounds.l;
elem.t = cntV/(float)numV * bounds.h + bounds.t;
if(++cntH == numH){
cntH=0;
if(++cntV == numV) cntV=0;
}
return elem;
}
Table::Table(const char * a, space_t padX, space_t padY, const Rect& r)
: Group(r), mSize1(0), mSize2(0), mPad1(padX), mPad2(padY)
{ arrangement(a); }
Table& Table::arrange(){
View * vp = child;
int ind = 0;
// Check if we have more children than the arrangement string accounts for.
// If so, then "fix" the string by creating additional copies.
int numChildren=0;
while(vp){ ++numChildren; vp=vp->sibling; }
if(numChildren > (int)mCells.size()){
std::string a = mAlign;
//int sizeCells = mCells.size();
int numCopies = (numChildren-1)/mCells.size();
for(int i=0; i<numCopies; ++i){ a+=","; a+=mAlign; }
arrangement(a.c_str());
}
// compute extent of table
mColWs.resize(mSize1);
mRowHs.resize(mSize2);
mColWs.assign(mColWs.size(), 0);
mRowHs.assign(mRowHs.size(), 0);
// resize table according to non-spanning cells
vp = child; ind=0;
while(vp){
View& v = *vp;
Cell& c = mCells[ind];
int i1=c.x, i2=c.y;
c.view = vp;
// c.w or c.h equal to 1 mean contents span 1 cell
if(c.w == 1 && v.w > mColWs[i1]) mColWs[i1] = v.w;
if(c.h == 1 && v.h > mRowHs[i2]) mRowHs[i2] = v.h;
vp = vp->sibling; ++ind;
}
// resize table according to spanning cells
for(unsigned i=0; i<mCells.size(); ++i){
Cell& c = mCells[i];
if(0 == c.view) continue;
View& v = *c.view;
if(c.w != 1){
int beg = c.x;
int end = c.x + c.w;
space_t cur = sumSpan(&mColWs[0], end, beg) + (c.w-1)*mPad1;
if(v.w > cur){
space_t add = (v.w - cur)/c.w;
for(int j=beg; j<end; ++j) mColWs[j] += add;
}
}
if(c.h != 1){
int beg = c.y;
int end = c.y + c.h;
space_t cur = sumSpan(&mRowHs[0], end, beg) + (c.h-1)*mPad2;
if(v.h > cur){
space_t add = (v.h - cur)/c.h;
for(int j=beg; j<end; ++j) mRowHs[j] += add;
}
}
}
// We need to compute the actual number of rows in the table here, because
// mSize2 may actually be larger...
// search for first non-zero row height from back
int ny=mSize2-1;
for(; ny>=0; --ny){
if(mRowHs[ny] != 0) break;
}
++ny;
//printf("%d %d\n", ny+1, mSize2);
//mSize2 = ny+1; // this causes a crash next time arrange is called???
space_t accW = sumSpan(&mColWs[0], mSize1) + mPad1*(mSize1+1);
//space_t accH = sumSpan(mRowHs, mSize2) + mPad2*(mSize2+1);
space_t accH = sumSpan(&mRowHs[0], ny) + mPad2*(ny+1);
extent(accW, accH);
// position child views
for(unsigned i=0; i<mCells.size(); ++i){
Cell& c = mCells[i];
if(0 == c.view) continue;
View& v = *c.view;
int i1=c.x, i2=c.y;
space_t padl = mPad1*(i1+1);
space_t padt = mPad2*(i2+1);
space_t padr = (c.w-1)*mPad1;
space_t padb = (c.h-1)*mPad2;
space_t pl = sumSpan(&mColWs[0], i1) + padl;
space_t pt = sumSpan(&mRowHs[0], i2) + padt;
space_t pr = sumSpan(&mColWs[0], i1+c.w, i1) + pl+padr;
space_t pb = sumSpan(&mRowHs[0], i2+c.h, i2) + pt+padb;
space_t cx = (pr-pl)*0.5;
space_t cy = (pb-pt)*0.5;
#define CS(c, p, x, y) case c: v.anchor(Place::p).pos(Place::p, x, y); break;
switch(c.code){
CS('x', CC, pl+cx, pt+cy)
CS('<', CL, pl, pt+cy)
CS('>', CR, pr, pt+cy)
CS('^', TC, pl+cx, pt)
CS('v', BC, pl+cx, pb)
CS('p', TL, pl, pt)
CS('q', TR, pr, pt)
CS('b', BL, pl, pb)
CS('d', BR, pr, pb)
};
#undef CS
}
return *this;
}
Table& Table::arrangement(const char * va){
mAlign = va;
mCells.clear();
mSize1=0; mSize2=1;
bool count1=true;
// derive the number of rows and columns from the arrangement string
const char * v = va;
while(*v){
char c = *v++;
if(isAlignCode(c) || ('.' == c) || ('-' == c) || ('|' == c)){
if(count1) ++mSize1;
}
else if(c==','){
++mSize2;
count1=false;
}
}
//printf("%d %d\n", mSize1, mSize2);
// compute and store geometry of table cells
v = va;
int ind=-1, indCell=-1;
while(*v){
if(isAlignCode(*v)){
++ind;
++indCell;
int ix = ind % mSize1;
int iy = (ind / mSize1) % mSize2;
mCells.push_back(Cell(ix, iy, 1, 1, *v));
}
else if('.' == *v){
++ind;
}
else if('-' == *v && indCell>=0){
mCells[indCell].w++;
++ind;
}
else if('|' == *v){
++ind;
int col = ind % mSize1;
// find first cell matching column number and inc its y span
for(unsigned i=0; i<mCells.size(); ++i){
Cell& c = mCells[i];
if(c.x == col && isAlignCode(c.code)) c.h++;
}
}
++v;
}
return *this;
}
void Table::onDraw(GLV& g){
// for(unsigned i=0; i<mColWs.size(); ++i) printf("%g ", mColWs[i]); printf("\n");
// for(unsigned i=0; i<mRowHs.size(); ++i) printf("%g ", mRowHs[i]); printf("\n\n");
// using namespace glv::draw;
// if(enabled(DrawGrid)){
// color(colors().border);
// lineWidth(1);
// for(unsigned i=0; i<mCells.size(); ++i){
// Cell& c = mCells[i];
// //printf("%d %d %d %d\n", c.x, c.y, c.w, c.h);
// space_t cl = sumSpan(&mColWs[0], c.x) + c.x*mPad1;
// space_t ct = sumSpan(&mRowHs[0], c.y) + c.y*mPad2;
// space_t cw = sumSpan(&mColWs[0], c.x+c.w, c.x) + c.w*mPad1;
// space_t ch = sumSpan(&mRowHs[0], c.y+c.h, c.y) + c.h*mPad2;
// frame(cl, ct, cl+cw, ct+ch);
// }
// }
}
} // glv::
| 23.724234 | 93 | 0.579312 | [
"geometry"
] |
56cde4eeeb1682550b0bb773d81d13944e7cfe9b | 2,920 | hpp | C++ | lib/sfml/include/sfml/SceneGame.hpp | Brukols/Epitech-Arcade | 5443d28169e9494f0c77abac23f4139e60b46365 | [
"MIT"
] | null | null | null | lib/sfml/include/sfml/SceneGame.hpp | Brukols/Epitech-Arcade | 5443d28169e9494f0c77abac23f4139e60b46365 | [
"MIT"
] | null | null | null | lib/sfml/include/sfml/SceneGame.hpp | Brukols/Epitech-Arcade | 5443d28169e9494f0c77abac23f4139e60b46365 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** Arcade
** File description:
** SceneGame
*/
#ifndef SCENEGAME_HPP
#define SCENEGAME_HPP
#include "sfml/IScene.hpp"
#include <vector>
#include "sfml/Button.hpp"
#include "sfml/Text.hpp"
#include "ErrorMessage.hpp"
#include <memory>
#include "sfml/ScenePause.hpp"
namespace arc
{
class SceneGame : public IScene {
public:
SceneGame();
~SceneGame();
void init() override;
void display(sf::RenderWindow &window) override;
void event(sf::RenderWindow &window, arc::Event::Type &_actualEventType, arc::Event::Key &_actualKeyPress) override;
void setFont(const sf::Font &font);
void eventFunctionBackToMenu(std::function<void()> event);
void setMapSize(size_t height, size_t width);
void updateGameInfo(const std::vector<std::shared_ptr<Entity>> &gameMap);
void setControls(const std::map<std::pair<Event::Type, Event::Key>, std::function<void ()>> &controls);
void setHowToPlay(const std::vector<std::pair<std::string, std::string>> &info);
void setGameStats(const std::vector<std::pair<std::string, std::string>> &info);
void setTitle(const std::string &name);
void setFunctionTogglePause(const std::function<void()> &function);
void setFunctionMenu(const std::function<void()> &function);
void setGamePause(bool pause);
private:
void initButtons();
void initTexts();
void initRects();
void eventButtons(sf::RenderWindow &window, sf::Event &event);
void displayGame(sf::RenderWindow &window);
void eventErrorMessage(sf::Event &event, sf::RenderWindow &window);
void initTextHowToPlay(const std::vector<std::pair<std::string, std::string>> &info);
void initTextStats(const std::vector<std::pair<std::string, std::string>> &info);
void eventFunctionBackToMenu();
private:
std::vector<std::pair<std::unique_ptr<Button>, void (SceneGame::*)()>> _buttons;
std::vector<Text> _texts;
std::vector<sf::RectangleShape> _rects;
sf::Font _font;
std::function<void()> _eventFunctionBackToMenu;
size_t _mapWidth;
size_t _mapHeight;
sf::RectangleShape _cell;
std::map<std::string, sf::Texture> _textureMap;
std::vector<std::shared_ptr<Entity>> _gameMap;
std::map<std::pair<Event::Type, Event::Key>, std::function<void ()>> _controls;
std::vector<ErrorMessage> _errorMessages;
std::vector<Text> _stats;
std::vector<Text> _howToPlay;
bool _exit = false;
std::string _title;
std::unique_ptr<ScenePause> _scenePause;
};
}
#endif /* !SCENEGAME_HPP */
| 31.06383 | 128 | 0.606849 | [
"vector"
] |
56d709bdc9bff46cb4610f235cde29bd12d9a4c3 | 671 | cpp | C++ | VirCA_RoboTester/GeneratedFiles/qrc_qtRoboTester.cpp | fletli/VirCA_RoboTester | 4aa6b35a1fc62ba8c715820a25d3ae2236d71da8 | [
"MIT"
] | null | null | null | VirCA_RoboTester/GeneratedFiles/qrc_qtRoboTester.cpp | fletli/VirCA_RoboTester | 4aa6b35a1fc62ba8c715820a25d3ae2236d71da8 | [
"MIT"
] | null | null | null | VirCA_RoboTester/GeneratedFiles/qrc_qtRoboTester.cpp | fletli/VirCA_RoboTester | 4aa6b35a1fc62ba8c715820a25d3ae2236d71da8 | [
"MIT"
] | null | null | null | /****************************************************************************
** Resource object code
**
** Created by: The Resource Compiler for Qt version 5.3.1
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <QtCore/qglobal.h>
QT_BEGIN_NAMESPACE
QT_END_NAMESPACE
int QT_MANGLE_NAMESPACE(qInitResources_qtRoboTester)()
{
return 1;
}
Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_qtRoboTester))
int QT_MANGLE_NAMESPACE(qCleanupResources_qtRoboTester)()
{
return 1;
}
Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_qtRoboTester))
| 22.366667 | 78 | 0.611028 | [
"object"
] |
56df419b465dd164759a76e40d1a8010bd7428f6 | 1,936 | cpp | C++ | code/wxWidgets/src/mgl/dcclient.cpp | Bloodknight/NeuTorsion | a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea | [
"MIT"
] | 38 | 2016-02-20T02:46:28.000Z | 2021-11-17T11:39:57.000Z | code/wxWidgets/src/mgl/dcclient.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 17 | 2016-02-20T02:19:55.000Z | 2021-02-08T15:15:17.000Z | code/wxWidgets/src/mgl/dcclient.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 46 | 2016-02-20T02:47:33.000Z | 2021-01-31T15:46:05.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: dcclient.cpp
// Purpose:
// Author: Vaclav Slavik
// RCS-ID: $Id: dcclient.cpp,v 1.13 2004/05/23 20:52:45 JS Exp $
// Copyright: (c) 2001-2002 SciTech Software, Inc. (www.scitechsoft.com)
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "dcclient.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/dcclient.h"
#include "wx/window.h"
#endif
#include <mgraph.hpp>
IMPLEMENT_DYNAMIC_CLASS(wxWindowDC, wxDC)
IMPLEMENT_DYNAMIC_CLASS(wxClientDC,wxWindowDC)
IMPLEMENT_DYNAMIC_CLASS(wxPaintDC, wxClientDC)
wxWindowDC::wxWindowDC(wxWindow *win) : m_wnd(win)
{
MGLDevCtx *dc = win->GetPaintMGLDC();
if ( dc )
{
m_inPaintHandler = TRUE;
m_globalClippingRegion = win->GetUpdateRegion();
SetMGLDC(dc, FALSE);
}
else
{
m_inPaintHandler = FALSE;
dc = new MGLDevCtx(MGL_wmBeginPaint(win->GetHandle()));
MGLRegion clip;
dc->getClipRegion(clip);
m_globalClippingRegion = wxRegion(clip);
SetMGLDC(dc, TRUE);
// TRUE means that dtor will delete MGLDevCtx object
// but it won't destroy MGLDC returned by MGL_wmBeginPaint because
// ~MGLDevCtx() doesn't call destroy()
}
}
wxWindowDC::~wxWindowDC()
{
if ( !m_inPaintHandler )
{
GetMGLDC()->setDC(NULL);
MGL_wmEndPaint(m_wnd->GetHandle());
}
}
wxClientDC::wxClientDC(wxWindow *win) : wxWindowDC(win)
{
wxRect r = m_wnd->GetClientRect();
m_globalClippingRegion.Intersect(r);
SetClippingRegion(m_globalClippingRegion);
SetDeviceOrigin(r.x, r.y);
}
| 25.813333 | 77 | 0.607438 | [
"object"
] |
56e47cff7857017ae4f414090ac2bb7c83a7eecb | 8,370 | cpp | C++ | smarttraffic-demo2.0/main.cpp | ThunderSoft-XA/C610-smarttraffic-demo2.0 | b2c50e812e4070ce7bbb067240ea0cd6bed098de | [
"Unlicense"
] | 5 | 2021-07-07T08:08:57.000Z | 2022-02-15T05:50:56.000Z | smarttraffic-demo2.0/main.cpp | ThunderSoft-XA/C610-smarttraffic-demo2.0 | b2c50e812e4070ce7bbb067240ea0cd6bed098de | [
"Unlicense"
] | null | null | null | smarttraffic-demo2.0/main.cpp | ThunderSoft-XA/C610-smarttraffic-demo2.0 | b2c50e812e4070ce7bbb067240ea0cd6bed098de | [
"Unlicense"
] | 1 | 2021-07-07T08:09:32.000Z | 2021-07-07T08:09:32.000Z | #include "refreshdata.hpp"
#include "easypr/core/plate_locate.h"
#include "easypr/core/plate_judge.h"
#include "easypr/core/plate.hpp"
#include "easypr/core/plate_recognize.h"
#include "easypr/core/plate_detect.h"
#include "easypr/core/SNPEPlate.hpp"
#include <mcheck.h>
#include <omp.h>
using namespace camera;
using namespace easyui;
using namespace easypr;
using namespace cv;
static SNPEPlate *snpecheck;
static GstFlowReturn on_new_sample (GstAppSink *appsink, RefreshObject *RefreshObject);
void plate_recognize(RefreshData *myFreshData,cv::Mat &src);
void refreshUI (EasyUI *usrUI,RefreshData *usrData);
int main(int argc,char **argv)
{
/* start up malloc trace record log */
setenv("MALLOC_TRACE", "mtrace.log", 1);
mtrace();
GMainLoop *loop;
loop = g_main_loop_new(NULL, FALSE);
cout << __FILE__ << "====" << __LINE__ << endl;
/* start up g_object thread for refresh thread across thread*/
if ( !g_thread_supported() ) {
#ifdef DEBUG
printf("[%s]--Init g_thread./r/n", __FUNCTION__);
#endif // DEBUG
g_thread_init(NULL);
gdk_threads_init();
}
cout << __FILE__ << "====" << __LINE__ << endl;
/* gtk gdk gst init */
gtk_init(&argc,&argv);
gdk_init(&argc,&argv);
gst_init(&argc,&argv);
RefreshObject *myObject;
RefreshData *myRefreshData;
again :
#pragma omp parallel
#pragma omp section
{
#pragma omp section
myObject->dstUI = new EasyUI();
myObject->dstUI->createUI();
cout << __FILE__ << "====" << __LINE__ << endl;
myObject->dstUI->buildSignal("recognition-signal");
myObject->dstUI->buildSignal("refresh-signal");
myObject->dstUI->showUI();
cout << __FILE__ << "====" << __LINE__ << endl;
#pragma omp section
snpecheck = new SNPEPlate();
cout << __FILE__ << "====" << __LINE__ << endl;
snpecheck->init();
#pragma omp section
myObject->srcCamera = new Camera();
do {
if(myObject->srcCamera->checkElements()) {
myObject->srcCamera->setElementsPro();
if(myObject->srcCamera->linkPipeline()) {
assert( myObject->srcCamera->setPipelineStatus(GST_STATE_NULL) != false);
}
}
cout << __FILE__ << "====" << __LINE__ << endl;
} while ( !myObject->srcCamera->flags);
}
if(myObject->srcCamera->flags == false || myObject->dstUI->flags == false || snpecheck->flags == false) {
goto again;
}
cout << __FILE__ << "====" << __LINE__ << endl;
#pragma omp parallel for ordered
{
g_signal_connect(myObject->srcCamera->sink,"new-sample",
G_CALLBACK(on_new_sample),myObject);
cout << __FILE__ << "====" << __LINE__ << endl;
#pragma omp ordered
g_signal_connect(myRefreshData,"recognition-signal",
G_CALLBACK(plate_recognize),&myObject->imgMat);
cout << __FILE__ << "====" << __LINE__ << endl;
g_signal_connect(myObject->dstUI->window,"refresh-signal",
G_CALLBACK(refreshUI),myRefreshData);
}
myObject->srcCamera->signalHandle();
assert (myObject->srcCamera->setPipelineStatus(GST_STATE_PLAYING) != false);
cout << __FILE__ << "====" << __LINE__ << endl;
g_main_loop_run(loop);
gdk_threads_enter();
gtk_main ();
gdk_threads_leave;
myObject->srcCamera->~Camera();
return 0;
}
static GstFlowReturn
on_new_sample (GstAppSink *appsink, RefreshObject *usrRefreshObject)
{
static gint frame_idx = 0;
cv::Mat srcmat;
GstSample *sample = gst_app_sink_pull_sample(appsink);
if(sample == NULL){
if(gst_app_sink_is_eos(appsink))
return GST_FLOW_EOS;
}
cout << __FILE__ << "====" << __LINE__ << endl;
GstBuffer *buffer = gst_sample_get_buffer(sample);
GstCaps *caps = gst_sample_get_caps(sample);
GstMapInfo map_info;
gint width,height;
gst_buffer_map(buffer,&map_info,GST_MAP_READ);
GstStructure *structure = gst_caps_get_structure(caps,0);
gst_structure_get_int(structure,"width",&width);
gst_structure_get_int(structure,"height",&height);
cout << __FILE__ << "====" << __LINE__ << endl;
frame_idx += 1;
cairo_format_t format;
cairo_surface_t *surface;
format = CAIRO_FORMAT_ARGB32;
surface = cairo_image_surface_create_for_data (map_info.data,
format, width, height, cairo_format_stride_for_width(format,width));
gtk_image_set_from_surface(GTK_IMAGE(usrRefreshObject->dstUI->videoDraw),surface);
cout << __FILE__ << "====" << __LINE__ << endl;
char filename[128] = {0};
g_mkdir_with_parents("/data/camera/pictures",0700);
snprintf(filename,sizeof(filename),"/data/camera/pictures/%06d.png",frame_idx);
cairo_status_t st = cairo_surface_write_to_png(surface,filename);
if(st != CAIRO_STATUS_SUCCESS){
g_printerr("st:%s\n",cairo_status_to_string(st));
}
usrRefreshObject->imgMat = imread(filename);
snpecheck->setSrcMat(usrRefreshObject->imgMat);
cout << __FILE__ << "====" << __LINE__ << endl;
if(snpecheck->snpeCheck() > 0 ) {
//emit signal
#pragma omp parallel for ordered
g_signal_emit_by_name (usrRefreshObject->dstUI->window, "recognition-signal");
#pragma omp ordered
g_signal_emit_by_name (usrRefreshObject->dstUI->window, "refresh-signal");
cout << __FILE__ << "====" << __LINE__ << endl;
}
cairo_surface_destroy(surface);
gst_sample_unref(sample);
return GST_FLOW_OK;
}
void refreshUI (EasyUI *usrUI,RefreshData *usrData)
{
std::ostringstream licenseColor,license,pass;
string tmp;
if(usrData->licenseColor != NULL) {
licenseColor << "<span foreground='green' underline='single' underline_color='blue' font_desc='12'>" << usrData->licenseColor << "</span>";
if (strcmp(usrData->licenseColor,"YellowLicense") == 0 ) {
tmp = string("NONE");
} else if (strcmp(usrData->licenseColor,"BlueLicense") == 0 ) {
tmp = string("PASS");
} else if (strcmp(usrData->licenseColor,"WhiteLicense") == 0 ) {
tmp = string("PASS");
}
pass << "<span foreground='blue' font_desc='24'>" << tmp.c_str() << "</span>";
} else {
licenseColor << "<span foreground='green' underline='single' underline_color='blue' font_desc='24'>show color</span>";
}
cout << __FILE__ << "====" << __LINE__ << endl;
if(usrData->license != NULL) {
license << "<span foreground='green' underline='single' underline_color='blue' font_desc='12'>" << usrData->license << "</span>";
} else {
license << "<span foreground='green' underline='single' underline_color='blue' font_desc='12'>show license</span>";
}
gdk_threads_enter();
gtk_label_set_markup(GTK_LABEL(usrUI->licenseLab),licenseColor.str().c_str());
gtk_label_set_markup(GTK_LABEL(usrUI->psssLab),license.str().c_str());
gtk_label_set_markup(GTK_LABEL(usrUI->psssLab),pass.str().c_str());
gdk_threads_leave;
}
void plate_recognize(RefreshData *myFreshData,cv::Mat &src)
{
cout << __FILE__ << "====" << __LINE__ << endl;
CPlateRecognize pr;
pr.setLifemode(true);
pr.setDebug(false);
pr.setMaxPlates(1);
//pr.setDetectType(PR_DETECT_COLOR | PR_DETECT_SOBEL);
pr.setDetectType(easypr::PR_DETECT_CMSER | PR_DETECT_COLOR | PR_DETECT_SOBEL);
//vector<string> plateVec;
vector<CPlate> plateVec;
int result = pr.plateRecognize(src, plateVec);
//int result = pr.plateRecognizeAsText(src, plateVec);
char* substr,*savestr;
std::ostringstream license,res;
if (result == 0) {
size_t num = plateVec.size();
cout << __FILE__ << "license num = " << num << "---" << __LINE__ << endl;
for (size_t j = 0; j < num; j++) {
cout << "plateRecognize: " << plateVec[j].getPlateStr() << endl;
if ( !plateVec[j].getPlateStr().empty() ) {
myFreshData->licenseColor = strtok_r((char *)plateVec[j].getPlateStr().c_str(),":",&savestr);
cout << __FILE__ << "substr = " << myFreshData->licenseColor << "---" << __LINE__ << endl;
myFreshData->license = (char *)plateVec[j].getPlateStr().substr(strlen(substr)+2, plateVec[j].getPlateStr().length()).c_str();
}
}
}
}
| 35.617021 | 147 | 0.63405 | [
"vector"
] |
56eb7124de44eb3284cef2ab4a5d6d438781231e | 4,568 | cpp | C++ | events/add_hf_entity_honor.cpp | BenLubar/weblegends | 0eea0239c57ffc2540adc4d312f446cafafeb2c5 | [
"Zlib"
] | 16 | 2018-02-05T17:44:12.000Z | 2022-03-03T13:37:06.000Z | events/add_hf_entity_honor.cpp | BenLubar/weblegends | 0eea0239c57ffc2540adc4d312f446cafafeb2c5 | [
"Zlib"
] | 12 | 2017-10-25T13:25:22.000Z | 2022-03-12T19:27:54.000Z | events/add_hf_entity_honor.cpp | BenLubar/weblegends | 0eea0239c57ffc2540adc4d312f446cafafeb2c5 | [
"Zlib"
] | 5 | 2017-10-25T13:30:45.000Z | 2018-08-03T12:51:40.000Z | #include "../helpers_event.h"
#include "df/history_event_add_hf_entity_honorst.h"
#include "df/honors_type.h"
void do_event(std::ostream & s, const event_context & context, df::history_event_add_hf_entity_honorst *event)
{
auto figure = df::historical_figure::find(event->hfid);
auto entity = df::historical_entity::find(event->entity_id);
auto honor = entity ? binsearch_in_vector(entity->honors, event->honor_id) : nullptr;
if (!honor)
{
do_event_missing(s, context, event, __FILE__, __LINE__);
return;
}
event_link(s, context, figure);
s << " received the title of " << honor->name << " in ";
event_link(s, context, entity);
if (honor->flags.bits.granted_to_all_new_members)
{
s << ", given to all new members";
return;
}
std::vector<std::string> requirements;
if (honor->required_skill_points > 0)
{
bool melee = honor->required_skill_type.bits.melee_weapon;
bool ranged = honor->required_skill_type.bits.ranged_weapon;
std::string req = "attaining sufficient skill with ";
if (melee && ranged)
{
req += "a weapon or technique";
}
else if (melee)
{
req += "a melee weapon or technique";
}
else if (ranged)
{
req += "a ranged weapon";
}
else
{
BEFORE_SWITCH(req_skill, honor->required_skill);
switch (req_skill) {
case job_skill::AXE:
req += "the axe";
BREAK(req_skill);
case job_skill::SWORD:
req += "the sword";
BREAK(req_skill);
case job_skill::MACE:
req += "the mace";
BREAK(req_skill);
case job_skill::HAMMER:
req += "the hammer";
BREAK(req_skill);
case job_skill::SPEAR:
req += "the spear";
BREAK(req_skill);
case job_skill::CROSSBOW:
req += "the crossbow";
BREAK(req_skill);
case job_skill::SHIELD:
req += "the shield";
BREAK(req_skill);
case job_skill::PIKE:
req += "the pike";
BREAK(req_skill);
case job_skill::WHIP:
req += "the whip";
BREAK(req_skill);
case job_skill::BOW:
req += "the bow";
BREAK(req_skill);
case job_skill::BLOWGUN:
req += "the blowgun";
BREAK(req_skill);
case job_skill::WRESTLING:
req += "grappling";
BREAK(req_skill);
case job_skill::BITE:
req += "the tooth";
BREAK(req_skill);
case job_skill::GRASP_STRIKE:
req += "strikes";
BREAK(req_skill);
case job_skill::STANCE_STRIKE:
req += "kicks";
BREAK(req_skill);
case job_skill::DODGING:
req += "dodging";
BREAK(req_skill);
default:
req += toLower(enum_item_key_str(req_skill));
break;
}
AFTER_SWITCH(req_skill, stl_sprintf("event-%d (ADD_HF_ENTITY_HONOR) skill", event->id));
requirements.push_back(req);
}
}
if (honor->required_battles > 0)
{
if (honor->required_battles == 1)
{
requirements.push_back("serving in combat");
}
else
{
requirements.push_back(stl_sprintf("participating in %d battles", honor->required_battles));
}
}
if (honor->required_kills > 0)
{
if (honor->required_kills == 1)
{
requirements.push_back("slaying an enemy");
}
else
{
requirements.push_back(stl_sprintf("slaying %d enemies", honor->required_kills));
}
}
if (honor->required_years_of_membership > 0)
{
if (honor->required_years_of_membership == 1)
{
requirements.push_back("being a member for a year");
}
else
{
requirements.push_back(stl_sprintf("%d years of membership", honor->required_years_of_membership));
}
}
if (!requirements.empty())
{
s << " after ";
list<std::string>(s, requirements, [](std::ostream& s, std::string str) { s << str; });
}
}
| 30.453333 | 111 | 0.510289 | [
"vector"
] |
56ec691528e2c835693215a8d0bb9addecb7f85f | 12,859 | cpp | C++ | fcd.cpp | FS-make-simple/fastcd | 1c98fcfb50e5df8fb2729af0e19debcf5e207806 | [
"MIT"
] | 7 | 2016-08-30T16:01:51.000Z | 2019-01-27T07:41:43.000Z | fastcd.cpp | ran130683/fastcd | d25ffba75146a9790f7bda7a41214f36864039ce | [
"MIT"
] | 1 | 2016-08-31T07:52:01.000Z | 2016-08-31T11:20:28.000Z | fastcd.cpp | ran130683/fastcd | d25ffba75146a9790f7bda7a41214f36864039ce | [
"MIT"
] | 3 | 2017-02-14T12:55:13.000Z | 2019-01-27T07:42:07.000Z |
/*
code by phoneli.
email : phone.wc.li@foxmail.com
license : MIT
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <ncurses.h>
#include <errno.h>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#define STR2UINT(str) strtoul( str , NULL , 10 )
const int baseY = 1;
const int baseX = 1;
int maxRow = 0;
int maxCol = 0;
std::string gStrPath;
std::string gStrIdxFile;
//string---------->
unsigned int PathLen( const char * line )
{
if( NULL == line ) return 0;
unsigned int iLen = strlen(line);
for( unsigned int i = 0 ; i < iLen ; ++i )
{
if( ' ' == line[i] || '\n' == line[i] )
return i;
}
return iLen-1;
}
void TrimString(std::string& str)
{
str.erase(0,str.find_first_not_of(" \t"));
str.erase(str.find_last_not_of(" \t")+1);
}
void TrimHeadString(std::string& str)
{
size_t pos = str.find_first_of('"');
if( pos != std::string::npos )
str.erase(0, pos+1);
pos = str.find_last_of('"');
if( pos != std::string::npos )
str.erase( pos );
}
void TrimForLastKey(std::string & str)
{
size_t pos = str.rfind( "/");
if( std::string::npos != pos )
str.erase(0, pos+1);
}
bool bIsOutWordRange( const char s )
{
int v = (int)s;
if( 48 <= v && v <= 57 ) return false;
if( 65 <= v && v <= 90 ) return false;
if( 97 <= v && v <= 122 ) return false;
return true;
}
bool bIsMyWord( const std::string & strKey , std::string & strLine )
{
size_t pos = strLine.find( strKey );
if( pos != std::string::npos )
{
if( pos != 0 && false == bIsOutWordRange( strLine[ pos - 1 ] ) )
{
return false;
}
if( ( pos + strKey.size() ) != strLine.size() &&
false == bIsOutWordRange( strLine[ pos + strKey.size() ] ) )
{
return false;
}
return true;
}
return false;
}
//<==========string
void func_flash(const char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
if((dp = opendir(dir)) == NULL) {
//printf("ERR : depth[%d] : %s\n" , depth , dir );
printf("%s\n" , dir );//May Be Link
return;
}
printf("%s [path]\n" , dir );
std::string strCurPath = gStrPath;
while( NULL != (entry = readdir(dp)) )
{
if( DT_DIR == entry->d_type || DT_LNK == entry->d_type )
{
if( depth >= 3 && DT_DIR != entry->d_type )
{
printf("%s/%s\n", strCurPath.c_str() , entry->d_name );
continue;
}
//ignore .
if(strncmp( ".", entry->d_name , 1) == 0 )
{ continue; }
gStrPath += "/";
gStrPath += entry->d_name;
//recurse
func_flash( gStrPath.c_str() ,depth+1);
gStrPath = strCurPath;
} else if ( DT_REG == entry->d_type ) {
printf("%s/%s\n", strCurPath.c_str() , entry->d_name );
}
}
closedir(dp);
}
void func_list( const unsigned int iLines ,
std::vector<std::string> * strLines = NULL ,
std::map<std::string , std::vector<std::string> > * strFileMap = NULL )
{
FILE * fIdxFile = fopen( gStrIdxFile.c_str() , "r" );
if( NULL == fIdxFile ) { return ; }
char sLine[1024] = {0};
unsigned int iCount = 1;
std::string strLine;
std::vector<std::string> * strFileMapItem = NULL;
for( ; NULL != fgets( sLine , sizeof(sLine) , fIdxFile ) && (iCount <= iLines) ; )
{
if( NULL != strLines )
{
sLine[ strlen(sLine) - 1 ] = '\0';
strLines->push_back( sLine );
} else if ( NULL != strFileMap )
{
sLine[ strlen(sLine) - 1 ] = '\0';
strLine = sLine;
if ( std::string::npos == strLine.find("[path]") )
{
TrimForLastKey( strLine );
strFileMapItem = &( (*strFileMap)[ strLine ] );
strFileMapItem->push_back( sLine );
}
} else
{
printf("\e[0;33m %.*s (%u)\n\e[0m" , (int)strlen(sLine)-1 , sLine , iCount );
}
iCount++;
}
fclose( fIdxFile );
return ;
}
void func_p( const unsigned int iIndex )
{
FILE * fIdxFile = fopen( gStrIdxFile.c_str() , "r" );
if( NULL == fIdxFile ) { return ; }
unsigned int iCount = 1;
char sLine[1024] = {0};
for( ; NULL != fgets( sLine , sizeof(sLine) , fIdxFile ) ; )
{
if( iIndex == iCount )
{
printf("%.*s\n" , PathLen(sLine) , sLine );
break;
}
iCount++;
}
fclose( fIdxFile );
return ;
}
void func_search_file( std::string & strOutRes )
{
initscr();
raw();
keypad(stdscr, TRUE);
start_color();
init_pair(1, COLOR_MAGENTA , COLOR_BLACK);
init_pair(2, COLOR_YELLOW, COLOR_BLACK);
getmaxyx(stdscr, maxRow , maxCol );
int y = 0 , x = 0;
std::string strUnder( maxCol , '_' );
std::vector< std::string > strKeys;
std::vector< std::string > strLines;
char sKey[128];
while( true )
{
move( baseY , baseX );
getstr( sKey );
if( 0 == strlen(sKey) )
{ continue; }
if( strncmp( sKey , ":" , 1 ) == 0 && strlen(sKey) >= 2 )
{
if( strlen(sKey) == 2 && ( sKey[1] == 'r' || sKey[1] == 'R' ) )
{
strKeys.clear();strLines.clear();
clear();
continue;
} else if( strlen(sKey) == 2 && ( sKey[1] == 'q' || sKey[1] == 'Q' ) )
{
strOutRes = "./ [path]";
break;
}
const unsigned int iLine = strtoul( sKey+1 , NULL , 10 );
if( iLine >= strLines.size() )
{ continue; }
//if( std::string::npos == strLines.at(iLine).find("[path]") )
//{ continue; }
strOutRes = strLines.at(iLine);
break;
}
if( 0 == strKeys.size() )
{ func_list( (unsigned int)-1 , &strLines , NULL ); }
strKeys.push_back( sKey );
{//find
std::string strKey = sKey;
bool reverse = false;
bool casecmp = false;
if( strncasecmp( sKey , "-v " , 3 ) == 0 && strlen(sKey) >= 4 )
{
strKey = sKey+3;
reverse = true;
} else if( strncasecmp( sKey , "-i " , 3 ) == 0 && strlen(sKey) >= 4 )
{
strKey = sKey+3;
casecmp = true;
transform(strKey.begin(), strKey.end(), strKey.begin(), ::tolower);
}
std::vector< std::string > strFindRes;
for( unsigned int i = 0 ; i < strLines.size() ; ++ i )
{
if( true == reverse )
{
if( std::string::npos == strLines.at(i).find( strKey ) )
{ strFindRes.push_back( strLines.at(i) ); }
} else if ( true == casecmp )
{
std::string strTmpKey = strLines.at(i);
transform( strLines.at(i).begin(), strLines.at(i).end(), strTmpKey.begin(), ::tolower);
if( std::string::npos != strTmpKey.find( strKey ) )
{ strFindRes.push_back( strLines.at(i) ); }
} else
{
if( std::string::npos != strLines.at(i).find( strKey ) )
{ strFindRes.push_back( strLines.at(i) ); }
}
}
strLines.swap( strFindRes );
}
clear();
move( baseY+1 , baseX );
attron( A_BOLD | COLOR_PAIR(1) );
for( unsigned int i = 0 ; i < strKeys.size() ; ++i )
printw("%s " , strKeys.at(i).c_str() );
printw("\n%.*s\n" , maxCol , strUnder.c_str() );
attroff( A_BOLD | COLOR_PAIR(1) );
attron(COLOR_PAIR(2));
getyx( stdscr , y , x );
for( int i = 0 ; i+y < maxRow && i < (int)strLines.size() ; ++i )
{
printw( " %s [%d]\n" , strLines.at(i).c_str() , i );
}
attroff(COLOR_PAIR(2));
refresh();
}
endwin();
return ;
}
int func_search_define( const char * sKey , const char * sInFile , const unsigned int iSample ,
const int iMaxDepth , const char * sEndA , const char * sEndB )
{
if( NULL == sInFile ) return 0;
const std::string strKey = sKey;
std::string strInFile = sInFile;
const char * sIncludeCmd = "#include";
const char * sImportCmd = "import";
std::map<std::string , std::vector<std::string> > strAllFileMap;//for get file-full-path
func_list( (unsigned int)-1 , NULL , &strAllFileMap );
std::set< std::string > oFileSet; //for de-weight
std::map< std::string * , int > oFileMap; //for de-weight
oFileMap.insert( std::map< std::string * ,int >::value_type(&strInFile,0) );
while( true )
{
const char * sFileName = NULL;
int iDepth = 0;
std::map<std::string *, int >::iterator iter;
for( iter = oFileMap.begin() ; iter != oFileMap.end() ; ++iter )
{
if( -1 != iter->second )
{
sFileName = iter->first->c_str();
iDepth = iter->second;
iter->second = -1;
break;
}
}
if( NULL == sFileName )
{ break; }
std::string strNewFileName = "";
if( sEndA != NULL && sEndB != NULL )
{
strNewFileName = sFileName;
size_t iTmp = strNewFileName.rfind( sEndA );
if( std::string::npos != iTmp )
{
strNewFileName.replace( iTmp , strlen(sEndA) , sEndB );
if( access( strNewFileName.c_str() , 0 ) == 0 )
{ sFileName = strNewFileName.c_str(); }
}
}
FILE * fFile = fopen( sFileName , "r" );
if( NULL == fFile )
{
printf( "\n-->iDepth[%d] sFileName[%s] not exist\n" , iDepth , sFileName );
continue ;
}
unsigned int iLine = 0;
std::string strTmpLine;
char sLine[1024] = {0};
bool bFindKey = false;
//printf("\n--> %s [file-depth:%d]\n" , sFileName , iDepth ) ;
for( unsigned int iPrint = 0 ; NULL != fgets( sLine , sizeof(sLine) , fFile ) && iPrint < iSample ; iLine++)
{
strTmpLine = sLine;
TrimString( strTmpLine );
if( strncmp( sIncludeCmd , strTmpLine.c_str() , 8 ) == 0 ||
strncmp( sImportCmd , strTmpLine.c_str() , 6 ) == 0 )
{
if( iDepth < iMaxDepth && std::string::npos != strTmpLine.find( "\"" ) )
{
TrimHeadString( strTmpLine );
TrimForLastKey( strTmpLine );
if( oFileSet.end() == oFileSet.find( strTmpLine ) )
{
//printf("search\n");
oFileSet.insert( strTmpLine );
if( strAllFileMap.end() != strAllFileMap.find( strTmpLine ) )
{
std::vector< std::string > * strRes;
strRes = &strAllFileMap[ strTmpLine ];
for( unsigned int i = 0 ; i < strRes->size() ; ++i )
{//insert file into map
oFileMap.insert( std::map< std::string * ,int>::value_type(
&(strRes->at(i)) , iDepth+1) );
}
}
} else {
//printf("save search!!!\n");
}
}
} else if( true == bIsMyWord( strKey , strTmpLine ) )
{
iPrint ++;
if( false == bFindKey )
{ printf("\n--> %s [file-depth:%d]\n" , sFileName , iDepth ) ; bFindKey = true; }
printf(" %.*s [%u]\n" , (int)strTmpLine.size()-1 , strTmpLine.c_str() , iLine );
}
}
fclose( fFile );
}
printf("\n");
return 0;
}
int main(int argc, char* argv[])
{
if ( false )
{
help:
printf( "\n" );
printf( "\e[0;33m usage %s [ l | p | flash | index | $key ]\n\e[0m" , argv[0] );
printf( "\e[0;33m l $line(d:line=10) : list\n\e[0m" );
printf( "\e[0;33m p $index : print the path of index\n\e[0m" );
printf( "\e[0;33m flash $path(d:path=$HOME) : refresh file index \n\e[0m" );
printf( "\e[0;33m index : fast cd to $index path\n\e[0m" );
printf( "\e[0;33m key : will search $key and cd path if only one matched\n\e[0m" );
printf( "\e[0;33m search_define key top-file sample-line max-depth a->b \n\e[0m" );
printf( "\e[0;33m magic : [-v reverse] [-i casecmp] [-r restart] [:index] \n\e[0m" );
printf( "\n" );
return 0;
}
gStrPath = getenv("HOME");
gStrIdxFile = gStrPath;
gStrIdxFile += "/.fastcd";
const char * sFunc = argv[1];
if( argc == 1 )
{
std::string strOutRes;
func_search_file( strOutRes );
std::string strCmd = "echo \"";
strCmd += strOutRes;
strCmd += "\" > ~/.fastcd.pwd";
system( strCmd.c_str() );
return 0;
}
if( strcmp( sFunc , "l" ) == 0 ||
strcmp( sFunc , "ls" ) == 0 ||
strcmp( sFunc , "list" ) == 0 )
{
unsigned int iLines = 10;
if( 3 == argc ) { iLines = STR2UINT(argv[2]); }
func_list( iLines );
}
else if ( strcmp( sFunc , "p" ) == 0 )
{
if( argc != 3 ) goto help;
unsigned int iIndex = STR2UINT(argv[2]);
func_p( iIndex );
}
else if ( strcmp( sFunc , "flash" ) == 0 )
{
if( 3 == argc )
gStrPath = argv[2];
func_flash( gStrPath.c_str() ,0);
}
else if ( strcmp( sFunc , "search_define" ) == 0 && ( 6 == argc || 8 == argc ) )
{
if( argc == 8 )
func_search_define( argv[2] , argv[3] , STR2UINT(argv[4]) , STR2UINT(argv[5]) , argv[6] , argv[7] );
else
func_search_define( argv[2] , argv[3] , STR2UINT(argv[4]) , STR2UINT(argv[5]) , NULL , NULL );
}
else if ( strcmp( sFunc , "debug-list-map" ) == 0 && 3 == argc )
{
std::map<std::string , std::vector<std::string> > strFileMap4test;
func_list( (unsigned int)-1 , NULL , &strFileMap4test );
std::string strKey = argv[2];
std::vector<std::string> * strRes = &(strFileMap4test[ strKey ]);
printf("strKey[%s] size[%zu] strRes[%zu]\n" ,
strKey.c_str() , strFileMap4test.size() , strRes->size() );
for( unsigned int i = 0 ; i < strRes->size() ; ++i )
{
printf("[%u] [%s]\n" , i , strRes->at(i).c_str() );
}
}
else if ( strcmp( sFunc , "debug-list" ) == 0 && 2 == argc )
{
std::vector<std::string> strLines;
func_list( (unsigned int)-1 , &strLines , NULL );
for( unsigned int i = 0 ; i < strLines.size() ; ++i )
{
printf("[%u] [%s]\n" , i , strLines.at(i).c_str() );
}
}
else
{
goto help;
}
return 0;
}
| 25.564612 | 110 | 0.564896 | [
"vector",
"transform"
] |
56f31918d0cbd1e00b9bcf1884704139822aef62 | 1,310 | hpp | C++ | include/Factory/Module/Encoder/Polar/Encoder_polar.hpp | FredrikBlomgren/aff3ct | fa616bd923b2dcf03a4cf119cceca51cf810d483 | [
"MIT"
] | 315 | 2016-06-21T13:32:14.000Z | 2022-03-28T09:33:59.000Z | include/Factory/Module/Encoder/Polar/Encoder_polar.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 153 | 2017-01-17T03:51:06.000Z | 2022-03-24T15:39:26.000Z | include/Factory/Module/Encoder/Polar/Encoder_polar.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 119 | 2017-01-04T14:31:58.000Z | 2022-03-21T08:34:16.000Z | /*!
* \file
* \brief Class factory::Encoder_polar.
*/
#ifndef FACTORY_ENCODER_POLAR_HPP
#define FACTORY_ENCODER_POLAR_HPP
#include <vector>
#include <string>
#include <map>
#include <cli.hpp>
#include "Tools/Factory/Header.hpp"
#include "Module/Encoder/Polar/Encoder_polar.hpp"
#include "Factory/Module/Encoder/Encoder.hpp"
namespace aff3ct
{
namespace factory
{
extern const std::string Encoder_polar_name;
extern const std::string Encoder_polar_prefix;
class Encoder_polar : public Encoder
{
public:
// ----------------------------------------------------------------------------------------------------- PARAMETERS
// empty
// -------------------------------------------------------------------------------------------------------- METHODS
explicit Encoder_polar(const std::string &p = Encoder_polar_prefix);
virtual ~Encoder_polar() = default;
Encoder_polar* clone() const;
// parameters construction
void get_description(cli::Argument_map_info &args) const;
void store (const cli::Argument_map_value &vals);
void get_headers (std::map<std::string,tools::header_list>& headers, const bool full = true) const;
// builder
template <typename B = int>
module::Encoder_polar<B>* build(const std::vector<bool> &frozen_bits) const;
};
}
}
#endif /* FACTORY_ENCODER_POLAR_HPP */
| 27.87234 | 116 | 0.629771 | [
"vector"
] |
56f3f3b7e07869fb562b35dca38ecadd11e82b65 | 1,163 | cpp | C++ | lab/lab03/visita.cpp | mfranzil-unitn/unitn-asd | 2288b0358d832fe3777c2af7cbb82d12d6365035 | [
"MIT"
] | null | null | null | lab/lab03/visita.cpp | mfranzil-unitn/unitn-asd | 2288b0358d832fe3777c2af7cbb82d12d6365035 | [
"MIT"
] | null | null | null | lab/lab03/visita.cpp | mfranzil-unitn/unitn-asd | 2288b0358d832fe3777c2af7cbb82d12d6365035 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct Nodo {
vector<int> vic;
int index;
bool visitato;
};
int count(vector<Nodo*> &G, Nodo* R);
int main() {
int N, M, S;
vector<Nodo*> G;
ifstream in("input.txt");
in >> N >> M >> S;
for (int i = 0; i < N; i++) {
Nodo* tmp = new Nodo();
tmp->index = i;
tmp->visitato = false;
G.push_back(tmp);
}
for (int i = 0; i < M; i++) {
int from, to;
in >> from >> to;
G.at(from)->vic.push_back(to);
}
ofstream out("output.txt");
out << count(G, G.at(S));
return 0;
}
int count(vector<Nodo*> &G, Nodo* R) {
queue<Nodo*> Q;
int count = 0;
Q.push(R);
G.at(R->index)->visitato = true;
while (!Q.empty()) {
Nodo* u = Q.front();
Q.pop();
u->visitato = true;
count++;
for (int i = 0; i < u->vic.size(); i++) {
Nodo* v = G.at(u->vic.at(i));
if (!v->visitato) {
v->visitato = true;
Q.push(v);
}
}
}
return count;
} | 17.892308 | 49 | 0.450559 | [
"vector"
] |
56f412198144906788e198f574371416b64f3601 | 8,552 | cpp | C++ | src/caffe/layers/fcn_image_data_layer.cpp | GuohongWu/caffe-windows-happynear | 88602198ff6507909b8d2992efa79d8ec74d7dfe | [
"BSD-2-Clause"
] | 2 | 2017-09-11T11:59:05.000Z | 2021-05-08T13:12:57.000Z | src/caffe/layers/fcn_image_data_layer.cpp | GuohongWu/caffe-windows-happynear | 88602198ff6507909b8d2992efa79d8ec74d7dfe | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/fcn_image_data_layer.cpp | GuohongWu/caffe-windows-happynear | 88602198ff6507909b8d2992efa79d8ec74d7dfe | [
"BSD-2-Clause"
] | null | null | null | #ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <fstream> // NOLINT(readability/streams)
#include <iostream> // NOLINT(readability/streams)
#include "caffe/layers/fcn_image_data_layer.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
namespace caffe {
template <typename Dtype>
FCNImageDataLayer<Dtype>::~FCNImageDataLayer<Dtype>() {
this->StopInternalThread();
}
template <typename Dtype>
void FCNImageDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// Read the img_source with filenames and labels
const string& source_ = this->layer_param_.image_data_param().source();
LOG(INFO) << "Opening file " << source_;
std::ifstream infile(source_.c_str());
string line;
size_t pos;
string label_;
lines_.clear();
while (std::getline(infile, line)) {
pos = line.find_last_of(' ');
label_ = line.substr(pos + 1);
while (line[pos] == ' ')
--pos;
lines_.emplace_back(line.substr(0, pos + 1), label_);
}
CHECK(!lines_.empty()) << "File is empty";
if (this->layer_param_.image_data_param().shuffle()) {
// randomly shuffle data
LOG(INFO) << "Shuffling data";
const unsigned int prefetch_rng_seed = caffe_rng_rand();
prefetch_rng_.reset(new Caffe::RNG(prefetch_rng_seed));
ShuffleImages();
}
else {
if (this->phase_ == TRAIN && Caffe::solver_rank() > 0 &&
this->layer_param_.image_data_param().rand_skip() == 0) {
LOG(WARNING) << "Shuffling or skipping recommended for multi-GPU";
}
}
LOG(INFO) << "A total of " << lines_.size() << " images.";
lines_id_ = 0;
// Check if we would need to randomly skip a few data points
if (this->layer_param_.image_data_param().rand_skip()) {
unsigned int skip = caffe_rng_rand() %
this->layer_param_.image_data_param().rand_skip();
LOG(INFO) << "Skipping first " << skip << " data points.";
CHECK_GT(lines_.size(), skip) << "Not enough points to skip";
lines_id_ = skip;
}
this->PreFetchReshape(bottom, top);
}
template <typename Dtype>
void FCNImageDataLayer<Dtype>::PreFetchReshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
int new_height = this->layer_param_.image_data_param().new_height();
int new_width = this->layer_param_.image_data_param().new_width();
const bool is_color = this->layer_param_.image_data_param().is_color();
const int batch_size = this->layer_param_.image_data_param().batch_size();
CHECK_GT(batch_size, 0) << "Positive batch size required";
CHECK((new_height == 0 && new_width == 0) ||
(new_height > 0 && new_width > 0)) << "Current implementation requires "
"new_height and new_width to be set at the same time.";
// Read an image, and use it to initialize the top blob.
if (new_height == 0) {
string root_folder = this->layer_param_.image_data_param().root_folder();
cv::Mat cv_img = ReadImageToCVMat(root_folder + lines_[lines_id_].first, is_color);
CHECK(cv_img.data) << "Could not load " << lines_[lines_id_].first;
new_height = cv_img.rows;
new_width = cv_img.cols;
}
vector<int> top0_shape{ 1, (is_color ? 3 : 1), new_height, new_width };
vector<int> top1_shape(top0_shape);
top1_shape[1] = 1;
this->transformed_data_.Reshape(top0_shape);
this->transformed_segMask_.Reshape(top1_shape);
// Reshape prefetch_data
top0_shape[0] = top1_shape[0] = batch_size;
for (int i = 0; i < this->prefetch_.size(); ++i) {
this->prefetch_[i]->data_.Reshape(top0_shape); // top[0]
this->prefetch_[i]->label_.Reshape(top1_shape); // top[1]
}
top[0]->Reshape(top0_shape);
top1_shape[1] = this->layer_param_.fcn_image_data_param().classification_nums();
top[1]->Reshape(top1_shape);
LOG(INFO) << "output data size: " << batch_size << ","
<< top[0]->channels() << "," << new_height << ","
<< new_width;
}
template <typename Dtype>
void FCNImageDataLayer<Dtype>::ShuffleImages() {
caffe::rng_t* prefetch_rng =
static_cast<caffe::rng_t*>(prefetch_rng_->generator());
shuffle(lines_.begin(), lines_.end(), prefetch_rng);
}
// This function is called on prefetch thread
template <typename Dtype>
void FCNImageDataLayer<Dtype>::load_batch(Batch<Dtype>* batch) {
CPUTimer batch_timer;
batch_timer.Start();
double read_time = 0;
double trans_time = 0;
CPUTimer timer;
CHECK(batch->data_.count());
CHECK(this->transformed_data_.count());
CHECK(batch->label_.count());
CHECK(this->transformed_segMask_.count());
const bool is_color = this->layer_param_.image_data_param().is_color();
const int batch_size = this->layer_param_.image_data_param().batch_size();
string root_folder = this->layer_param_.image_data_param().root_folder();
Dtype* prefetch_data = batch->data_.mutable_cpu_data();
Dtype* prefetch_label = batch->label_.mutable_cpu_data();
// datum scales
const int lines_size = lines_.size();
for (int item_id = 0; item_id < batch_size; ++item_id) {
// get a blob
timer.Start();
bool valid_sample = false;
while (!valid_sample) {
CHECK_GT(lines_size, lines_id_);
std::pair<std::string, std::string> this_line = lines_[lines_id_];
cv::Mat cv_img = ReadImageToCVMat(root_folder + this_line.first, is_color);
if (!cv_img.data) {
LOG(INFO) << "Could not load " << root_folder + this_line.first;
valid_sample = false;
}
else {
valid_sample = true;
}
cv::Mat cv_mask_img = ReadImageToCVMat(root_folder + this_line.second, false);
if (!cv_mask_img.data) {
LOG(INFO) << "Could not load " << root_folder + this_line.second;
valid_sample = false;
}
else {
valid_sample = true;
}
CHECK_EQ(cv_img.size(), cv_mask_img.size()) << "segMask image must have the same size as the input image.";
read_time += timer.MicroSeconds();
// go to the next iter
lines_id_++;
if (lines_id_ >= lines_size) {
// We have reached the end. Restart from the first.
DLOG(INFO) << "Restarting data prefetching from start.";
lines_id_ = 0;
if (this->layer_param_.image_data_param().shuffle()) {
ShuffleImages();
}
}
if (valid_sample) {
timer.Start();
// Apply transformations (mirror, crop...) to the image
int offset0 = batch->data_.offset(item_id);
this->transformed_data_.set_cpu_data(prefetch_data + offset0);
int offset1 = batch->label_.offset(item_id);
this->transformed_segMask_.set_cpu_data(prefetch_label + offset1);
this->data_transformer_->Transform(cv_img, &(this->transformed_data_), cv_mask_img, &(this->transformed_segMask_), nullptr, nullptr, 0);
trans_time += timer.MicroSeconds();
}
}
}
batch_timer.Stop();
DLOG(INFO) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms.";
DLOG(INFO) << " Read time: " << read_time / 1000 << " ms.";
DLOG(INFO) << "Transform time: " << trans_time / 1000 << " ms.";
}
template <typename Dtype>
void FCNImageDataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
if (this->prefetch_current_) {
this->prefetch_free_.push(this->prefetch_current_);
}
this->prefetch_current_ = this->prefetch_full_.pop("Waiting for data");
top[0]->set_cpu_data(this->prefetch_current_->data_.mutable_cpu_data());
const int class_nums = this->layer_param_.fcn_image_data_param().classification_nums();
Dtype* mask_data = this->prefetch_current_->label_.mutable_cpu_data();
for (int i = 0; i < this->prefetch_current_->label_.count(); ++i) {
if (mask_data[i] != Dtype(255) && mask_data[i] > class_nums)
mask_data[i] = Dtype(255);
}
CHECK_EQ(class_nums, top[1]->channels());
CHECK_EQ(1, this->prefetch_current_->label_.channels());
int nums = top[1]->num();
int img_size = top[1]->height() * top[1]->width();
Dtype* top1_data = top[1]->mutable_cpu_data();
for (int n = 0; n < nums; ++n) {
for (int c = 1; c <= class_nums; ++c) {
for (int i = 0; i < img_size; ++i) {
if(mask_data[i] == Dtype(255))
*top1_data = Dtype(255);
else if(mask_data[i] == Dtype(c))
*top1_data = Dtype(1);
else
*top1_data = Dtype(0);
++top1_data;
//*top1_data++ = (*(mask_data + i) == Dtype(c) || *(mask_data + i) == Dtype(255)) ? *(mask_data + i) : Dtype(0);
}
}
mask_data += img_size;
}
}
INSTANTIATE_CLASS(FCNImageDataLayer);
REGISTER_LAYER_CLASS(FCNImageData);
} // namespace caffe
#endif // USE_OPENCV
| 35.338843 | 141 | 0.67224 | [
"vector",
"transform"
] |
56f55e86f8bdc99d824412ed38fa805fb3ef3d19 | 25,303 | cxx | C++ | StRoot/StSecondaryVertexMaker/StKinkMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StSecondaryVertexMaker/StKinkMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StSecondaryVertexMaker/StKinkMaker.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | /*!
* \class StKinkMaker
* \brief Class to find kink secondary vertices
* \author Camelia Mironov, KSU
* \date Jan,2004
*
*
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "StMemStat.h"
#include "StKinkMaker.h"
#include "StKinkLocalTrack.hh"
#include "StTrackGeometry.h"
#include "StV0FinderMaker.h"
#include "StEvent/StEventTypes.h"
#include "StEvent.h"
#include "TMath.h"
#include "StTrack.h"
#include "tables/St_tkf_tkfpar_Table.h"
#include "StMessMgr.h"
#include "math_constants.h"
#include "phys_constants.h"
#include "TVector2.h"
#include "StThreeVectorF.hh"
#include "TObjArray.h"
#include "SystemOfUnits.h"
#if !defined(ST_NO_NAMESPACES)
using namespace units;
#endif
const double kaonMass= M_KAON_PLUS;
const double pionMass= M_PION_PLUS;
const double muonMass= M_MUON_PLUS;
const double pi0Mass= M_PION_0;
const double kaonToMuonQ= 0.236;
const double kaonToPionQ= 0.205;
const double pionToMuonQ= 0.030;
const int MAXNUMOFTRACKS= 10000;
const int SIZETRKIDCHECK= 1000;
//=======================================================================
StKinkMaker::StKinkMaker(const char *name):StMaker(name),m_tkfpar(0)
{
mTrack1 = 0;
mTrack2 = 0;
mGlobalTrks = 0;
mParentTrackCandidate=0;
mDaughterTrackCandidate=0;
mDaughterTrackUnic=0;
mUseTracker = kTrackerUseBOTH;
event = 0;
kinkVertex = 0;
mBfield = -2.; // arbitrary value, normalized after ...neat (gene)
}
//=======================================================================
StKinkMaker::~StKinkMaker(){
}
//======================================================================
/*!
Init() will aslo initialize the track type to select on.
See SetTrackerUsage(). Note that the steering of how to call
SetTrackerUsage() is done through StBFChain and the maker m_Mode
mechanism. Refer to SetTrackerUsage() method for more explaination.
*/
Int_t StKinkMaker::Init(){
// m_Mode -> SetTrackerUsage()
if (m_Mode == 1) SetTrackerUsage(kTrackerUseTPT);
else if (m_Mode == 2) SetTrackerUsage(kTrackerUseITTF);
else if (m_Mode == 3) SetTrackerUsage(kTrackerUseBOTH);
return StMaker::Init();
}
//=============================================================================
Int_t StKinkMaker::InitRun(int runumber) {
m_tkfpar = (St_tkf_tkfpar*) GetDataBase("Calibrations/tracker/tkf_tkfpar");
if (!m_tkfpar) {
gMessMgr->Error(
"StKinkMaker::InitRun() : could not find tkf_tkfpar in database.");
return kStErr;
}
return StMaker::InitRun(runumber);
}
//=============================================================================
Int_t StKinkMaker::Make(){//called for each event
//******* variables
unsigned short nNodes,i,j;
int cutLast=0;
StKinkLocalTrack* tempTrack;
TObjArray trackArray(MAXNUMOFTRACKS);trackArray.SetOwner();
tkf_tkfpar_st *tkfpar = m_tkfpar->GetTable();
gMessMgr->Info()<<"StKinkMaker: impact parameter"<<tkfpar->impactCut<<endm;
StThreeVectorF p,start,end;
//******* GET
//### event
event = (StEvent*)GetInputDS("StEvent");
if (!event){
gMessMgr->Warning("StKinkMaker:no StEvent;skip event");
return kStWarn;
}
//### primary vertex
StPrimaryVertex* vrtx=event->primaryVertex();
if (!vrtx){
gMessMgr->Warning("StKinkMaker:no primary vertex;skip event");
return kStWarn;
}
mEventVertex = vrtx->position(); //StThreeVectorD
//### global tracks to use
StSPtrVecTrackNode& theNodes = event->trackNodes();
nNodes = theNodes.size();
mGlobalTrks=0;
for (i=0;i<nNodes;i++){
int nj = theNodes[i]->entries(global);
for (j=0; j<nj;j++){
StTrack* trk = theNodes[i]->track(global,j);
if( !acceptTrack(trk) )continue;
//******* find the magnetic field
StTrackGeometry* trkGeom = trk->geometry();
if(!trkGeom) continue; //ignore the track if it has no geometry
if(!mGlobalTrks)//calculate mBfield only for the first global trk from the event
{
StThreeVectorD p11 = trk->geometry()->momentum();
StThreeVectorD p22 = trk->geometry()->helix().momentum(mBfield);
if (fabs(p22.x()) > 1.e-20) mBfield *= p11.x()/p22.x();
else if (fabs(p22.y()) > 1.e-20) mBfield *= p11.y()/p22.y();
else continue;
if (fabs(mBfield) < 1.e-20) return kStWarn;
}
mGlobalTrks++;
//### cut: fiducial volume
Float_t trkStartRadius2D = trk->geometry()->origin().perp();
Float_t trkEndRadius2D = trk->outerGeometry()->origin().perp();
if (trkStartRadius2D < tkfpar->vertexRMin2D && //cut [133,179]
trkEndRadius2D > tkfpar->vertexRMax2D )
{ continue;}
if (trkStartRadius2D < tkfpar->vertexRMax2D ||
trkEndRadius2D > tkfpar->vertexRMin2D ){
tempTrack = new StKinkLocalTrack(trk);
trackArray.Add(tempTrack);//keep the track if ok
}
}//for each track in the node
} //for each node
//***************************************************************************************
// cout<<" magnetic field="<<mBfield<<endl;
//******* erase existing kinks; because everything runs in chain, the tkf makes its own kinks
StSPtrVecKinkVertex& kinkVertices = event->kinkVertices();
/* StMemStat memStat("kinkVertices");
kinkVertices.getEntries();
cout<<"memory used"<< memStat.Used();
*/
kinkVertices.erase(kinkVertices.begin(),kinkVertices.end());
// kinkVertices.getEntries();
//cout<<"memory used"<< memStat.Used();
// StSPtrVecKinkVertex kinkVertices2;
//kinkVertices = kinkVertices2;
//******* sorts by the trkStartRadius2D==>the potential parent trk, with
//smaller radius will be ahead of the potential daughters
if (trackArray.GetEntries() > 0) trackArray.Sort();
Int_t kinkCandidate=0;
Int_t cutPPt=0,cutPImpact=0,initial=0;
int ni=trackArray.GetEntries();
for (i=0;i<ni;i++){//parent
initial++;
mTrack1 = (StKinkLocalTrack*)trackArray.At(i);
mParentTrackCandidate = mTrack1->trackBack();
StTrackGeometry* myParentGeometry1 = mParentTrackCandidate->geometry(); //first point
StTrackGeometry* myParentGeometry11 = mParentTrackCandidate->outerGeometry();//last point
StPhysicalHelixD parentHelix = myParentGeometry1->helix();
double parentPtot = myParentGeometry11->momentum().mag();
double parentPt = myParentGeometry11->momentum().perp();
//### cut pT parent minimum = 0.2 Gev/c
if (myParentGeometry1->momentum().perp() < tkfpar->parentPtMin ) continue;
cutPPt++;
//### cut : impact parameter parent
mParentImpact = parentHelix.distance(mEventVertex);
if (mParentImpact > tkfpar->impactCut ) continue;
cutPImpact++;
Int_t foundDaughters = 0;
int nj = trackArray.GetLast()+1;
for (j=i+1;j<nj;j++ ){//daughter
mTrack2 = (StKinkLocalTrack*)trackArray.At(j);
mDaughterTrackCandidate = mTrack2->trackBack();
StTrackGeometry* myDaughterGeometry1 = mDaughterTrackCandidate->geometry();//first point
StPhysicalHelixD daughterHelix = myDaughterGeometry1->helix();
double daughterPtot = myDaughterGeometry1->momentum().mag();
double daughterPt = myDaughterGeometry1->momentum().perp();
//### cut: same charge
if (myParentGeometry1->charge() != myDaughterGeometry1->charge() ) continue;
//### cut:low lim fiducial volume = 133cm
if (myDaughterGeometry1->origin().perp() < tkfpar->vertexRMin2D ) continue;
//### cut:daughter impact parameter >2cm
mDaughterImpact = daughterHelix.distance(mEventVertex);
if (mDaughterImpact < mParentImpact) continue;
//### cut:last_pt-first_pt < 14 (radial) and < 20 (z)
if (fabs(myDaughterGeometry1->origin().perp() - myParentGeometry11->origin().perp())
> tkfpar->parentLastDaughterStart2D ) continue;
if (fabs(myDaughterGeometry1->origin().z() - myParentGeometry11->origin().z())
> tkfpar->parentLastDaughterStartZ ) continue;
cutLast++;
//##############################################################
//2D method (gets 3D aproximation after two 2D solution //
// ***** START DETERMINATION 2D DCA .... good luck //
//###############################################################
//kink vertex; look at the intersection pts in 2d of the 2helices
pairD paths,path2,paths1; // helix pathLength vars;
TVector2 r1,r2,xc1 ,xc2,tmp2V; // for 2D helices projections
StThreeVectorD x1,x2,p1,p2,x1i,x2j ;//position and momentum at 2d dca
double separation,dxc; // helix circle params
double dca_12,dca_12tmp; // 2D dca ... helpers
double rad_1,rad_2;//radii of the projected helices
double distanceOne,distanceTwo;
//### parent
xc1.Set(parentHelix.xcenter(),parentHelix.ycenter());//center of parent helix circle
r1.Set(parentHelix.origin().x(),parentHelix.origin().y());//first pt of the helix
r1 -= xc1;//distance
rad_1 = r1.Mod();//sqrt(x*x+y*y) length of the radius
//### daughter
xc2.Set(daughterHelix.xcenter(),daughterHelix.ycenter());//center of daughter helix circle
r2.Set(daughterHelix.origin().x(),daughterHelix.origin().y());//first pt on the helix
r2 -= xc2;//distance
rad_2 = r2.Mod();//sqrt(x*x+y*y) length of the radius
tmp2V = xc1 - xc2;//distance between centers
dxc = tmp2V.Mod();//length =O1O2
separation = dxc - (rad_1+rad_2);//O1O2-(r1+r2)
distanceOne = 0;
dca_12 = -9999;
dca_12tmp = -9999;
if (dxc==0)continue;
if (separation < 0){
if (dxc <= TMath::Abs(rad_1-rad_2)){//one helix circle, completely inside the other
double why = xc1.Y()-((rad_1+rad_2+dxc)*0.5 * (xc1.Y()-xc2.Y()))/dxc;
double ecs = xc1.X()-((rad_1+rad_2+dxc)*0.5 * (xc1.X()-xc2.X()))/dxc;
paths.first = parentHelix.pathLength(ecs,why);
paths.second = daughterHelix.pathLength(ecs,why);
x1 = parentHelix.at(paths.first);
x2 = daughterHelix.at(paths.second);
dca_12=x1.z()-x2.z();
}else {//2 intersection points=>2 solution, process those who aren't nan
//paths containes the path lengths for this solution with
//that for track 1 stores in 'first', and the track2 stored in 'second'
path2 = parentHelix.pathLength(rad_2,xc2.X(),xc2.Y());
if (!std::isnan(path2.first)){
paths.first = path2.first;
x1 = parentHelix.at(paths.first);
paths.second = daughterHelix.pathLength(x1.x(),x1.y());
x2 = daughterHelix.at(paths.second);
dca_12 = x1.z()-x2.z();
distanceOne = (x1-myDaughterGeometry1->origin()).mag();
}
if ((!std::isnan(path2.second))&&(path2.second!=path2.first))
{ paths1.first = path2.second;
x1i = parentHelix.at(paths1.first);
paths1.second = daughterHelix.pathLength(x1i.x(),x1i.y());
x2j = daughterHelix.at(paths1.second);
distanceTwo = (x2j-myDaughterGeometry1->origin()).mag();
dca_12tmp = x1i.z()-x2j.z();
if( distanceTwo < distanceOne){
//second solution is better
dca_12 = dca_12tmp;
x1 = x1i;
x2 = x2j;
paths = paths1;
}//distance
}else if (std::isnan(path2.second))//no solution
{ continue;}
}
}else if(separation==0){
double why = xc1.Y()-(rad_1 * (xc1.Y()-xc2.Y()))/dxc;
double ecs = xc1.X()-(rad_1 * (xc1.X()-xc2.X()))/dxc;
paths.first = parentHelix.pathLength(ecs,why);
paths.second = daughterHelix.pathLength(ecs,why);
x1 = parentHelix.at(paths.first);
x2 = daughterHelix.at(paths.second);
dca_12=x1.z()-x2.z();
}else if ((separation < tkfpar->dcaParentDaughterMax)){
//helix circles are close, but not overlapping
//find dca to point halfway between circle centers
tmp2V = (xc1 + xc2) * 0.5;
paths.first = parentHelix.pathLength(tmp2V.X(),tmp2V.Y());
paths.second = daughterHelix.pathLength(tmp2V.X(),tmp2V.Y());
x1 = parentHelix.at(paths.first);
x2 = daughterHelix.at(paths.second);
dca_12=x1.z()-x2.z();
// cout << "3rd case :xtarget = " << x1.x() << "\ty target =" << x1.y()<<endl;
}else {continue ;}//helix circle too far apart
//### cut: kink vertex in fiducial volume [133,179]
if ((x1.perp() > tkfpar->vertexRMax2D)|| (x1.perp() < tkfpar->vertexRMin2D) ) continue;
if ((x2.perp() > tkfpar->vertexRMax2D)|| (x2.perp() < tkfpar->vertexRMin2D) ) continue;
//### cut: projectPointZDiff (2cm)
if (fabs(dca_12) > tkfpar->projectPointZDiff) continue;
//at this point, dca_12 can be used in 3D calculation of the dca
//###############################################################
//DONE @D DCA < START 3D DCA FINDING# //
//##############################################################
//### momentum of the 2 tracks , at the inters pt
mParentMoment = parentHelix.momentumAt(paths.first, mBfield);
mDaughterMoment = daughterHelix.momentumAt(paths.second, mBfield);
//### cut: decay angle > 1
mDecayAngle = (1./degree) * mParentMoment.angle(mDaughterMoment);
if (mDecayAngle<tkfpar->thetaMin) continue;
//### 3D dca between parent and daughter (comes out square)
StThreeVectorD temp3V;
double cos12,sin2_12,t1,t2; // 3D dca calculation vars
double temp;
p1 = mParentMoment/parentPtot;
p2 = mDaughterMoment/daughterPtot;
cos12 = p1.dot(p2);
sin2_12 = (1.0 - cos12)*(1.- cos12);
if( sin2_12){
temp = dca_12/sin2_12;
t1 = (-p1.z()+p2.z()*cos12)*temp;
t2 = ( p2.z()-p1.z()*cos12)*temp;
temp = rad_1*(parentPtot/parentPt);
temp *= sin(t1/temp);
x1i = x1 + p1.pseudoProduct(temp,temp,t1);
temp = rad_2*(daughterPtot/daughterPt);
temp *= sin(t2/temp);
x2j = x2 + p2.pseudoProduct(temp,temp,t2);
dca_12tmp = (x1i - x2j).mag2();
dca_12 *= dca_12;
if( dca_12tmp < dca_12){
paths.first = parentHelix.pathLength(x1i.x(),x1i.y());
paths.second = daughterHelix.pathLength(x2j.x(),x2j.y());
x1i = parentHelix.at(paths.first);
x2j = daughterHelix.at(paths.second);
dca_12tmp = (x1i - x2j).mag2();
if( dca_12tmp < dca_12){
x1 = x1i;
x2 = x2j;
mParentMoment = parentHelix.momentumAt(paths.first, mBfield);
mDaughterMoment = daughterHelix.momentumAt(paths.second,mBfield);
dca_12 = dca_12tmp;
}
}
}
//############ end 3D DCA CALCUALTION
mDca = sqrt(dca_12);
//###cut: 3D dca < .5
if (mDca>(tkfpar->dcaParentDaughterMax) ) continue;
// cout << " dca is = " << mDca;
//cutDca++;
mKinkVertex = (x1 + x2) * 0.5;//vertex position
Float_t dx,dy;
dx = mKinkVertex.x() - myParentGeometry11->origin().x();
dy = mKinkVertex.y() - myParentGeometry11->origin().y();
Float_t distanceKinkParent2D = sqrt(dx*dx+dy*dy );
dx = mKinkVertex.x() - myDaughterGeometry1->origin().x();
dy = mKinkVertex.y() - myDaughterGeometry1->origin().y();
Float_t distanceKinkDaughter2D = sqrt(dx*dx+dy*dy );
Float_t distanceKinkParentZ = mKinkVertex.z() - myParentGeometry11->origin().z();
Float_t distanceKinkDaughterZ = mKinkVertex.z() - myDaughterGeometry1->origin().z();
//cut: distance kink track :radial<14, z<20
if (distanceKinkParent2D > tkfpar->distanceKinkParent2D ) continue;
if (distanceKinkDaughter2D > tkfpar->distanceKinkDaughter2D ) continue;
if (distanceKinkParentZ > tkfpar->distanceKinkParentZ ) continue;
if (distanceKinkDaughterZ > tkfpar->distanceKinkDaughterZ ) continue;
foundDaughters++;
mDaughterTrackUnic = myDaughterGeometry1;
}//loop j.. daughters
if(foundDaughters!=1)continue;//if found more than 1 daugthers for one parent track,ignore it
kinkCandidate++;
FillEvent(mDaughterTrackUnic,myParentGeometry11);
kinkVertices.push_back(kinkVertex);
// cout<<"foundDaugthers" <<foundDaughters<<endl;
}//loop i .. parents
// trackArray.Delete();
gMessMgr->Info() << "StKinkMaker:: Found " << kinkCandidate << " kink candidates " << endm;
//========================================================================
// Look for kinks in which 2 different parents are sharing the same daughter
// mark the coresonding kink vertices by changing the decayAngle value
// the new decay angle is [old*100+99]
// make the vertex found zombie ???!!!
if(kinkVertices.size()>1) Crop();
return kStOK;
}
//######################### DONE!!! ###############################################
/// Event filling
void StKinkMaker::FillEvent(StTrackGeometry *myDaughterGeometry1,StTrackGeometry *myParentGeometry11){
kinkVertex = new StKinkVertex();
StThreeVectorF pMomMinusdMom = mParentMoment - mDaughterMoment;
Float_t deltaKaonMuon = fabs(sqrt(mParentMoment.mag2() + kaonMass*kaonMass) -
sqrt(mDaughterMoment.mag2() + muonMass*muonMass) -
pMomMinusdMom.mag());
Float_t deltaKaonPion = fabs(sqrt(mParentMoment.mag2() + kaonMass*kaonMass) -
sqrt(mDaughterMoment.mag2() + pionMass*pionMass) -
sqrt(pMomMinusdMom.mag2() + pi0Mass*pi0Mass));
Float_t deltaPionMuon = fabs(sqrt(mParentMoment.mag2() + pionMass*pionMass) -
sqrt(mDaughterMoment.mag2() + muonMass*muonMass) -
pMomMinusdMom.mag());
//K-/+=>pi+/- + pi0
if ((deltaKaonPion < deltaKaonMuon) && (deltaKaonPion < deltaPionMuon) ){
Float_t asinArg = (mDaughterMoment.mag() / kaonToPionQ) * sin(mDecayAngle*degree);//sin(theta_cm)
if (fabs(asinArg) < 1. ) {
kinkVertex->setDecayAngleCM(float((1./degree) * asin(asinArg)));
}
else {
kinkVertex->setDecayAngleCM(999.) ;
}
if( myParentGeometry11->charge() > 0 ){ //parent K+
kinkVertex->setGeantIdDaughter(8);//daughter is pi+
kinkVertex->setGeantIdParent(11);
}
else {// parent K-
kinkVertex->setGeantIdDaughter(9);//daughter pi-
kinkVertex->setGeantIdParent(12);
}
} //K-/+=>mu+/- + (anti)neutrino
else if ((deltaKaonMuon < deltaKaonPion) && (deltaKaonMuon < deltaPionMuon) ) {
Float_t asinArg = (mDaughterMoment.mag() / kaonToMuonQ) * sin(mDecayAngle*degree);
if (fabs(asinArg) < 1. ) {
kinkVertex->setDecayAngleCM( (1./degree) * asin(asinArg) );
}
else {
kinkVertex->setDecayAngleCM( 999.) ;
}
if( myParentGeometry11->charge() > 0 ){ //parent K+
kinkVertex->setGeantIdDaughter(5);//daughter mu +
kinkVertex->setGeantIdParent(11);
}
else {//parent K-
kinkVertex->setGeantIdDaughter(6);//daughter mu-
kinkVertex->setGeantIdParent(12);
}
} else { //pi+/-=>mu+/- + (anti)neutrino
Float_t asinArg = (mDaughterMoment.mag() / pionToMuonQ) * sin(mDecayAngle*degree);
if( fabs(asinArg) < 1. ) {
kinkVertex->setDecayAngleCM( (1./degree) * asin(asinArg) );
}
else {
kinkVertex->setDecayAngleCM( 999.) ;
}
if (myParentGeometry11->charge() > 0 ){ //parent pi+
kinkVertex->setGeantIdDaughter(5);//daughter mu+
kinkVertex->setGeantIdParent(8);
}
else {//parent pi-
kinkVertex->setGeantIdDaughter(6);//daughter mu-
kinkVertex->setGeantIdParent(9);
}
}
kinkVertex->setDcaParentDaughter(mDca);
kinkVertex->setDcaDaughterPrimaryVertex(mDaughterImpact);//dca daughter from event vertex
kinkVertex->setDcaParentPrimaryVertex(mParentImpact);//dca parent from event vertex
//distance last point parent - first pt daughter
kinkVertex->setHitDistanceParentDaughter( (myDaughterGeometry1->origin() - myParentGeometry11->origin()).mag() );
//distance last point parent primary vertex
kinkVertex->setHitDistanceParentVertex(sqrt( pow(mKinkVertex.x() - myParentGeometry11->origin().x(), 2) +
pow(mKinkVertex.y() - myParentGeometry11->origin().y(), 2) +
pow(mKinkVertex.z() - myParentGeometry11->origin().z(), 2)) );
//set dE-delta enrgy for different deay hypotheses
kinkVertex->setdE(1,deltaKaonMuon);//dE for K->mu + (anti)neutrino
kinkVertex->setdE(2,deltaKaonPion);//dE for K->pi+pi0
kinkVertex->setdE(3,deltaPionMuon);//dE for pi->mu +(anti)neutrino
//set momentum
kinkVertex->setParentMomentum(mParentMoment);
kinkVertex->setDaughterMomentum(mDaughterMoment);
kinkVertex->setParent(mParentTrackCandidate);
//set dcay angle
kinkVertex->setDecayAngle(mDecayAngle);
//add daughter
kinkVertex->addDaughter(mDaughterTrackCandidate);
//set kinkVertex position
kinkVertex->setPosition(mKinkVertex);
}
/*!
Track acceptance filter
fittingMethod() as defined in pams/global/inc/StTrackMethod.h
(values themselves are defined in pams/global/inc/StTrackDefinitions.h)
while mUseTracker is defined as SetTrackerUsage(). Note that TPT
tracks are set as kHelix3DIdentifier BUT, we also found that there are
some cases (untraced) where the mEncodedMethod is reset to 0 (the only tracks
having kHelix3DIdentifier being tracks with SVT points). So, we had to revert
to a non-equality for safety purposes i.e. kTrackerUseTPT will consider any
tracks not being kITKalmanFitId (sad).
*/
/*!
Julien : I change this on Jerome's request : now TPT tracks will only be kHelix3DIdentifier... for safety purposes too ;-))
*/
bool StKinkMaker::acceptTrack(StTrack *trk)
{
//cout << "DEBUG Track [" << trk->fittingMethod() << "] [" << trk->flag() << "] FitIds ["
// << kKalmanFitId << "] [" << kITKalmanFitId << "] selector [" << mUseTracker << "]" << endl;
// cut on flag
if (trk->flag() <= 0) return false;
// on fittingMethod()
if (
//( trk->fittingMethod() == kHelix3DIdentifier && (mUseTracker == kTrackerUseTPT || mUseTracker == kTrackerUseBOTH) ) ||
( trk->fittingMethod() != kITKalmanFitId && (mUseTracker == kTrackerUseTPT || mUseTracker == kTrackerUseBOTH) ) ||
( trk->fittingMethod() == kITKalmanFitId && (mUseTracker == kTrackerUseITTF || mUseTracker == kTrackerUseBOTH) ) ){
return true;
} else {
return false;
}
}
/*!
Sets the tracker track-selection flag according to convention defined
enumeration in StV0FinderMaker.h . One should not confuse this value
with the value of the controlling parameter m_Mode setting calling
this method as follow
m_Mode=0 00 Leaves mUseTracker as default i.e. kTrackerUseBOTH (see ctor)
m_Mode=1 01 sets mUseTracker to kTrackerUseTPT
m_Mode=2 10 Sets mUseTracker to kTrackerUseITTF
m_Mode=3 11 Sets mUseTracker to kTrackerUseBOTH (bitmask)
See Init() for how this is set. The m_Mode convention would allow for
easier extension to yet another track-selection flags.
*/
void StKinkMaker::SetTrackerUsage(Int_t opt)
{
mUseTracker=opt;
gMessMgr->Info() << "StKinkMaker::SetTrackerUsage : Setting option to " << mUseTracker << endm;
}
void StKinkMaker::Crop(){
// Loop over kinks and remove (makeZombie() )+ change the decay angle for those that have one daughter sharing two different parents
gMessMgr->Info()<<"StKinkMaker::Crop() : Starting ...."<<endm;
event = (StEvent *)GetInputDS("StEvent");
StSPtrVecKinkVertex& kinkVertices = event->kinkVertices();
StKinkVertex* kinkVtxPtr1 = 0;//new StKinkVertex();
StKinkVertex* kinkVtxPtr2 = 0;// new StKinkVertex();
StTrack* daughterTrk1 = 0;
StTrack* daughterTrk2 = 0;
int iKinks = kinkVertices.size();
///////////////////////////////////////////////////////////////////////
// take pairs of consecutive kink vertices and check for same track key() for daugther
for(Int_t ikv1=0; ikv1<iKinks-1; ikv1++) {//first kink vertex from teh container
kinkVtxPtr1 = kinkVertices[ikv1];
daughterTrk1=kinkVtxPtr1->daughter();
// gMessMgr->Info()<<"###########StKinkMaker:daughter1->key()"<<daughterTrk1->key()<<endm;
for(Int_t ikv2=ikv1+1; ikv2<iKinks; ikv2++) {//next kink vertex in the container
kinkVtxPtr2 = kinkVertices[ikv2];
daughterTrk2=kinkVtxPtr2->daughter();
// gMessMgr->Info()<<"###########StKinkMaker: daughter2->key()"<<daughterTrk2->key()<<endm;
if(daughterTrk1->key() == daughterTrk2->key()) {
float decAngKinkVtx1 = kinkVtxPtr1->decayAngle();
float decAngKinkVtx2 = kinkVtxPtr2->decayAngle();
kinkVtxPtr1->setDecayAngle(decAngKinkVtx1*100+99);
kinkVtxPtr2->setDecayAngle(decAngKinkVtx2*100+99);
}
}//second vertex loop
}//first vtx loop
///////////////////////////////////////////////////////////////////////
// make Zombie the kink vertices with problems
// for(int ikv=iKinks-1;ikv>=0;ikv--){
// kinkVertex = kinkVertices[ikv];
// if( (kinkVertex->geantIdDaughter()%100) == 99){
// kinkVertex->makeZombie();
// // gMessMgr->Info()<<"###########StKinkMaker: AFTER "<<kinkVertex->decayAngle()%100<<endm;
// iKinks--;
// }
// }
// gMessMgr->Info()<<"StKinkMaker::Crop() : saving "<< iKinks << " Kink Candidates" <<endm;
}
| 39.04784 | 134 | 0.624353 | [
"geometry",
"3d"
] |
56f6827065b9aee2f376bab4a0a027c1d5dfc12f | 499 | cpp | C++ | OpenTESArena/src/World/SkyMoonDefinition.cpp | Alucowie/OpenTESArena | f8e04f288dfb587e390d15bf9eb6e017fe991d83 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/SkyMoonDefinition.cpp | Alucowie/OpenTESArena | f8e04f288dfb587e390d15bf9eb6e017fe991d83 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/SkyMoonDefinition.cpp | Alucowie/OpenTESArena | f8e04f288dfb587e390d15bf9eb6e017fe991d83 | [
"MIT"
] | null | null | null | #include "SkyMoonDefinition.h"
#include "components/debug/Debug.h"
void SkyMoonDefinition::init(std::vector<TextureAssetReference> &&textureAssetRefs)
{
this->textureAssetRefs = std::move(textureAssetRefs);
}
int SkyMoonDefinition::getTextureCount() const
{
return static_cast<int>(this->textureAssetRefs.size());
}
const TextureAssetReference &SkyMoonDefinition::getTextureAssetRef(int index) const
{
DebugAssertIndex(this->textureAssetRefs, index);
return this->textureAssetRefs[index];
}
| 24.95 | 83 | 0.795591 | [
"vector"
] |
56f7e5e52e21edebde86e1ffe71ef16fdb020c64 | 2,915 | hh | C++ | include/Run.hh | Kri-Ol/ProtonBub | 476949da8fd9545d22098bc92c4839750d0cbf3d | [
"MIT"
] | 1 | 2017-10-15T18:09:55.000Z | 2017-10-15T18:09:55.000Z | include/Run.hh | Kri-Ol/ProtonBub | 476949da8fd9545d22098bc92c4839750d0cbf3d | [
"MIT"
] | null | null | null | include/Run.hh | Kri-Ol/ProtonBub | 476949da8fd9545d22098bc92c4839750d0cbf3d | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <iostream>
#include "G4Run.hh"
#include "G4Event.hh"
#include "G4THitsMap.hh"
//---------------------------------------------------------------------
/// Run class
///
/// Example implementation for multi-functional-detector and primitive scorer.
/// This Run class has collections which accumulate
/// a event information into a run information.
//---------------------------------------------------------------------
class Run : public G4Run
{
#pragma region Data
private: std::vector<std::string> _CollName;
private: std::vector<int> _CollID;
private: std::vector<G4THitsMap<double>*> _runMap;
#pragma endregion
#pragma region Ctor/Dtor/ops
public: Run();
public: Run(const std::vector<std::string> mfdName);
public: virtual ~Run();
#pragma endregion
#pragma region Interfaces
public: virtual void RecordEvent(const G4Event*) override;
#pragma endregion
#pragma region Observers
// Access methods for scoring information.
// - Number of HitsMap for this RUN.
// This is equal to number of collections.
public: size_t GetNumberOfHitsMap() const
{
return _runMap.size();
}
// - Get HitsMap of this RUN.
// by sequential number, by multifucntional name and collection name,
// and by collection name with full path.
public: G4THitsMap<double>* GetHitsMap(size_t i) const
{
return _runMap[i];
}
public: G4THitsMap<double>* GetHitsMap(const std::string& detName,
const std::string& colName) const;
public: G4THitsMap<double>* GetHitsMap(const std::string& fullName) const;
void ConstructMFD(const std::vector<std::string>&);
virtual void Merge(const G4Run*) override;
#pragma endregion
};
//==========================================================================
// Generic Functions to help with merge
//==========================================================================
template <typename T> inline void
copy(std::vector<T>& main, const std::vector<T>& data)
{
for(auto i = main.size(); i != data.size(); ++i)
{
main.push_back(data.at(i));
}
}
template <typename T> inline size_t
copy(std::vector<T*>& main, const std::vector<T*>& data)
{
auto size_diff = data.size() - main.size();
for(auto i = main.size(); i != data.size(); ++i)
{
main.push_back(new T(*data.at(i)));
}
return size_diff;
}
template <typename T> inline std::ostream&
print(const std::vector<T>& data, std::ostream& os)
{
os << std::endl;
for(size_t i = 0; i != data.size(); ++i)
{
os << "\t\t" << i << " \t\t " << data.at(i) << std::endl;
}
os << std::endl;
return os;
}
template <typename T> inline std::ostream&
print(const std::vector<T>& data)
{
return print(data, std::cout);
}
| 27.5 | 78 | 0.568439 | [
"vector"
] |
56f94389126004853afad3bc819be479984bc474 | 17,535 | cpp | C++ | SliceModel.cpp | cbutakoff/DSI-Studio | d77dffa4526d66da421fa84f7187e85bca6bce7c | [
"BSD-3-Clause"
] | null | null | null | SliceModel.cpp | cbutakoff/DSI-Studio | d77dffa4526d66da421fa84f7187e85bca6bce7c | [
"BSD-3-Clause"
] | null | null | null | SliceModel.cpp | cbutakoff/DSI-Studio | d77dffa4526d66da421fa84f7187e85bca6bce7c | [
"BSD-3-Clause"
] | null | null | null | // ---------------------------------------------------------------------------
#include <string>
#include <QFileInfo>
#include <QInputDialog>
#include <QMessageBox>
#include <QDir>
#include "SliceModel.h"
#include "prog_interface_static_link.h"
#include "fib_data.hpp"
#include "fa_template.hpp"
// ---------------------------------------------------------------------------
SliceModel::SliceModel(void)
{
slice_visible[0] = false;
slice_visible[1] = false;
slice_visible[2] = false;
std::fill(transform.begin(),transform.end(),0.0);
transform[0] = transform[5] = transform[10] = transform[15] = 1.0;
invT = transform;
}
// ---------------------------------------------------------------------------
void SliceModel::get_mosaic(image::color_image& show_image,
unsigned int mosaic_size,
const image::value_to_color<float>& v2c,
unsigned int skip)
{
unsigned slice_num = geometry[2] / skip;
show_image.clear();
show_image.resize(image::geometry<2>(geometry[0]*mosaic_size,
geometry[1]*(std::ceil((float)slice_num/(float)mosaic_size))));
int old_z = slice_pos[2];
for(unsigned int z = 0;z < slice_num;++z)
{
slice_pos[2] = z*skip;
image::color_image slice_image;
get_slice(slice_image,2,v2c);
image::vector<2,int> pos(geometry[0]*(z%mosaic_size),
geometry[1]*(z/mosaic_size));
image::draw(slice_image,show_image,pos);
}
slice_pos[2] = old_z;
}
FibSliceModel::FibSliceModel(std::shared_ptr<fib_data> handle_,int view_id_):handle(handle_),view_id(view_id_)
{
// already setup the geometry and source image
geometry = handle_->dim;
voxel_size = handle_->vs;
slice_pos[0] = geometry.width() >> 1;
slice_pos[1] = geometry.height() >> 1;
slice_pos[2] = geometry.depth() >> 1;
}
// ---------------------------------------------------------------------------
std::pair<float,float> FibSliceModel::get_value_range(void) const
{
return std::make_pair(handle->view_item[view_id].min_value,handle->view_item[view_id].max_value);
}
// ---------------------------------------------------------------------------
void FibSliceModel::get_slice(image::color_image& show_image,unsigned char cur_dim,const image::value_to_color<float>& v2c) const
{
handle->get_slice(view_id,cur_dim, slice_pos[cur_dim],show_image,v2c);
}
// ---------------------------------------------------------------------------
image::const_pointer_image<float, 3> FibSliceModel::get_source(void) const
{
return handle->view_item[view_id].image_data;
}
// ---------------------------------------------------------------------------
void CustomSliceModel::init(void)
{
geometry = source_images.geometry();
slice_pos[0] = geometry.width() >> 1;
slice_pos[1] = geometry.height() >> 1;
slice_pos[2] = geometry.depth() >> 1;
min_value = *std::min_element(source_images.begin(),source_images.end());
max_value = *std::max_element(source_images.begin(),source_images.end());
scale = max_value-min_value;
if(scale != 0.0)
scale = 255.0/scale;
}
bool CustomSliceModel::initialize(std::shared_ptr<fib_data> handle,bool is_qsdr,
const std::vector<std::string>& files,
bool correct_intensity)
{
terminated = true;
ended = true;
is_diffusion_space = false;
gz_nifti nifti;
// QSDR loaded, use MNI transformation instead
bool has_transform = false;
name = QFileInfo(files[0].c_str()).completeBaseName().toStdString();
if(is_qsdr && files.size() == 1 && nifti.load_from_file(files[0]))
{
loadLPS(nifti);
invT.identity();
nifti.get_image_transformation(invT.begin());
invT.inv();
invT *= handle->trans_to_mni;
transform = image::inverse(invT);
has_transform = true;
}
else
{
if(files.size() == 1 && nifti.load_from_file(files[0]))
loadLPS(nifti);
else
{
if(files.size() == 1)
{
image::io::bruker_2dseq bruker;
if(bruker.load_from_file(files[0].c_str()))
{
bruker.get_voxel_size(voxel_size.begin());
bruker.get_image().swap(source_images);
init();
QDir d = QFileInfo(files[0].c_str()).dir();
if(d.cdUp() && d.cdUp())
{
QString method_file_name = d.absolutePath()+ "/method";
image::io::bruker_info method;
if(method.load_from_file(method_file_name.toStdString().c_str()))
name = method["Method"];
}
}
}
else
if(QFileInfo(files[0].c_str()).completeSuffix() == "bmp")
{
QString info_file = QString(files[0].c_str()) + ".info.txt";
if(!QFileInfo(info_file).exists())
{
std::cout << "Cannot find " << info_file.toStdString() << std::endl;
return false;
}
std::ifstream in(info_file.toStdString().c_str());
in >> geometry[0];
in >> geometry[1];
in >> geometry[2];
in >> voxel_size[0];
in >> voxel_size[1];
in >> voxel_size[2];
std::vector<float> T;
std::copy(std::istream_iterator<float>(in),
std::istream_iterator<float>(),std::back_inserter(T));
if(T.size() != 12)
{
std::cout << "Invalid BMP info text: failed to read transformation matrix." << std::endl;
return false;
}
if(geometry[2] != files.size())
{
std::cout << "Invalid BMP info text: file count does not match." << std::endl;
return false;
}
unsigned int in_plane_subsample = 1;
unsigned int slice_subsample = 1;
// non isotropic condition
while(voxel_size[2]/voxel_size[0] > 1.5f)
{
++in_plane_subsample;
geometry[0] = geometry[0] >> 1;
geometry[1] = geometry[1] >> 1;
voxel_size[0] *= 2.0;
voxel_size[1] *= 2.0;
T[0] *= 2.0;
T[1] *= 2.0;
T[4] *= 2.0;
T[5] *= 2.0;
T[8] *= 2.0;
T[9] *= 2.0;
}
image::geometry<3> geo(geometry);
bool ok;
int down_size = QInputDialog::getInt(0,
"DSI Studio",
"Downsampling count (0:no downsampling)",1,0,4,1&ok);
if(!ok)
return false;
while(1)
{
if(down_size)
--down_size;
else
{
try{
image::basic_image<float, 3> buf;
buf.resize(geo);
buf.swap(source_images);
}
catch(...)
{
QMessageBox::information(0,"DSI Studio","Memory allocation failed. Please increase downsizing count",0);
return false;
}
break;
}
geo[0] = geo[0] >> 1;
geo[1] = geo[1] >> 1;
geo[2] = geo[2] >> 1;
voxel_size *= 2.0;
image::multiply_constant(T.begin(),T.begin()+3,2.0);
image::multiply_constant(T.begin()+4,T.begin()+7,2.0);
image::multiply_constant(T.begin()+8,T.begin()+11,2.0);
++in_plane_subsample;
++slice_subsample;
}
begin_prog("loading images");
for(unsigned int i = 0;check_prog(i,geo[2]);++i)
{
image::basic_image<short,2> I;
image::io::bitmap bmp;
unsigned int file_index = (slice_subsample == 1 ? i : (i << (slice_subsample-1)));
if(file_index >= files.size())
break;
if(!bmp.load_from_file(files[file_index].c_str()))
{
std::cout << "Invalid BMP format: " << files[file_index] << std::endl;
return false;
}
bmp >> I;
for(int j = 1;j < in_plane_subsample;++j)
image::downsampling(I);
if(I.size() != source_images.plane_size())
{
std::cout << "Invalid BMP image size: " << files[file_index] << std::endl;
return false;
}
std::copy(I.begin(),I.end(),source_images.begin() + i*source_images.plane_size());
}
if(prog_aborted())
return false;
image::io::nifti nii;
nii.set_dim(geo);
nii.set_voxel_size(voxel_size.begin());
nii.set_image_transformation(T.begin());
nii << source_images;
nii.toLPS(source_images);
nii.get_voxel_size(voxel_size.begin());
transform.identity();
nii.get_image_transformation(transform.begin());
// LPS matrix switched to RAS
transform[0] = -transform[0];
transform[1] = -transform[1];
transform[4] = -transform[4];
transform[5] = -transform[5];
transform[8] = -transform[8];
transform[9] = -transform[9];
invT = image::inverse(transform);
has_transform = true;
}
else
{
image::io::volume volume;
if(volume.load_from_files(files,files.size()))
load(volume);
else
return false;
}
}
// same dimension, no registration required.
if(source_images.geometry() == handle->dim)
{
transform.identity();
invT.identity();
is_diffusion_space = true;
has_transform = true;
}
// same dimension different resolution, no registrationrequired
float r = std::round((float)source_images.width()/(float)handle->dim[0]);
if(r > 1.0 && r == std::round(source_images.height()/handle->dim[1]) &&
r == std::round(source_images.depth()/handle->dim[2]))
{
transform.identity();
invT.identity();
invT[0] = r;
invT[5] = r;
invT[10] = r;
invT[15] = 1.0;
transform = image::inverse(invT);
has_transform = true;
}
}
// quality control for t1w
if(correct_intensity)
{
float t = image::segmentation::otsu_threshold(source_images);
float snr = image::mean(source_images.begin()+source_images.width(),source_images.begin()+2*source_images.width());
// correction for SNR
for(unsigned int i = 0;i < 6 && snr != 0 && t/snr < 10;++i)
{
image::filter::gaussian(source_images);
t = image::segmentation::otsu_threshold(source_images);
snr = image::mean(source_images.begin()+source_images.width(),source_images.begin()+2*source_images.width());
}
// correction for intensity bias
t = image::segmentation::otsu_threshold(source_images);
std::vector<float> x,y;
for(unsigned char dim = 0;dim < 3;++dim)
{
x.clear();
y.clear();
for(image::pixel_index<3> i(source_images.geometry());i < source_images.size();++i)
if(source_images[i.index()] > t)
{
x.push_back(i[dim]);
y.push_back(source_images[i.index()]);
}
std::pair<double,double> r = image::linear_regression(x.begin(),x.end(),y.begin());
for(image::pixel_index<3> i(source_images.geometry());i < source_images.size();++i)
source_images[i.index()] -= (float)i[dim]*r.first;
image::lower_threshold(source_images,0);
}
}
geometry = source_images.geometry();
if(!has_transform)
{
if(handle->dim.depth() < 10) // 2d assume FOV is the same
{
transform.identity();
invT.identity();
invT[0] = (float)source_images.width()/(float)handle->dim.width();
invT[5] = (float)source_images.height()/(float)handle->dim.height();
invT[10] = (float)source_images.depth()/(float)handle->dim.depth();
invT[15] = 1.0;
transform = image::inverse(invT);
}
else
{
from = image::make_image(handle->dir.fa[0],handle->dim);
from_vs = handle->vs;
thread.reset(new std::future<void>(
std::async(std::launch::async,[this](){argmin(image::reg::rigid_body);})));
}
}
return true;
}
// ---------------------------------------------------------------------------
std::pair<float,float> CustomSliceModel::get_value_range(void) const
{
return image::min_max_value(source_images.begin(),source_images.end());
}
// ---------------------------------------------------------------------------
void CustomSliceModel::argmin(image::reg::reg_type reg_type)
{
terminated = false;
ended = false;
size_ratio = 1.0f;
/*
if(from_vs[0]/voxel_size[0] > 2.0f)
{
source_buf_vs = voxel_size;
source_buf.clear();
while(from_vs[0]/source_buf_vs[0] > 2.0f)
{
source_buf_vs *= 2.0;
size_ratio *= 2.0;
if(source_buf.empty())
image::downsampling(source_images,source_buf);
else
image::downsampling(source_buf);
}
image::const_pointer_image<float,3> to = source_buf;
image::reg::linear_mr(from,from_vs,to,source_buf_vs,arg_min,reg_type,image::reg::mutual_information_mt(),terminated);
}
else*/
{
image::const_pointer_image<float,3> to = source_images;
image::reg::linear_mr(from,from_vs,to,voxel_size,arg_min,reg_type,image::reg::mutual_information(),terminated,0.1);
image::reg::linear_mr(from,from_vs,to,voxel_size,arg_min,reg_type,image::reg::mutual_information(),terminated,0.01);
}
ended = true;
}
// ---------------------------------------------------------------------------
void CustomSliceModel::update(void)
{
if(size_ratio != 1.0)
{
image::transformation_matrix<double> T(arg_min,from.geometry(),from_vs,source_buf.geometry(),source_buf_vs);
invT.identity();
T.save_to_transform(invT.begin());
image::multiply_constant(invT,size_ratio);
}
else
{
image::transformation_matrix<double> T(arg_min,from.geometry(),from_vs,source_images.geometry(),voxel_size);
invT.identity();
T.save_to_transform(invT.begin());
}
transform = image::inverse(invT);
}
// ---------------------------------------------------------------------------
void CustomSliceModel::terminate(void)
{
terminated = true;
if(thread.get())
thread->wait();
ended = true;
}
// ---------------------------------------------------------------------------
void CustomSliceModel::get_slice(image::color_image& show_image,unsigned char cur_dim,const image::value_to_color<float>& v2c) const
{
image::basic_image<float,2> buf;
image::reslicing(source_images, buf, cur_dim, slice_pos[cur_dim]);
v2c.convert(buf,show_image);
}
// ---------------------------------------------------------------------------
bool CustomSliceModel::stripskull(float qa_threshold)
{
if(!ended)
return false;
update();
image::basic_image<float,3> filter(source_images.geometry());
image::resample(from,filter,transform,image::linear);
image::upper_threshold(filter,qa_threshold);
image::filter::gaussian(filter);
image::filter::gaussian(filter);
float m = *std::max_element(source_images.begin(),source_images.end());
source_images *= filter;
image::normalize(source_images,m);
return true;
}
| 40.125858 | 136 | 0.473852 | [
"geometry",
"vector",
"transform"
] |
71009bec2c64011cb4b366be45365e1bc207d7da | 1,300 | cpp | C++ | tests/unit_tests/Repo/image/DeleteImage.cpp | Allaeddineattia/Valravn | 7afa00bfe3c6f0c8357209601a67508a35b466b5 | [
"MIT"
] | null | null | null | tests/unit_tests/Repo/image/DeleteImage.cpp | Allaeddineattia/Valravn | 7afa00bfe3c6f0c8357209601a67508a35b466b5 | [
"MIT"
] | null | null | null | tests/unit_tests/Repo/image/DeleteImage.cpp | Allaeddineattia/Valravn | 7afa00bfe3c6f0c8357209601a67508a35b466b5 | [
"MIT"
] | 2 | 2021-05-07T20:35:55.000Z | 2021-07-08T15:14:43.000Z | //
// Created by alro on 29/11/2020.
//
#include <Shared/DependencyInjector.h>
#include <Shared/Tools.h>
#include <Entity/Contract/Image.h>
#include "gtest/gtest.h"
#include "../tools/Database.h"
#include "../stubs/Images.h"
using namespace std;
TEST(image_deleting, delete_saved_image){
string fileName = "testdata.db";
ASSERT_EQ(Unit_testing::Database::drop_database(fileName), true);
shared_ptr<DependencyInjector> di = make_shared<DependencyInjector> ();
di->install_data_base(fileName);
di->install_multimedia_repo(di);
di->install_image_repo(di);
ASSERT_EQ( Unit_testing::Database::init_database(di), true);
Unit_testing::Images::seed_db_with_images(di);
auto image_repo = di->get_image_repo(di);
Image::installRepo(image_repo);
auto image = Unit_testing::Images::get_image_1();
image->remove();
auto res = Image::fetchById(image->getId());
ASSERT_EQ(res.has_value(), false);
vector<unique_ptr<Image>> images;
images.push_back(Unit_testing::Images::get_image_2());
images.push_back(Unit_testing::Images::get_image_3());
auto images_res = Image::getAll();
bool equality = std::equal(images_res.begin(), images_res.end(), images.begin(), Tools::unique_ptr_vec_comparator<Image>);
ASSERT_EQ( equality, true);
}; | 36.111111 | 126 | 0.716154 | [
"vector"
] |
71024ecc5c0367cb46aa582019af4da8c757290b | 1,640 | cpp | C++ | C or C++/ConsDestructor.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-11-01T05:48:04.000Z | 2021-04-25T05:33:47.000Z | C or C++/ConsDestructor.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | null | null | null | C or C++/ConsDestructor.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-10-31T05:29:55.000Z | 2021-06-19T09:33:53.000Z | // Using a constructor and destructor
#include <iostream>
#include <map>
#include <new>
#include <cstdlib>
using namespace std;
const int SIZE=100;
// This creates the class stack.
class stack
{
int stck[SIZE];
int tos;
public:
stack(); // constructor
~stack(); // destructor
void push(int i);
int pop();
stack(const stack &a);// copy constructor
};
// stack's constructor
stack::stack()
{
try
{
stck = new int[100];
}
catch(bad_alloc xa)
{
cout << "Allocation Failure" << endl;
exit(EXIT_FAILURE);
}
tos = 0;
cout << "Stack Initialized\n";
}
// stack's destructor
stack::~stack()
{
cout << "Stack Destroyed\n";
}
stack::stack(const stack &a)
{
// constructor to copy the elements of the data of object a to the new object
try
{
stck = new int[SIZE];
}
catch(bad_alloc xa)
{
cout << "Allocation Failure" << endl;
exit(EXIT_FAILURE);
}
for(int i=0;i<SIZE;i++)
stck[i] = a.stck[i];
}
void stack::push(int i)
{
if(tos==SIZE)
{
cout << "Stack is full.\n";
return;
}
stck[tos] = i;
tos++;
}
int stack::pop()
{
if(tos==0)
{
cout << "Stack underflow.\n";
return 0;
}
tos--;
return stck[tos];
}
int main()
{
stack a, b;
// create two stack objects
//
//
a.push(1);
b.push(2);
a.push(3);
b.push(4);
cout << a.pop() << endl;
cout << a.pop() << endl;
cout << b.pop() << endl;
cout << b.pop() << endl;
cout << "Reached end of file";
return 0;
};
| 17.446809 | 81 | 0.518293 | [
"object"
] |
710b38dcc9ecaf909efa4216d580c37795a7b5b8 | 13,545 | cpp | C++ | src/myoCollector.cpp | JinkiJung/GetGes | cfc27cf55a8785cd2feab90d92ddf7cafa37e19d | [
"MIT"
] | null | null | null | src/myoCollector.cpp | JinkiJung/GetGes | cfc27cf55a8785cd2feab90d92ddf7cafa37e19d | [
"MIT"
] | null | null | null | src/myoCollector.cpp | JinkiJung/GetGes | cfc27cf55a8785cd2feab90d92ddf7cafa37e19d | [
"MIT"
] | null | null | null | #include "MyoCollector.h"
#define EMG_ELEMENT_NUM 8
#define NOT_CALIBRATED -1
using namespace cv;
using namespace std;
MyoCollector::MyoCollector()
{
}
void MyoCollector::collect(myo::Hub*& hub){
// set sensor frequency for collecting data
hub->run(MYO_FREQUENCY);
//hub->run(50);
}
int MyoCollector::init(myo::Hub*& hub){
// We catch any exceptions that might occur below -- see the catch statement for more details.
try {
// First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when
// publishing your application. The Hub provides access to one or more Myos.
hub = new myo::Hub("dev.jinki.getges");
std::cout << "Attempting to find a Myo..." << std::endl;
myo::Myo* myo = hub->waitForMyo(50);
// If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message.
if (!myo) {
throw std::runtime_error("Unable to find a Myo!");
}
// We've found a Myo.
std::cout << "Connected to a Myo armband!" << std::endl << std::endl;
// Next we construct an instance of our DeviceListener, so that we can register it with the Hub.
// Hub::addListener() takes the address of saveTrainDataany object whose class inherits from DeviceListener, and will cause
// Hub::run() to send events to all registered device listeners.
hub->addListener(this);
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Press enter to continue.";
std::cin.ignore();
return -2;
}
return 1;
}
void MyoCollector::onAccelerometerData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3< float > &accel){
int curMyoIdx = getMyoIdx(myo);
myoData[curMyoIdx].accelMat = (Mat_<float>(1,3) << accel[0], accel[1], accel[2] );
}
// onUnpair() is called whenever the Myo is disconnected from Myo Connect by the user.
void MyoCollector::onUnpair(myo::Myo* myo, uint64_t timestamp)
{
// We've lost a Myo.
// Let's clean up some leftover state.
int curMyoIdx = getMyoIdx(myo);
myoData[curMyoIdx].emgSamples.fill(0);
myoData[curMyoIdx].roll_w = 0;
myoData[curMyoIdx].pitch_w = 0;
myoData[curMyoIdx].yaw_w = 0;
myoData[curMyoIdx].onArm = false;
myoData[curMyoIdx].isUnlocked = false;
}
// onOrientationData() is called whenever the Myo device provides its current orientation, which is represented
// as a unit quaternion.
void MyoCollector::onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion<float>& quat)
{
int curMyoIdx = getMyoIdx(myo);
using std::atan2;
using std::asin;
using std::sqrt;
using std::max;
using std::min;
// Calculate Euler angles (roll, pitch, and yaw) from the unit quaternion.
float roll = atan2(2.0f * (quat.w() * quat.x() + quat.y() * quat.z()),
1.0f - 2.0f * (quat.x() * quat.x() + quat.y() * quat.y()));
float pitch = asin(max(-1.0f, min(1.0f, 2.0f * (quat.w() * quat.y() - quat.z() * quat.x()))));
float yaw = atan2(2.0f * (quat.w() * quat.z() + quat.x() * quat.y()),
1.0f - 2.0f * (quat.y() * quat.y() + quat.z() * quat.z()));
myoData[curMyoIdx].quatMat = (Mat_<float>(1, 4) << quat.x(), quat.y(), quat.z(), quat.w());
// Convert the floating point angles in radians to a scale from 0 to 180.
myoData[curMyoIdx].roll_w = (float)((roll + (float)M_PI) / (M_PI * 2.0f) * 180) - myoData[curMyoIdx].calibDegOffset[0];
myoData[curMyoIdx].pitch_w = (float)((pitch + (float)M_PI / 2.0f) / M_PI * 180) - myoData[curMyoIdx].calibDegOffset[1];
myoData[curMyoIdx].yaw_w = (float)((yaw + (float)M_PI) / (M_PI * 2.0f) * 180) - myoData[curMyoIdx].calibDegOffset[2];
}
void MyoCollector::onConnect(myo::Myo* myo, uint64_t timestamp, myo::FirmwareVersion firmwareVersion) {
std::cout << "Myo " << myo << " has connected." << std::endl;
knownMyos.push_back(myo);
myo->setStreamEmg(myo::Myo::streamEmgEnabled);
std::ostringstream s;
s << myo;
string myoAdd = s.str();
MyoData newMyoData1(myoAdd);
myoData.push_back(newMyoData1);
}
void MyoCollector::onDisconnect(myo::Myo* myo, uint64_t timestamp) {
std::cout << "Myo " << myo << " has disconnected." << std::endl;
// erase element from myo data array
// to notify one of myo has disconnected
for (int i = 0; i < myoData.size(); i++){
std::ostringstream s;
s << myo;
string myoAdd = s.str();
if (myoData[i].UID == myoAdd){//dynamic_cast<std::ostringstream&>(std::ostringstream() << myo).str()){
myoData.erase(myoData.begin() + i);
break;
}
}
}
// onPose() is called whenever the Myo detects that the person wearing it has changed their pose, for example,
// making a fist, or not making a fist anymore.
void MyoCollector::onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
{
myoData[getMyoIdx(myo)].currentPose = pose;
if (pose != myo::Pose::unknown && pose != myo::Pose::rest) {
// Tell the Myo to stay unlocked until told otherwise. We do that here so you can hold the poses without the
// Myo becoming locked.
myo->unlock(myo::Myo::unlockHold);
// Notify the Myo that the pose has resulted in an action, in this case changing
// the text on the screen. The Myo will vibrate.
myo->notifyUserAction();
}
else {
// Tell the Myo to stay unlocked only for a short period. This allows the Myo to stay unlocked while poses
// are being performed, but lock after inactivity.
myo->unlock(myo::Myo::unlockTimed);
}
}
// onArmSync() is called whenever Myo has recognized a Sync Gesture after someone has put it on their
// arm. This lets Myo know which arm it's on and which way it's facing.
void MyoCollector::onArmSync(myo::Myo* myo, uint64_t timestamp, myo::Arm arm, myo::XDirection xDirection, float rotation,
myo::WarmupState warmupState)
{
//myoData[getMyoIdx(myo)].onArm = true;
//myoData[getMyoIdx(myo)].whichArm = arm;
}
// onArmUnsync() is called whenever Myo has detected that it was moved from a stable position on a person's arm after
// it recognized the arm. Typically this happens when someone takes Myo off of their arm, but it can also happen
// when Myo is moved around on the arm.
void MyoCollector::onArmUnsync(myo::Myo* myo, uint64_t timestamp)
{
//myoData[getMyoIdx(myo)].onArm = false;
}
void MyoCollector::onPair(myo::Myo* myo, uint64_t timestamp, myo::FirmwareVersion firmwareVersion){
// Print out the MAC address of the armband we paired with.
// The pointer address we get for a Myo is unique - in other words, it's safe to compare two Myo pointers to
// see if they're referring to the same Myo.
// Add the Myo pointer to our list of known Myo devices. This list is used to implement getMyoIdx() below so
// that we can give each Myo a nice short identifier.
//knownMyos.push_back(myo); // Now that we've added it to our list, get our short ID for it and print it out.
std::ostringstream s;
s << myo;
string myoAdd = s.str();
std::cout << "Paired with " << myoAdd << "." << std::endl;
//knownMyos.push_back()
}
int MyoCollector::getMyoIdx(myo::Myo* myo) {
// Walk through the list of Myo devices that we've seen pairing events for.
for (size_t i = 0; i < knownMyos.size(); ++i) {
// If two Myo pointers compare equal, they refer to the same Myo device.
if (knownMyos[i] == myo) {
return i ;
}
} return 0;
}
// onUnlock() is called whenever Myo has become unlocked, and will start delivering pose events.
void MyoCollector::onUnlock(myo::Myo* myo, uint64_t timestamp)
{
myoData[getMyoIdx(myo)].isUnlocked = true;
}
// onLock() is called whenever Myo has become locked. No pose events will be sent until the Myo is unlocked again.
void MyoCollector::onLock(myo::Myo* myo, uint64_t timestamp)
{
myoData[getMyoIdx(myo)].isUnlocked = false;
}
// onEmgData() is called whenever a paired Myo has provided new EMG data, and EMG streaming is enabled.
void MyoCollector::onEmgData(myo::Myo* myo, uint64_t timestamp, const int8_t* emg)
{
int curMyoIdx = getMyoIdx(myo);
std::vector<int> values;
for (int i = 0; i < EMG_ELEMENT_NUM; i++) {
int idx = i - myoData[curMyoIdx].calibEmgOffset;
if( idx < 0 )
idx += EMG_ELEMENT_NUM;
myoData[curMyoIdx].emgSamples[idx] = emg[i];
}
for (int i = 0; i<myoData[curMyoIdx].emgSamples.size(); i++)
values.push_back(myoData[curMyoIdx].emgSamples[i]);
Mat tempValues(values);
myoData[curMyoIdx].emgMat = tempValues.clone();
}
// There are other virtual functions in DeviceListener that we could override here, like onAccelerometerData().
// For this example, the functions overridden above are sufficient.
// We define this function to print the current values that were updated by the on...() functions above.
void MyoCollector::visualizeRawData(bool showRawData)
{
// Clear the current line
//std::cout << '\r';
for (int i = 0; i < myoData.size(); i++){
int curMyoIdx = i;
int baseline4Rows = myoData[curMyoIdx].visual.rows - 50;
//if ( !myoData[i].onArm )
// continue;
float avgMag = 0;
Mat values;
// Print out the EMG data.
for (size_t i = 0; i < myoData[curMyoIdx].emgSamples.size(); i++) {
std::ostringstream oss;
oss << static_cast<int>(myoData[curMyoIdx].emgSamples[i]);
std::string emgString = oss.str();
int value = (atoi(emgString.c_str()));
int width = (int)i * VISUALIZING_INTERVAL + 20;
rectangle(myoData[curMyoIdx].visual, Point(width, baseline4Rows / 2), Point(width + VISUALIZING_BAR_WIDTH, baseline4Rows / 2 + value), myoData[curMyoIdx].colorPot[i], -1);
avgMag += value*value;
values.push_back(value);
if (showRawData)
std::cout << '[' << emgString << std::string(4 - emgString.size(), ' ') << ']';
string valueTitle = to_string(i);
putText(myoData[curMyoIdx].visual, valueTitle, Point(width, myoData[curMyoIdx].visual.rows - 10), FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255, 255, 255), 1);
}
int index = 8;
int width = 8 * VISUALIZING_INTERVAL + 20;
Scalar mean, sdv;
values = abs(values);
meanStdDev(values, mean, sdv);
rectangle(myoData[curMyoIdx].visual, Point(width, baseline4Rows), Point(width + VISUALIZING_BAR_WIDTH, baseline4Rows - mean(0)), myoData[curMyoIdx].colorPot[index], -1);
putText(myoData[curMyoIdx].visual, "mean", Point(width, myoData[curMyoIdx].visual.rows - 10), FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255, 255, 255), 1);
index++;
width = 9 * VISUALIZING_INTERVAL + 20;
rectangle(myoData[curMyoIdx].visual, Point(width, baseline4Rows), Point(width + VISUALIZING_BAR_WIDTH, baseline4Rows - sdv(0)), myoData[curMyoIdx].colorPot[index], -1);
putText(myoData[curMyoIdx].visual, "sdv", Point(width, myoData[curMyoIdx].visual.rows - 10), FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255, 255, 255), 1);
index++;
//std::cout << "\t" << mean(0) << "\t" << sdv(0) << std::endl;
Mat ori_mat = (Mat_<float>(1, 3) << myoData[curMyoIdx].roll_w, myoData[curMyoIdx].pitch_w, myoData[curMyoIdx].yaw_w);
//*
width = 10 * VISUALIZING_INTERVAL + 20;
rectangle(myoData[curMyoIdx].visual, Point(width, 0), Point(width + VISUALIZING_BAR_WIDTH, ori_mat.at<float>(0, 0)), myoData[curMyoIdx].colorPot[index++], -1);
putText(myoData[curMyoIdx].visual, "roll", Point(width, myoData[curMyoIdx].visual.rows - 10), FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255, 255, 255), 1);
width = 11 * VISUALIZING_INTERVAL + 20;
rectangle(myoData[curMyoIdx].visual, Point(width, 0), Point(width + VISUALIZING_BAR_WIDTH, ori_mat.at<float>(0, 1)), myoData[curMyoIdx].colorPot[index++], -1);
putText(myoData[curMyoIdx].visual, "pitch", Point(width, myoData[curMyoIdx].visual.rows - 10), FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255, 255, 255), 1);
width = 12 * VISUALIZING_INTERVAL + 20;
rectangle(myoData[curMyoIdx].visual, Point(width, 0), Point(width + VISUALIZING_BAR_WIDTH, ori_mat.at<float>(0, 2)), myoData[curMyoIdx].colorPot[index++], -1);
putText(myoData[curMyoIdx].visual, "yaw", Point(width, myoData[curMyoIdx].visual.rows - 10), FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255, 255, 255), 1);
//*/
// Print out the orientation. Orientation data is always available, even if no arm is currently recognized.
//std::cout << '[' << std::string(roll_w, '*') << std::string(180 - roll_w, ' ') << ']' << '[' << std::string(pitch_w, '*') << std::string(180 - pitch_w, ' ') << ']' << '[' << std::string(yaw_w, '*') << std::string(180 - yaw_w, ' ') << ']';
if (myoData[curMyoIdx].onArm) {
// Print out the lock state, the currently recognized pose, and which arm Myo is being worn on.
// Pose::toString() provides the human-readable name of a pose. We can also output a Pose directly to an
// output stream (e.g. std::cout << currentPose;). In this case we want to get the pose name's length so
// that we can fill the rest of the field with spaces below, so we obtain it as a string using toString().
std::string poseString = myoData[curMyoIdx].currentPose.toString();
//std::cout << '[' << (isUnlocked ? "unlocked" : "locked ") << ']' << '[' << (whichArm == myo::armLeft ? "L" : "R") << ']' << '[' << poseString << std::string(14 - poseString.size(), ' ') << ']';
}
else {
// Print out a placeholder for the arm and pose when Myo doesn't currently know which arm it's on.
//std::cout << '[' << std::string(8, ' ') << ']' << "[?]" << '[' << std::string(14, ' ') << ']';
}
if (showRawData)
std::cout << std::endl;
std::string name = "graph - " + myoData[curMyoIdx].UID;
imshow(name.c_str(), myoData[curMyoIdx].visual);
myoData[curMyoIdx].visual = myoData[curMyoIdx].visual* 0.6f;
//waitKey(1);
}
}
| 42.59434 | 242 | 0.674492 | [
"object",
"vector"
] |
71164154eba3bf50f9c7a951f69a6befedfd31f8 | 1,695 | cpp | C++ | examples/quadratic.cpp | marcorushdy/realGen | 2441cbb81d034137926c0f50c7dcdc6777329b76 | [
"MIT"
] | 16 | 2017-04-23T23:24:08.000Z | 2021-03-12T21:38:28.000Z | examples/quadratic.cpp | marcorushdy/realGen | 2441cbb81d034137926c0f50c7dcdc6777329b76 | [
"MIT"
] | null | null | null | examples/quadratic.cpp | marcorushdy/realGen | 2441cbb81d034137926c0f50c7dcdc6777329b76 | [
"MIT"
] | 6 | 2017-06-14T11:50:37.000Z | 2019-05-16T20:09:07.000Z | #include <iostream>
#include <time.h>
#include "realgen.h"
#include "fitnessfunction.h"
#define N_SAMPLE 1000
using namespace std;
class QuadraticFitness : public FitnessFunction {
public:
double eval(const RealGenotype &g) {
double f = 0.0;
double dx1 = g.gene[0]-2.5,
dx2 = g.gene[1]-2.5;
return dx1*dx1+dx2*dx2;
}
};
int main(int argc, char** argv) {
vector<float> LB = {-5.0, -5.0}; // Lower bound of genes
vector<float> UB = { 5.0, 5.0}; // Upper bound of genes
QuadraticFitness *myFitnessFunction = new QuadraticFitness();
RealGenOptions options;
options.setChromosomeSize(2);
options.setPopulationSize(200);
options.setBounds(LB, UB);
options.setMaxGenerations(200);
options.setMutationType("gaussian");
options.setMutationRate(0.05);
options.setMutationGaussianScaleShrink(1, 1);
// Define RealGen(Population size, number of genes in a chromosome, LB, UB)
RealGen ga(options);
ga.setFitnessFunction(myFitnessFunction);
ga.setVerbose(true);
// Init population with uniform random
ga.initRandom();
// Evolve the population for 100 times
for (int i=0; i<100; i++) {
ga.evolve();
cout << "Diversity " << ga.getDiversity() << endl;
}
// get the best score function (the minimum)
RealGenotype best = ga.getBestChromosome();
// Print results
cout << ga.populationToString(); // print all the population
cout << "Best solution: "<< best.toString() << endl;
cout << "Best Fitness value = " << best.fitness << endl;
delete myFitnessFunction;
return 0;
}
| 30.267857 | 80 | 0.625369 | [
"vector"
] |
712c0fe49f738076d1730570dcf014ce85710104 | 2,268 | cpp | C++ | src/geomodel.cpp | yramachers/SNDrift | fcadc0a8f812db071f0911a7c811b34ff4bfecba | [
"MIT"
] | null | null | null | src/geomodel.cpp | yramachers/SNDrift | fcadc0a8f812db071f0911a7c811b34ff4bfecba | [
"MIT"
] | null | null | null | src/geomodel.cpp | yramachers/SNDrift | fcadc0a8f812db071f0911a7c811b34ff4bfecba | [
"MIT"
] | null | null | null | // us
#include "geomodel.hh"
// standard includes
#include <iostream>
// ROOT includes
#include "TGeoVolume.h"
#include "TString.h"
#include "TObjArray.h"
//****************
// Geometry Model
//****************
// Constructors
GeometryModel::GeometryModel(const char* filename) {
// import geometry from file
// closes geometry but ID's can be different to initial building
TGeoManager* g = new TGeoManager("dummy","");
try {
geom = g->Import(filename);
fill_wires(); // only constructed when geometry is known from file
} catch (const std::exception& e) {
std::cout << "Exception: " << e.what() << std::endl;
std::cout << "Could not import " << std::endl;
return;
}
}
// default Destructor
GeometryModel::~GeometryModel() {
wires.clear();
if (geom) delete geom;
}
void GeometryModel::fill_wires() {
TGeoVolume* vol = geom->FindVolumeFast("Comsol"); // hard-wired region name
TObjArray* lon = vol->GetNodes(); // should all be in comsol region
TString name;
for (int n=0;n<lon->GetEntries();n++) {
name = lon->At(n)->GetName();
if (name.Contains("Wire")) // hard-wired wire name
wires.push_back((TGeoNode*)lon->At(n));
}
std::cout << "Geometry model; got "<< wires.size() << " wires" << std::endl;
}
int GeometryModel::whereami(double xv, double yv, double zv) {
// Talk to geometry
geom->SetCurrentPoint(xv,yv,zv);
TGeoNode* nd = geom->FindNode();
TGeoVolume* vol = nd->GetVolume();
TString region(vol->GetName()); // changed from GetNumber()
// std::cout << "Geometry model: region = " << region << std::endl;
// std::cout << "Geometry model: coords: " << xv << " " << yv << " " << zv << std::endl;
// the four considered cases as answers to Where Am I
if (region.Contains("Comsol"))
return 1; // drifting region, field map
else if (region.Contains("Wire")) {
return -1; // stop
}
else if (region.Contains("World")) {
return -1; // out, stop transport
}
else {
std::cout << "Geometry model: undefined place" << std::endl;
std::cout << "Geometry model: coords: " << xv << " " << yv << " " << zv << std::endl;
std::cout << "Geometry model: name: " << region << std::endl;
return -1; // should never get here, stop
}
}
| 26.372093 | 91 | 0.608466 | [
"geometry",
"model"
] |
712d1a46b1f72b8da8d38a5226f4707d758879e4 | 34,709 | cc | C++ | Translator_file/examples/step-30/step-30.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null | Translator_file/examples/step-30/step-30.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null | Translator_file/examples/step-30/step-30.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null |
/* ---------------------------------------------------------------------
*
* Copyright (C) 2007 - 2021 by the deal.II authors
*
* This file is part of the deal.II library.
*
* The deal.II library is free software; you can use it, redistribute
* it, and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* The full text of the license can be found in the file LICENSE.md at
* the top level directory of deal.II.
*
* ---------------------------------------------------------------------
*
* Author: Tobias Leicht, 2007
*/
// deal.II包括的文件已经在前面的例子中介绍过了,因此不再做进一步的评论。
#include <deal.II/base/function.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/timer.h>
#include <deal.II/lac/precondition_block.h>
#include <deal.II/lac/solver_richardson.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/mapping_q1.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/derivative_approximation.h>
// 而这又是C++。
#include <array>
#include <iostream>
#include <fstream>
// 最后一步和以前所有的程序一样。
namespace Step30
{
using namespace dealii;
// @sect3{Equation data}
// 描述方程数据的类和单个术语的实际装配几乎完全照搬自 step-12 。我们将对差异进行评论。
template <int dim>
class RHS : public Function<dim>
{
public:
virtual void value_list(const std::vector<Point<dim>> &points,
std::vector<double> & values,
const unsigned int /*component*/ = 0) const override
{
(void)points;
Assert(values.size() == points.size(),
ExcDimensionMismatch(values.size(), points.size()));
std::fill(values.begin(), values.end(), 0.);
}
};
template <int dim>
class BoundaryValues : public Function<dim>
{
public:
virtual void value_list(const std::vector<Point<dim>> &points,
std::vector<double> & values,
const unsigned int /*component*/ = 0) const override
{
Assert(values.size() == points.size(),
ExcDimensionMismatch(values.size(), points.size()));
for (unsigned int i = 0; i < values.size(); ++i)
{
if (points[i](0) < 0.5)
values[i] = 1.;
else
values[i] = 0.;
}
}
};
template <int dim>
class Beta
{
public:
//流场选择为逆时针方向的四分之一圆,原点为域的右半部分的中点,数值为正 $x$ ,而在域的左边部分,流速只是向左走,与从右边进来的流速一致。在圆形部分,流速的大小与离原点的距离成正比。这与 step-12 不同,在该定义中,到处都是1。新定义导致 $\beta$ 沿单元的每个给定面的线性变化。另一方面, $u(x,y)$ 的解决方案与之前完全相同。
void value_list(const std::vector<Point<dim>> &points,
std::vector<Point<dim>> & values) const
{
Assert(values.size() == points.size(),
ExcDimensionMismatch(values.size(), points.size()));
for (unsigned int i = 0; i < points.size(); ++i)
{
if (points[i](0) > 0)
{
values[i](0) = -points[i](1);
values[i](1) = points[i](0);
}
else
{
values[i] = Point<dim>();
values[i](0) = -points[i](1);
}
}
}
};
// @sect3{Class: DGTransportEquation}
// 这个类的声明完全不受我们目前的变化影响。
template <int dim>
class DGTransportEquation
{
public:
DGTransportEquation();
void assemble_cell_term(const FEValues<dim> &fe_v,
FullMatrix<double> & ui_vi_matrix,
Vector<double> & cell_vector) const;
void assemble_boundary_term(const FEFaceValues<dim> &fe_v,
FullMatrix<double> & ui_vi_matrix,
Vector<double> & cell_vector) const;
void assemble_face_term(const FEFaceValuesBase<dim> &fe_v,
const FEFaceValuesBase<dim> &fe_v_neighbor,
FullMatrix<double> & ui_vi_matrix,
FullMatrix<double> & ue_vi_matrix,
FullMatrix<double> & ui_ve_matrix,
FullMatrix<double> & ue_ve_matrix) const;
private:
const Beta<dim> beta_function;
const RHS<dim> rhs_function;
const BoundaryValues<dim> boundary_function;
};
// 同样地,该类的构造函数以及组装对应于单元格内部和边界面的术语的函数与之前没有变化。装配单元间面术语的函数也没有改变,因为它所做的只是对两个FEFaceValuesBase类型的对象进行操作(它是FEFaceValues和FESubfaceValues的基类)。这些对象从何而来,即它们是如何被初始化的,对这个函数来说并不重要:它只是假设这两个对象所代表的面或子面上的正交点与物理空间中的相同点相对应。
template <int dim>
DGTransportEquation<dim>::DGTransportEquation()
: beta_function()
, rhs_function()
, boundary_function()
{}
template <int dim>
void DGTransportEquation<dim>::assemble_cell_term(
const FEValues<dim> &fe_v,
FullMatrix<double> & ui_vi_matrix,
Vector<double> & cell_vector) const
{
const std::vector<double> &JxW = fe_v.get_JxW_values();
std::vector<Point<dim>> beta(fe_v.n_quadrature_points);
std::vector<double> rhs(fe_v.n_quadrature_points);
beta_function.value_list(fe_v.get_quadrature_points(), beta);
rhs_function.value_list(fe_v.get_quadrature_points(), rhs);
for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point)
for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i)
{
for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j)
ui_vi_matrix(i, j) -= beta[point] * fe_v.shape_grad(i, point) *
fe_v.shape_value(j, point) * JxW[point];
cell_vector(i) +=
rhs[point] * fe_v.shape_value(i, point) * JxW[point];
}
}
template <int dim>
void DGTransportEquation<dim>::assemble_boundary_term(
const FEFaceValues<dim> &fe_v,
FullMatrix<double> & ui_vi_matrix,
Vector<double> & cell_vector) const
{
const std::vector<double> & JxW = fe_v.get_JxW_values();
const std::vector<Tensor<1, dim>> &normals = fe_v.get_normal_vectors();
std::vector<Point<dim>> beta(fe_v.n_quadrature_points);
std::vector<double> g(fe_v.n_quadrature_points);
beta_function.value_list(fe_v.get_quadrature_points(), beta);
boundary_function.value_list(fe_v.get_quadrature_points(), g);
for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point)
{
const double beta_n = beta[point] * normals[point];
if (beta_n > 0)
for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i)
for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j)
ui_vi_matrix(i, j) += beta_n * fe_v.shape_value(j, point) *
fe_v.shape_value(i, point) * JxW[point];
else
for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i)
cell_vector(i) -=
beta_n * g[point] * fe_v.shape_value(i, point) * JxW[point];
}
}
template <int dim>
void DGTransportEquation<dim>::assemble_face_term(
const FEFaceValuesBase<dim> &fe_v,
const FEFaceValuesBase<dim> &fe_v_neighbor,
FullMatrix<double> & ui_vi_matrix,
FullMatrix<double> & ue_vi_matrix,
FullMatrix<double> & ui_ve_matrix,
FullMatrix<double> & ue_ve_matrix) const
{
const std::vector<double> & JxW = fe_v.get_JxW_values();
const std::vector<Tensor<1, dim>> &normals = fe_v.get_normal_vectors();
std::vector<Point<dim>> beta(fe_v.n_quadrature_points);
beta_function.value_list(fe_v.get_quadrature_points(), beta);
for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point)
{
const double beta_n = beta[point] * normals[point];
if (beta_n > 0)
{
for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i)
for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j)
ui_vi_matrix(i, j) += beta_n * fe_v.shape_value(j, point) *
fe_v.shape_value(i, point) * JxW[point];
for (unsigned int k = 0; k < fe_v_neighbor.dofs_per_cell; ++k)
for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j)
ui_ve_matrix(k, j) -= beta_n * fe_v.shape_value(j, point) *
fe_v_neighbor.shape_value(k, point) *
JxW[point];
}
else
{
for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i)
for (unsigned int l = 0; l < fe_v_neighbor.dofs_per_cell; ++l)
ue_vi_matrix(i, l) += beta_n *
fe_v_neighbor.shape_value(l, point) *
fe_v.shape_value(i, point) * JxW[point];
for (unsigned int k = 0; k < fe_v_neighbor.dofs_per_cell; ++k)
for (unsigned int l = 0; l < fe_v_neighbor.dofs_per_cell; ++l)
ue_ve_matrix(k, l) -=
beta_n * fe_v_neighbor.shape_value(l, point) *
fe_v_neighbor.shape_value(k, point) * JxW[point];
}
}
}
// @sect3{Class: DGMethod}
// 这个声明很像 step-12 的声明。然而,我们引入了一个新的例程(set_anisotropic_flags)并修改了另一个例程(refine_grid)。
template <int dim>
class DGMethod
{
public:
DGMethod(const bool anisotropic);
void run();
private:
void setup_system();
void assemble_system();
void solve(Vector<double> &solution);
void refine_grid();
void set_anisotropic_flags();
void output_results(const unsigned int cycle) const;
Triangulation<dim> triangulation;
const MappingQ1<dim> mapping;
// 我们再次希望使用程度为1的DG元素(但这只在构造函数中指定)。如果你想使用不同程度的DG方法,请在构造函数中用新的程度替换1。
const unsigned int degree;
FE_DGQ<dim> fe;
DoFHandler<dim> dof_handler;
SparsityPattern sparsity_pattern;
SparseMatrix<double> system_matrix;
// 这是新的,在介绍中解释的各向异性跳跃指标的评估中使用的阈值。它的值在构造函数中被设置为3.0,但它可以很容易地被改变为一个大于1的不同值。
const double anisotropic_threshold_ratio;
// 这是一个指示是否使用各向异性细化的bool标志。它由构造函数设置,构造函数需要一个同名的参数。
const bool anisotropic;
const QGauss<dim> quadrature;
const QGauss<dim - 1> face_quadrature;
Vector<double> solution2;
Vector<double> right_hand_side;
const DGTransportEquation<dim> dg;
};
template <int dim>
DGMethod<dim>::DGMethod(const bool anisotropic)
: mapping()
,
// 对于不同程度的DG方法,在这里进行修改。
degree(1)
, fe(degree)
, dof_handler(triangulation)
, anisotropic_threshold_ratio(3.)
, anisotropic(anisotropic)
,
// 由于β是一个线性函数,我们可以选择正交的度数,对于这个度数,所得的积分是正确的。因此,我们选择使用 <code>degree+1</code> 高斯点,这使我们能够准确地积分度数为 <code>2*degree+1</code> 的多项式,足以满足我们在本程序中要进行的所有积分。
quadrature(degree + 1)
, face_quadrature(degree + 1)
, dg()
{}
template <int dim>
void DGMethod<dim>::setup_system()
{
dof_handler.distribute_dofs(fe);
sparsity_pattern.reinit(dof_handler.n_dofs(),
dof_handler.n_dofs(),
(GeometryInfo<dim>::faces_per_cell *
GeometryInfo<dim>::max_children_per_face +
1) *
fe.n_dofs_per_cell());
DoFTools::make_flux_sparsity_pattern(dof_handler, sparsity_pattern);
sparsity_pattern.compress();
system_matrix.reinit(sparsity_pattern);
solution2.reinit(dof_handler.n_dofs());
right_hand_side.reinit(dof_handler.n_dofs());
}
// @sect4{Function: assemble_system}
// 我们继续使用 <code>assemble_system</code> 函数来实现DG离散化。这个函数与 step-12 中的 <code>assemble_system</code> 函数的作用相同(但没有MeshWorker)。 一个单元的邻居关系所考虑的四种情况与各向同性的情况相同,即a)单元在边界上,b)有更细的邻居单元,c)邻居既不粗也不细,d)邻居更粗。 然而,我们决定哪种情况的方式是按照介绍中描述的方式进行修改的。
template <int dim>
void DGMethod<dim>::assemble_system()
{
const unsigned int dofs_per_cell = dof_handler.get_fe().n_dofs_per_cell();
std::vector<types::global_dof_index> dofs(dofs_per_cell);
std::vector<types::global_dof_index> dofs_neighbor(dofs_per_cell);
const UpdateFlags update_flags = update_values | update_gradients |
update_quadrature_points |
update_JxW_values;
const UpdateFlags face_update_flags =
update_values | update_quadrature_points | update_JxW_values |
update_normal_vectors;
const UpdateFlags neighbor_face_update_flags = update_values;
FEValues<dim> fe_v(mapping, fe, quadrature, update_flags);
FEFaceValues<dim> fe_v_face(mapping,
fe,
face_quadrature,
face_update_flags);
FESubfaceValues<dim> fe_v_subface(mapping,
fe,
face_quadrature,
face_update_flags);
FEFaceValues<dim> fe_v_face_neighbor(mapping,
fe,
face_quadrature,
neighbor_face_update_flags);
FullMatrix<double> ui_vi_matrix(dofs_per_cell, dofs_per_cell);
FullMatrix<double> ue_vi_matrix(dofs_per_cell, dofs_per_cell);
FullMatrix<double> ui_ve_matrix(dofs_per_cell, dofs_per_cell);
FullMatrix<double> ue_ve_matrix(dofs_per_cell, dofs_per_cell);
Vector<double> cell_vector(dofs_per_cell);
for (const auto &cell : dof_handler.active_cell_iterators())
{
ui_vi_matrix = 0;
cell_vector = 0;
fe_v.reinit(cell);
dg.assemble_cell_term(fe_v, ui_vi_matrix, cell_vector);
cell->get_dof_indices(dofs);
for (const auto face_no : cell->face_indices())
{
const auto face = cell->face(face_no);
// 情况(a)。该面在边界上。
if (face->at_boundary())
{
fe_v_face.reinit(cell, face_no);
dg.assemble_boundary_term(fe_v_face, ui_vi_matrix, cell_vector);
}
else
{
Assert(cell->neighbor(face_no).state() == IteratorState::valid,
ExcInternalError());
const auto neighbor = cell->neighbor(face_no);
// 情况(b)。这是一个内部面,邻居是精炼的(我们可以通过询问当前单元格的面是否有孩子来测试)。在这种情况下,我们需要对 "子面 "进行整合,即当前单元格的面的子女。 (有一个稍微令人困惑的角落案例。如果我们是在1d中--诚然,当前的程序和它对各向异性细化的演示并不特别相关--那么单元间的面总是相同的:它们只是顶点。换句话说,在1d中,我们不希望对不同层次的单元之间的面进行不同的处理。我们在这里检查的条件`face->has_children()`确保了这一点:在1d中,这个函数总是返回`false`,因此在1d中我们不会进入这个`if`分支。但我们将不得不在下面的情况(c)中回到这个角落。
if (face->has_children())
{
// 我们需要知道,哪个邻居的面朝向我们单元格的方向。使用 @p neighbor_face_no 函数,我们可以得到粗邻和非粗邻的这些信息。
const unsigned int neighbor2 =
cell->neighbor_face_no(face_no);
// 现在我们对所有的子脸进行循环,也就是当前脸的子脸和可能的孙子脸。
for (unsigned int subface_no = 0;
subface_no < face->n_active_descendants();
++subface_no)
{
// 为了得到当前子面后面的单元,我们可以使用 @p neighbor_child_on_subface 函数。它照顾到了所有各向异性细化和非标准面的复杂情况。
const auto neighbor_child =
cell->neighbor_child_on_subface(face_no, subface_no);
Assert(!neighbor_child->has_children(),
ExcInternalError());
// 这个案例的其余部分没有变化。
ue_vi_matrix = 0;
ui_ve_matrix = 0;
ue_ve_matrix = 0;
fe_v_subface.reinit(cell, face_no, subface_no);
fe_v_face_neighbor.reinit(neighbor_child, neighbor2);
dg.assemble_face_term(fe_v_subface,
fe_v_face_neighbor,
ui_vi_matrix,
ue_vi_matrix,
ui_ve_matrix,
ue_ve_matrix);
neighbor_child->get_dof_indices(dofs_neighbor);
for (unsigned int i = 0; i < dofs_per_cell; ++i)
for (unsigned int j = 0; j < dofs_per_cell; ++j)
{
system_matrix.add(dofs[i],
dofs_neighbor[j],
ue_vi_matrix(i, j));
system_matrix.add(dofs_neighbor[i],
dofs[j],
ui_ve_matrix(i, j));
system_matrix.add(dofs_neighbor[i],
dofs_neighbor[j],
ue_ve_matrix(i, j));
}
}
}
else
{
//情况(c)。如果这是一个内部面,并且邻居没有进一步细化,我们就会得到这里(或者,如上所述,我们是在1d中,在这种情况下,我们对每个内部面都会得到这里)。然后我们需要决定是否要对当前面进行整合。如果邻居实际上更粗,那么我们就忽略这个面,而是在访问邻居单元并查看当前面的时候处理它(除了在1d中,如上所述,这不会发生)。
if (dim > 1 && cell->neighbor_is_coarser(face_no))
continue;
// 另一方面,如果邻居是更精细的,那么我们已经处理了上面(b)情况下的脸(1d除外)。所以对于2d和3d,我们只需要决定是要处理来自当前一侧的同一层次的单元格之间的面,还是来自邻接一侧的面。 我们通过引入一个平局来做到这一点。 我们只取索引较小的单元格(在当前细化级别内)。在1d中,我们取较粗的单元,或者如果它们在同一层次,则取该层次中指数较小的单元。这就导致了一个复杂的条件,希望在上面的描述中可以理解。
if (((dim > 1) && (cell->index() < neighbor->index())) ||
((dim == 1) && ((cell->level() < neighbor->level()) ||
((cell->level() == neighbor->level()) &&
(cell->index() < neighbor->index())))))
{
// 这里我们知道,邻居不是更粗的,所以我们可以使用通常的 @p neighbor_of_neighbor 函数。然而,我们也可以使用更通用的 @p neighbor_face_no 函数。
const unsigned int neighbor2 =
cell->neighbor_of_neighbor(face_no);
ue_vi_matrix = 0;
ui_ve_matrix = 0;
ue_ve_matrix = 0;
fe_v_face.reinit(cell, face_no);
fe_v_face_neighbor.reinit(neighbor, neighbor2);
dg.assemble_face_term(fe_v_face,
fe_v_face_neighbor,
ui_vi_matrix,
ue_vi_matrix,
ui_ve_matrix,
ue_ve_matrix);
neighbor->get_dof_indices(dofs_neighbor);
for (unsigned int i = 0; i < dofs_per_cell; ++i)
for (unsigned int j = 0; j < dofs_per_cell; ++j)
{
system_matrix.add(dofs[i],
dofs_neighbor[j],
ue_vi_matrix(i, j));
system_matrix.add(dofs_neighbor[i],
dofs[j],
ui_ve_matrix(i, j));
system_matrix.add(dofs_neighbor[i],
dofs_neighbor[j],
ue_ve_matrix(i, j));
}
}
// 我们不需要考虑情况(d),因为这些面在情况(b)中被 "从另一侧 "处理。
}
}
}
for (unsigned int i = 0; i < dofs_per_cell; ++i)
for (unsigned int j = 0; j < dofs_per_cell; ++j)
system_matrix.add(dofs[i], dofs[j], ui_vi_matrix(i, j));
for (unsigned int i = 0; i < dofs_per_cell; ++i)
right_hand_side(dofs[i]) += cell_vector(i);
}
}
// @sect3{Solver}
// 对于这个简单的问题,我们再次使用简单的Richardson迭代法。该求解器完全不受我们各向异性变化的影响。
template <int dim>
void DGMethod<dim>::solve(Vector<double> &solution)
{
SolverControl solver_control(1000, 1e-12, false, false);
SolverRichardson<Vector<double>> solver(solver_control);
PreconditionBlockSSOR<SparseMatrix<double>> preconditioner;
preconditioner.initialize(system_matrix, fe.n_dofs_per_cell());
solver.solve(system_matrix, solution, right_hand_side, preconditioner);
}
// @sect3{Refinement}
// 我们根据 step-12 中使用的相同的简单细化标准来细化网格,即对解的梯度的近似。
template <int dim>
void DGMethod<dim>::refine_grid()
{
Vector<float> gradient_indicator(triangulation.n_active_cells());
// 我们对梯度进行近似计算。
DerivativeApproximation::approximate_gradient(mapping,
dof_handler,
solution2,
gradient_indicator);
//并对其进行缩放,以获得一个误差指标。
for (const auto &cell : triangulation.active_cell_iterators())
gradient_indicator[cell->active_cell_index()] *=
std::pow(cell->diameter(), 1 + 1.0 * dim / 2);
// 然后我们用这个指标来标记误差指标最高的30%的单元格来进行精炼。
GridRefinement::refine_and_coarsen_fixed_number(triangulation,
gradient_indicator,
0.3,
0.1);
// 现在,细化标志被设置为那些具有大误差指标的单元。如果不做任何改变,这些单元将被等向细化。如果给这个函数的 @p anisotropic 标志被设置,我们现在调用set_anisotropic_flags()函数,该函数使用跳转指标将一些细化标志重置为各向异性细化。
if (anisotropic)
set_anisotropic_flags();
// 现在执行考虑各向异性以及各向同性的细化标志的细化。
triangulation.execute_coarsening_and_refinement();
}
// 一旦错误指标被评估,误差最大的单元被标记为细化,我们要再次循环这些被标记的单元,以决定它们是否需要各向同性的细化或各向异性的细化更为合适。这就是在介绍中解释的各向异性跳跃指标。
template <int dim>
void DGMethod<dim>::set_anisotropic_flags()
{
// 我们想在被标记的单元格的面上评估跳跃,所以我们需要一些对象来评估面上的解决方案的值。
UpdateFlags face_update_flags =
UpdateFlags(update_values | update_JxW_values);
FEFaceValues<dim> fe_v_face(mapping,
fe,
face_quadrature,
face_update_flags);
FESubfaceValues<dim> fe_v_subface(mapping,
fe,
face_quadrature,
face_update_flags);
FEFaceValues<dim> fe_v_face_neighbor(mapping,
fe,
face_quadrature,
update_values);
// 现在我们需要对所有活动单元进行循环。
for (const auto &cell : dof_handler.active_cell_iterators())
// 我们只需要考虑那些被标记为细化的单元。
if (cell->refine_flag_set())
{
Point<dim> jump;
Point<dim> area;
for (const auto face_no : cell->face_indices())
{
const auto face = cell->face(face_no);
if (!face->at_boundary())
{
Assert(cell->neighbor(face_no).state() ==
IteratorState::valid,
ExcInternalError());
const auto neighbor = cell->neighbor(face_no);
std::vector<double> u(fe_v_face.n_quadrature_points);
std::vector<double> u_neighbor(fe_v_face.n_quadrature_points);
// 在汇编例程中看到的四种不同的邻居关系的情况在这里以同样的方式重复。
if (face->has_children())
{
// 邻居被完善。 首先,我们存储信息,即邻居的哪个面指向我们当前单元的方向。这个属性将被继承给子代。
unsigned int neighbor2 = cell->neighbor_face_no(face_no);
// 现在我们对所有的子面进行循环。
for (unsigned int subface_no = 0;
subface_no < face->n_active_descendants();
++subface_no)
{
//得到一个迭代器,指向当前子面后面的单元格...
const auto neighbor_child =
cell->neighbor_child_on_subface(face_no,
subface_no);
Assert(!neighbor_child->has_children(),
ExcInternalError());
// ...并重新启动各自的FEFaceValues和FESSubFaceValues对象。
fe_v_subface.reinit(cell, face_no, subface_no);
fe_v_face_neighbor.reinit(neighbor_child, neighbor2);
// 我们获得了函数值
fe_v_subface.get_function_values(solution2, u);
fe_v_face_neighbor.get_function_values(solution2,
u_neighbor);
//以及正交权重,乘以雅各布行列式。
const std::vector<double> &JxW =
fe_v_subface.get_JxW_values();
// 现在我们在所有的正交点上循环。
for (unsigned int x = 0;
x < fe_v_subface.n_quadrature_points;
++x)
{
//并整合解决方案的跳跃的绝对值,即分别从当前单元和邻近单元看到的函数值的绝对值。我们知道,前两个面与单元格上的第一个坐标方向正交,后两个面与第二个坐标方向正交,以此类推,所以我们将这些值累积成具有 <code>dim</code> 成分的向量。
jump[face_no / 2] +=
std::abs(u[x] - u_neighbor[x]) * JxW[x];
// 我们还将缩放后的权重相加,以获得脸部的量度。
area[face_no / 2] += JxW[x];
}
}
}
else
{
if (!cell->neighbor_is_coarser(face_no))
{
// 我们的当前单元和邻居在所考虑的面有相同的细化。除此以外,我们的做法与上述情况下的一个子单元的做法基本相同。
unsigned int neighbor2 =
cell->neighbor_of_neighbor(face_no);
fe_v_face.reinit(cell, face_no);
fe_v_face_neighbor.reinit(neighbor, neighbor2);
fe_v_face.get_function_values(solution2, u);
fe_v_face_neighbor.get_function_values(solution2,
u_neighbor);
const std::vector<double> &JxW =
fe_v_face.get_JxW_values();
for (unsigned int x = 0;
x < fe_v_face.n_quadrature_points;
++x)
{
jump[face_no / 2] +=
std::abs(u[x] - u_neighbor[x]) * JxW[x];
area[face_no / 2] += JxW[x];
}
}
else // i.e. neighbor is coarser than cell
{
// 现在邻居实际上更粗了。这种情况是新的,因为它没有出现在汇编程序中。在这里,我们必须考虑它,但这并不太复杂。我们只需使用 @p neighbor_of_coarser_neighbor 函数,它再次自行处理各向异性的细化和非标准面的方向。
std::pair<unsigned int, unsigned int>
neighbor_face_subface =
cell->neighbor_of_coarser_neighbor(face_no);
Assert(neighbor_face_subface.first < cell->n_faces(),
ExcInternalError());
Assert(neighbor_face_subface.second <
neighbor->face(neighbor_face_subface.first)
->n_active_descendants(),
ExcInternalError());
Assert(neighbor->neighbor_child_on_subface(
neighbor_face_subface.first,
neighbor_face_subface.second) == cell,
ExcInternalError());
fe_v_face.reinit(cell, face_no);
fe_v_subface.reinit(neighbor,
neighbor_face_subface.first,
neighbor_face_subface.second);
fe_v_face.get_function_values(solution2, u);
fe_v_subface.get_function_values(solution2,
u_neighbor);
const std::vector<double> &JxW =
fe_v_face.get_JxW_values();
for (unsigned int x = 0;
x < fe_v_face.n_quadrature_points;
++x)
{
jump[face_no / 2] +=
std::abs(u[x] - u_neighbor[x]) * JxW[x];
area[face_no / 2] += JxW[x];
}
}
}
}
}
// 现在我们分析一下平均跳动的大小,我们用跳动除以各面的度量得到。
std::array<double, dim> average_jumps;
double sum_of_average_jumps = 0.;
for (unsigned int i = 0; i < dim; ++i)
{
average_jumps[i] = jump(i) / area(i);
sum_of_average_jumps += average_jumps[i];
}
// 现在我们在单元格的 <code>dim</code> 坐标方向上进行循环,并比较与该方向正交的面的平均跳跃和与其余方向正交的面的平均跳跃。如果前者比后者大一个给定的系数,我们只沿帽轴进行细化。否则,我们不改变细化标志,导致各向同性的细化。
for (unsigned int i = 0; i < dim; ++i)
if (average_jumps[i] > anisotropic_threshold_ratio *
(sum_of_average_jumps - average_jumps[i]))
cell->set_refine_flag(RefinementCase<dim>::cut_axis(i));
}
}
// @sect3{The Rest}
// 程序的其余部分非常遵循之前教程程序的方案。我们以VTU格式输出网格(就像我们在 step-1 中所做的那样,例如),并以VTU格式输出可视化,我们几乎总是这样做。
template <int dim>
void DGMethod<dim>::output_results(const unsigned int cycle) const
{
std::string refine_type;
if (anisotropic)
refine_type = ".aniso";
else
refine_type = ".iso";
{
const std::string filename =
"grid-" + std::to_string(cycle) + refine_type + ".svg";
std::cout << " Writing grid to <" << filename << ">..." << std::endl;
std::ofstream svg_output(filename);
GridOut grid_out;
grid_out.write_svg(triangulation, svg_output);
}
{
const std::string filename =
"sol-" + std::to_string(cycle) + refine_type + ".vtu";
std::cout << " Writing solution to <" << filename << ">..."
<< std::endl;
std::ofstream gnuplot_output(filename);
DataOut<dim> data_out;
data_out.attach_dof_handler(dof_handler);
data_out.add_data_vector(solution2, "u");
data_out.build_patches(degree);
data_out.write_vtu(gnuplot_output);
}
}
template <int dim>
void DGMethod<dim>::run()
{
for (unsigned int cycle = 0; cycle < 6; ++cycle)
{
std::cout << "Cycle " << cycle << ':' << std::endl;
if (cycle == 0)
{
// 创建矩形域。
Point<dim> p1, p2;
p1(0) = 0;
p1(0) = -1;
for (unsigned int i = 0; i < dim; ++i)
p2(i) = 1.;
// 调整不同方向的单元数,以获得原始网格的完全各向同性的单元。
std::vector<unsigned int> repetitions(dim, 1);
repetitions[0] = 2;
GridGenerator::subdivided_hyper_rectangle(triangulation,
repetitions,
p1,
p2);
triangulation.refine_global(5 - dim);
}
else
refine_grid();
std::cout << " Number of active cells: "
<< triangulation.n_active_cells() << std::endl;
setup_system();
std::cout << " Number of degrees of freedom: " << dof_handler.n_dofs()
<< std::endl;
Timer assemble_timer;
assemble_system();
std::cout << " Time of assemble_system: " << assemble_timer.cpu_time()
<< std::endl;
solve(solution2);
output_results(cycle);
std::cout << std::endl;
}
}
} // namespace Step30
int main()
{
try
{
using namespace Step30;
// 如果你想以3D方式运行程序,只需将下面一行改为 <code>const unsigned int dim = 3;</code> 。
const unsigned int dim = 2;
{
// 首先,我们用各向同性的细化方法进行一次运行。
std::cout << "Performing a " << dim
<< "D run with isotropic refinement..." << std::endl
<< "------------------------------------------------"
<< std::endl;
DGMethod<dim> dgmethod_iso(false);
dgmethod_iso.run();
}
{
// 现在我们进行第二次运行,这次是各向异性的细化。
std::cout << std::endl
<< "Performing a " << dim
<< "D run with anisotropic refinement..." << std::endl
<< "--------------------------------------------------"
<< std::endl;
DGMethod<dim> dgmethod_aniso(true);
dgmethod_aniso.run();
}
}
catch (std::exception &exc)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
};
return 0;
}
| 36.005187 | 311 | 0.503299 | [
"vector"
] |
7135447bee2ecfb30ed86660de318b5b53582b9a | 2,986 | cpp | C++ | gecode/clock_triplets.cpp | Wikunia/hakank | 030bc928d2efe8dcbc5118bda3f8ae9575d0fd13 | [
"MIT"
] | 279 | 2015-01-10T09:55:35.000Z | 2022-03-28T02:34:03.000Z | gecode/clock_triplets.cpp | Wikunia/hakank | 030bc928d2efe8dcbc5118bda3f8ae9575d0fd13 | [
"MIT"
] | 10 | 2017-10-05T15:48:50.000Z | 2021-09-20T12:06:52.000Z | gecode/clock_triplets.cpp | Wikunia/hakank | 030bc928d2efe8dcbc5118bda3f8ae9575d0fd13 | [
"MIT"
] | 83 | 2015-01-20T03:44:00.000Z | 2022-03-13T23:53:06.000Z | /*
Clock triplet puzzle in Gecode.
Problem formulation
http://www.f1compiler.com/samples/Dean%20Clark%27s%20Problem.f1.html
"""
Dean Clark's Problem (Clock Triplets Problem)
The problem was originally posed by Dean Clark and then presented
to a larger audience by Martin Gardner.
The problem was discussed in Dr. Dobbs's Journal, May 2004 in an article
by Timothy Rolfe. According to the article, in his August 1986 column for
Isaac Asimov's Science Fiction Magazine, Martin Gardner presented this problem:
Now for a curious little combinatorial puzzle involving the twelve
numbers on the face of a clock. Can you rearrange the numbers (keeping
them in a circle) so no triplet of adjacent numbers has a sum higher
than 21? This is the smallest value that the highest sum of a triplet
can have.
"""
Compare with the following models:
* MiniZinc: http://www.hakank.org/minzinc/clock_triplets.mzn
* SICStus Prolog: http://www.hakank.org/sicstus/clock_triplets.pl
* ECLiPSe: http://www.hakank.org/eclipse/clock_triplets.ecl
This Gecode model was created by Hakan Kjellerstrand (hakank@gmail.com)
Also, see my Gecode page: http://www.hakank.org/gecode/ .
*/
#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include <gecode/set.hh>
using namespace Gecode;
using std::cout;
using std::endl;
class ClockTriplets : public Script {
protected:
static const int n = 12;
// the clock
IntVarArray x;
IntVar triplet_sum;
public:
ClockTriplets(const Options& opt)
:
x(*this, n, 1, n),
triplet_sum(*this, 0, 21)
{
// rel(*this, triplet_sum <= 21);
distinct(*this, x);
// symmetry breaking
rel(*this, x[0] == 12);
rel(*this, x[1] > x[11]);
for(int i = 2; i <= 11; i++) {
rel(*this, x[i] + x[i-1] + x[i-2] <= triplet_sum);
}
// around the corner
rel(*this, x[10] + x[11] + x[0] <= triplet_sum);
rel(*this, x[11] + x[0] + x[1] <= triplet_sum);
// branching
branch(*this, x, INT_VAR_SIZE_MIN(), INT_VAL_MIN());
}
// Print solution
virtual void
print(std::ostream& os) const {
os << x << endl;
os << " " << x[0] << endl;
os << " " << x[11] << " " << x[1] << endl;
os << " " << x[10] << " " << x[2] << endl;
os << " " << x[9] << " " << x[3] << endl;
os << " " << x[8] << " " << x[4] << endl;
os << " " << x[7] << " " << x[5] << endl;
os << " " << x[6] << endl;
os << endl;
}
// Constructor for cloning s
ClockTriplets(bool share, ClockTriplets& s) : Script(share,s) {
x.update(*this, share, s.x);
}
// Copy during cloning
virtual Space*
copy(bool share) {
return new ClockTriplets(share,*this);
}
};
int
main(int argc, char* argv[]) {
Options opt("ClockTriplets");
opt.solutions(0);
opt.parse(argc,argv);
Script::run<ClockTriplets,DFS,Options>(opt);
return 0;
}
| 24.276423 | 81 | 0.608506 | [
"model"
] |
7148f1968f1fe9d3144fd5338e09942e0a68615c | 8,767 | cpp | C++ | tests/unit/test_ecdsa.cpp | yiyang-tian/openthread | 885e2043c430b55d3501502e57323dfb7fadae03 | [
"BSD-3-Clause"
] | 2 | 2016-09-10T04:10:24.000Z | 2017-01-04T21:34:14.000Z | tests/unit/test_ecdsa.cpp | yiyang-tian/openthread | 885e2043c430b55d3501502e57323dfb7fadae03 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/test_ecdsa.cpp | yiyang-tian/openthread | 885e2043c430b55d3501502e57323dfb7fadae03 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <openthread/config.h>
#include "test_platform.h"
#include "test_util.hpp"
#include "common/debug.hpp"
#include "common/random.hpp"
#include "crypto/ecdsa.hpp"
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/ecdsa.h>
#include <mbedtls/pk.h>
#if OPENTHREAD_CONFIG_ECDSA_ENABLE
namespace ot {
namespace Crypto {
void TestEcdsaVector(void)
{
// This case is derived from the test vector from RFC 6979 - section A.2.5 (for NIST P-256 and SHA-256 hash).
const uint8_t kKeyPairInfo[] = {
0x30, 0x78, 0x02, 0x01, 0x01, 0x04, 0x21, 0x00, 0xC9, 0xAF, 0xA9, 0xD8, 0x45, 0xBA, 0x75, 0x16, 0x6B, 0x5C,
0x21, 0x57, 0x67, 0xB1, 0xD6, 0x93, 0x4E, 0x50, 0xC3, 0xDB, 0x36, 0xE8, 0x9B, 0x12, 0x7B, 0x8A, 0x62, 0x2B,
0x12, 0x0F, 0x67, 0x21, 0xA0, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0xA1, 0x44,
0x03, 0x42, 0x00, 0x04, 0x60, 0xFE, 0xD4, 0xBA, 0x25, 0x5A, 0x9D, 0x31, 0xC9, 0x61, 0xEB, 0x74, 0xC6, 0x35,
0x6D, 0x68, 0xC0, 0x49, 0xB8, 0x92, 0x3B, 0x61, 0xFA, 0x6C, 0xE6, 0x69, 0x62, 0x2E, 0x60, 0xF2, 0x9F, 0xB6,
0x79, 0x03, 0xFE, 0x10, 0x08, 0xB8, 0xBC, 0x99, 0xA4, 0x1A, 0xE9, 0xE9, 0x56, 0x28, 0xBC, 0x64, 0xF2, 0xF1,
0xB2, 0x0C, 0x2D, 0x7E, 0x9F, 0x51, 0x77, 0xA3, 0xC2, 0x94, 0xD4, 0x46, 0x22, 0x99};
const uint8_t kPublicKey[] = {
0x60, 0xFE, 0xD4, 0xBA, 0x25, 0x5A, 0x9D, 0x31, 0xC9, 0x61, 0xEB, 0x74, 0xC6, 0x35, 0x6D, 0x68,
0xC0, 0x49, 0xB8, 0x92, 0x3B, 0x61, 0xFA, 0x6C, 0xE6, 0x69, 0x62, 0x2E, 0x60, 0xF2, 0x9F, 0xB6,
0x79, 0x03, 0xFE, 0x10, 0x08, 0xB8, 0xBC, 0x99, 0xA4, 0x1A, 0xE9, 0xE9, 0x56, 0x28, 0xBC, 0x64,
0xF2, 0xF1, 0xB2, 0x0C, 0x2D, 0x7E, 0x9F, 0x51, 0x77, 0xA3, 0xC2, 0x94, 0xD4, 0x46, 0x22, 0x99,
};
const uint8_t kMessage[] = {'s', 'a', 'm', 'p', 'l', 'e'};
const uint8_t kExpectedSignature[] = {
0xEF, 0xD4, 0x8B, 0x2A, 0xAC, 0xB6, 0xA8, 0xFD, 0x11, 0x40, 0xDD, 0x9C, 0xD4, 0x5E, 0x81, 0xD6,
0x9D, 0x2C, 0x87, 0x7B, 0x56, 0xAA, 0xF9, 0x91, 0xC3, 0x4D, 0x0E, 0xA8, 0x4E, 0xAF, 0x37, 0x16,
0xF7, 0xCB, 0x1C, 0x94, 0x2D, 0x65, 0x7C, 0x41, 0xD4, 0x36, 0xC7, 0xA1, 0xB6, 0xE2, 0x9F, 0x65,
0xF3, 0xE9, 0x00, 0xDB, 0xB9, 0xAF, 0xF4, 0x06, 0x4D, 0xC4, 0xAB, 0x2F, 0x84, 0x3A, 0xCD, 0xA8,
};
Instance *instance = testInitInstance();
Ecdsa::P256::KeyPair keyPair;
Ecdsa::P256::PublicKey publicKey;
Ecdsa::P256::Signature signature;
Sha256 sha256;
Sha256::Hash hash;
VerifyOrQuit(instance != nullptr, "Null OpenThread instance");
printf("\n===========================================================================\n");
printf("Test ECDA with test vector from RFC 6979 (A.2.5)\n");
printf("\nLoading key-pair ----------------------------------------------------------\n");
memcpy(keyPair.GetDerBytes(), kKeyPairInfo, sizeof(kKeyPairInfo));
keyPair.SetDerLength(sizeof(kKeyPairInfo));
DumpBuffer("KeyPair", keyPair.GetDerBytes(), keyPair.GetDerLength());
SuccessOrQuit(keyPair.GetPublicKey(publicKey), "KeyPair::GetPublicKey() failed");
DumpBuffer("PublicKey", publicKey.GetBytes(), Ecdsa::P256::PublicKey::kSize);
VerifyOrQuit(sizeof(kPublicKey) == Ecdsa::P256::PublicKey::kSize, "Example public key is invalid");
VerifyOrQuit(memcmp(publicKey.GetBytes(), kPublicKey, sizeof(kPublicKey)) == 0,
"KeyPair::GetPublicKey() did not return the expected key");
printf("\nHash the message ----------------------------------------------------------\n");
sha256.Start();
sha256.Update(kMessage);
sha256.Finish(hash);
DumpBuffer("Hash", hash.GetBytes(), sizeof(hash));
printf("\nSign the message ----------------------------------------------------------\n");
SuccessOrQuit(keyPair.Sign(hash, signature), "KeyPair::Sign() failed");
DumpBuffer("Signature", signature.GetBytes(), sizeof(signature));
printf("\nCheck signature against expected sequence----------------------------------\n");
DumpBuffer("Expected signature", kExpectedSignature, sizeof(kExpectedSignature));
VerifyOrQuit(sizeof(kExpectedSignature) == sizeof(signature), "Signature length does not match expected size");
VerifyOrQuit(memcmp(signature.GetBytes(), kExpectedSignature, sizeof(kExpectedSignature)) == 0,
"Signature does not match expected value");
printf("Signature matches expected sequence.\n");
printf("\nVerify the signature ------------------------------------------------------\n");
SuccessOrQuit(publicKey.Verify(hash, signature), "PublicKey::Verify() failed");
printf("\nSignature was verified successfully.\n\n");
testFreeInstance(instance);
}
void TestEdsaKeyGenerationSignAndVerify(void)
{
Instance *instance = testInitInstance();
const char *kMessage = "You are not a drop in the ocean. You are the entire ocean in a drop.";
Ecdsa::P256::KeyPair keyPair;
Ecdsa::P256::PublicKey publicKey;
Ecdsa::P256::Signature signature;
Sha256 sha256;
Sha256::Hash hash;
VerifyOrQuit(instance != nullptr, "Null OpenThread instance");
printf("\n===========================================================================\n");
printf("Test ECDA key generation, signing and verification\n");
printf("\nGenerating key-pair -------------------------------------------------------\n");
SuccessOrQuit(keyPair.Generate(), "KeyPair::Generate() failed");
DumpBuffer("KeyPair", keyPair.GetDerBytes(), keyPair.GetDerLength());
SuccessOrQuit(keyPair.GetPublicKey(publicKey), "KeyPair::GetPublicKey() failed");
DumpBuffer("PublicKey", publicKey.GetBytes(), Ecdsa::P256::PublicKey::kSize);
printf("\nHash the message ----------------------------------------------------------\n");
sha256.Start();
sha256.Update(kMessage, sizeof(kMessage) - 1);
sha256.Finish(hash);
DumpBuffer("Hash", hash.GetBytes(), sizeof(hash));
printf("\nSign the message ----------------------------------------------------------\n");
SuccessOrQuit(keyPair.Sign(hash, signature), "KeyPair::Sign() failed");
DumpBuffer("Signature", signature.GetBytes(), sizeof(signature));
printf("\nVerify the signature ------------------------------------------------------\n");
SuccessOrQuit(publicKey.Verify(hash, signature), "PublicKey::Verify() failed");
printf("\nSignature was verified successfully.");
sha256.Start();
sha256.Update(kMessage, sizeof(kMessage)); // include null char
sha256.Finish(hash);
VerifyOrQuit(publicKey.Verify(hash, signature) != kErrorNone, "PublicKey::Verify() passed for invalid signature");
printf("\nSignature verification correctly failed with incorrect hash/signature.\n\n");
testFreeInstance(instance);
}
} // namespace Crypto
} // namespace ot
#endif // OPENTHREAD_CONFIG_ECDSA_ENABLE
int main(void)
{
#if OPENTHREAD_CONFIG_ECDSA_ENABLE
ot::Crypto::TestEcdsaVector();
ot::Crypto::TestEdsaKeyGenerationSignAndVerify();
printf("All tests passed\n");
#else
printf("ECDSA feature is not enabled\n");
#endif
return 0;
}
| 44.958974 | 118 | 0.638531 | [
"vector"
] |
714948159ce867ec6cbd18bd95cd4fe8dc6e8ffb | 15,918 | cpp | C++ | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/test/unit/src/tools/misc/TestMisc.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/test/unit/src/tools/misc/TestMisc.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/test/unit/src/tools/misc/TestMisc.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | /*****************************************************************************
* GATB : Genome Assembly Tool Box
* Copyright (C) 2014 R.Chikhi, G.Rizk, E.Drezen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include <CppunitCommon.hpp>
#include <gatb/system/impl/System.hpp>
#include <gatb/system/impl/TimeCommon.hpp>
#include <gatb/tools/misc/api/Range.hpp>
#include <gatb/tools/misc/api/Vector.hpp>
#include <gatb/tools/misc/api/Macros.hpp>
#include <gatb/tools/misc/impl/OptionsParser.hpp>
#include <gatb/tools/misc/impl/Property.hpp>
#include <gatb/tools/misc/impl/StringLine.hpp>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <memory>
using namespace std;
using namespace gatb::core::system;
using namespace gatb::core::system::impl;
using namespace gatb::core::tools::dp;
using namespace gatb::core::tools::misc;
using namespace gatb::core::tools::misc::impl;
#define ABS(a) ((a)<0 ? -(a) : (a))
/********************************************************************************/
namespace gatb { namespace tests {
/********************************************************************************/
/** \brief Test class for miscellaneous operations
*/
class TestMisc : public Test
{
/********************************************************************************/
CPPUNIT_TEST_SUITE_GATB (TestMisc);
CPPUNIT_TEST_GATB (range_checkIterator1);
CPPUNIT_TEST_GATB (range_checkIterator2);
// NEED A GOOD TIMER ACCURACY... CPPUNIT_TEST_GATB (range_checkPerformance);
// DEACTIVATED BECAUSE OF MACOS (TO BE INVESTIGATED...) CPPUNIT_TEST_GATB (vector_check1);
CPPUNIT_TEST_GATB (vector_check2);
CPPUNIT_TEST_GATB (vector_check3);
CPPUNIT_TEST_GATB (parser_check1);
CPPUNIT_TEST_GATB (parser_check2);
CPPUNIT_TEST_GATB (stringline_check1);
CPPUNIT_TEST_SUITE_GATB_END();
public:
/********************************************************************************/
void setUp () { srand (time(NULL)); }
void tearDown () {}
/********************************************************************************/
/** \brief test of Range class and its associated iterator.
*
* We create an iterator for an integer range and check that each iterated item is ok.
*/
void range_checkIterator1 ()
{
/** We create a range. */
Range<size_t> range (1, 1000);
/** We create an iterator from the range. */
Range<size_t>::Iterator it (range);
size_t check = range.getBegin();
/** We iterate each item of the range. */
for (it.first(); !it.isDone(); it.next())
{
/** We check that the current iterated item is ok. */
CPPUNIT_ASSERT (it.item() == check++);
}
}
/********************************************************************************/
/** \brief test of Range associated iterator.
*
* We create an iterator for an integer range and check that each iterated item is ok.
*/
void range_checkIterator2 ()
{
size_t from=1, to=100, check=from;
/** We create an iterator from the range. */
Range<size_t>::Iterator it (from, to);
/** We iterate each item of the range. */
for (it.first(); !it.isDone(); it.next())
{
/** We check that the current iterated item is ok. */
CPPUNIT_ASSERT (it.item() == check++);
}
}
/********************************************************************************/
void range_checkPerformance ()
{
typedef u_int64_t INT;
u_int64_t sum1=0, sum2=0;
INT begin=1, end=1000*1000*1000;
/** We create a range. */
Range<INT> range (begin, end);
/** We create an iterator from the range (seen as an Iterable). */
Range<INT>::Iterator it (range);
/** We need something to measure elapsed time. */
ITime& ts = System::time();
/** Note that we use 'volatile' keyword in order to avoid unwanted optimizations here. */
volatile ITime::Value t0 = ts.getTimeStamp();
for (it.first(); !it.isDone(); it.next()) { sum1 += it.item(); }
volatile ITime::Value t1 = ts.getTimeStamp();
for (INT i=begin; i<=end; i++) { sum2 += i; }
volatile ITime::Value t2 = ts.getTimeStamp();
/** We check we got the same result with both loops. */
CPPUNIT_ASSERT (sum1 > 0 && sum1 == sum2);
/** We check that performances are of same order. */
double err = 100.0 * ABS (1.0 - (double)(t1-t0) / (double)(t2-t1));
/** The 'iterator' loop should be less than 100% slower than the 'direct' loop. */
CPPUNIT_ASSERT (err < 100);
}
/********************************************************************************/
void vector_check1 ()
{
char table[] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
Vector<char> v1;
CPPUNIT_ASSERT (v1.size() == 0);
CPPUNIT_ASSERT (v1.getBuffer() == 0);
v1.set (table, ARRAY_SIZE(table));
CPPUNIT_ASSERT (v1.size() == ARRAY_SIZE(table));
for (size_t i=0; i<ARRAY_SIZE(table); i++) { CPPUNIT_ASSERT (v1[i] == table[i]); }
v1.set (0, 0);
CPPUNIT_ASSERT (v1.size() == 0);
CPPUNIT_ASSERT (v1.getBuffer() == 0);
}
/********************************************************************************/
void vector_check2 ()
{
char table[] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
/** We create a reference vector and use it locally. */
Vector<char>* ref = new Vector<char> (ARRAY_SIZE(table));
ref->use ();
/** We put some values into the vector. */
for (size_t i=0; i<ARRAY_SIZE(table); i++) { (*ref)[i] = table[i]; }
/** We create other vectors referencing the previous one. */
Vector<char> v1; v1.setRef (ref, 0, 2);
Vector<char> v2; v2.setRef (ref, 2, 2);
Vector<char> v3; v3.setRef (ref, 4, 2);
Vector<char> v4; v4.setRef (ref, 6, 2);
Vector<char> v5; v5.setRef (ref, 8, 2);
/** We release locally the referred vector. Since it is referred by the other vectors,
* it won't be deleted by the release here but when the last vector will release it. */
ref->forget ();
/** Now we check the content of the other vectors. */
CPPUNIT_ASSERT (v1.size() == 2); for (size_t i=0; i<v1.size(); i++) { CPPUNIT_ASSERT (v1[i] == table[i+0]); }
CPPUNIT_ASSERT (v2.size() == 2); for (size_t i=0; i<v2.size(); i++) { CPPUNIT_ASSERT (v2[i] == table[i+2]); }
CPPUNIT_ASSERT (v3.size() == 2); for (size_t i=0; i<v3.size(); i++) { CPPUNIT_ASSERT (v3[i] == table[i+4]); }
CPPUNIT_ASSERT (v4.size() == 2); for (size_t i=0; i<v4.size(); i++) { CPPUNIT_ASSERT (v4[i] == table[i+6]); }
CPPUNIT_ASSERT (v5.size() == 2); for (size_t i=0; i<v5.size(); i++) { CPPUNIT_ASSERT (v5[i] == table[i+8]); }
}
/********************************************************************************/
/** \brief Check reference of a reference.
*
* Note: we instantiate ref1 and ref2 but don't take a local reference (with 'use')
* => they are referred by ref3 (directly and indirectly) and so should be deleted when needed.
*/
void vector_check3 ()
{
char table[] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
/** We create a reference vector. */
Vector<char>* ref1 = new Vector<char> (ARRAY_SIZE(table));
for (size_t i=0; i<ARRAY_SIZE(table); i++) { (*ref1)[i] = table[i]; }
/** We create a reference vector. */
Vector<char>* ref2 = new Vector<char> ();
ref2->setRef (ref1, 3, 5); // should hold 5, 8, 13, 21, 34
CPPUNIT_ASSERT (ref2->size() == 5);
/** We create a reference vector and use it locally. */
Vector<char> ref3;
ref3.setRef (ref2, 1, 3); // should hold 8, 13, 21
CPPUNIT_ASSERT (ref3.size() == 3);
CPPUNIT_ASSERT (ref3[0] == 8);
CPPUNIT_ASSERT (ref3[1] == 13);
CPPUNIT_ASSERT (ref3[2] == 21);
}
/********************************************************************************/
void parser_check1_aux (IOptionsParser* parser, const string& str, bool ok, size_t nbProps, const string& check)
{
IProperties* props = 0;
try
{
props = parser->parseString (str);
/** We can't be here. */
CPPUNIT_ASSERT (ok);
}
catch (OptionFailure& e)
{
CPPUNIT_ASSERT (!ok);
}
if (ok)
{
CPPUNIT_ASSERT (props != 0);
if (props->getKeys().size() > 0)
{
stringstream ss;
XmlDumpPropertiesVisitor xml (ss, false, false);
props->accept (&xml);
CPPUNIT_ASSERT (check == ss.str());
}
CPPUNIT_ASSERT (props->getKeys().size() == nbProps);
}
}
void parser_check1 ()
{
OptionsParser* parser1 = new OptionsParser ("dsk");
parser1->push_back (new OptionOneParam ("-a", "option a", false, "1"));
OptionsParser* parser2 = new OptionsParser ("bloom");
parser2->push_back (new OptionOneParam ("-b", "option b", true));
OptionsParser* parser3 = new OptionsParser ("debloom");
parser3->push_back (new OptionOneParam ("-c", "option c", false));
OptionsParser* composite = new OptionsParser ("dbgh5");
LOCAL (composite);
composite->push_back (parser1);
composite->push_back (parser2);
composite->push_back (parser3);
parser_check1_aux (parser1, "-a 1", true, 1, "<-a>1</-a>");
parser_check1_aux (parser1, "-b 2", false, 1, "<-a>1</-a>");
parser_check1_aux (parser2, "-a 3", false, 1, "");
parser_check1_aux (parser2, "-b 4", true, 1, "<-b>4</-b>");
parser_check1_aux (parser3, "-c 5", true, 1, "<-c>5</-c>");
parser_check1_aux (composite, "-a 5 -b 6 -c 7", true, 3, "<-a>5</-a><-b>6</-b><-c>7</-c>");
parser_check1_aux (composite, "-a 8 -b 9", true, 2, "<-a>8</-a><-b>9</-b>");
parser_check1_aux (composite, "-a 10 -c 11", false, 0, "");
}
/********************************************************************************/
void parser_check2 ()
{
{
OptionsParser parser ("test1");
parser.push_back (new OptionNoParam ("-a", "option a", false));
parser.push_back (new OptionNoParam ("-b", "option b", false));
try {
parser.parseString ("-a -b");
CPPUNIT_ASSERT(parser.saw("-a"));
CPPUNIT_ASSERT(parser.saw("-b"));
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(false); }
}
{
OptionsParser parser ("test2");
parser.push_back (new OptionNoParam ("-a", "option a", false));
parser.push_back (new OptionOneParam ("-b", "option b", false));
try {
parser.parseString ("-a -b foo");
CPPUNIT_ASSERT(parser.saw("-a"));
CPPUNIT_ASSERT(parser.saw("-b"));
CPPUNIT_ASSERT(parser.getProperties()->getStr("-b") == "foo");
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(false); }
}
{
OptionsParser parser ("test3");
parser.push_back (new OptionOneParam ("-a", "option a", false));
parser.push_back (new OptionNoParam ("-b", "option b", false));
try {
parser.parseString ("-a foo -b");
CPPUNIT_ASSERT(parser.saw("-a"));
CPPUNIT_ASSERT(parser.saw("-b"));
CPPUNIT_ASSERT(parser.getProperties()->getStr("-a") == "foo");
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(false); }
}
{
OptionsParser parser ("test4");
parser.push_back (new OptionNoParam ("-a", "option a", false));
parser.push_back (new OptionOneParam ("-b", "option b", false));
parser.push_back (new OptionNoParam ("-c", "option c", false));
try {
parser.parseString ("-a -b foo -c");
CPPUNIT_ASSERT(parser.saw("-a"));
CPPUNIT_ASSERT(parser.saw("-b"));
CPPUNIT_ASSERT(parser.getProperties()->getStr("-b") == "foo");
CPPUNIT_ASSERT(parser.saw("-c"));
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(false); }
}
{
OptionsParser parser ("test5");
parser.push_back (new OptionOneParam ("-b", "option b", false));
try {
parser.parseString ("-b");
CPPUNIT_ASSERT(false);
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(true); }
}
{
OptionsParser parser ("test6");
parser.push_back (new OptionNoParam ("-b", "option b", false));
try {
parser.parseString ("");
CPPUNIT_ASSERT(true);
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(false); }
}
{
OptionsParser parser ("test7");
try {
parser.parseString ("");
CPPUNIT_ASSERT(true);
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(false); }
}
{
OptionsParser parser ("test7");
parser.push_back (new OptionNoParam ("-b", "option b", true));
try {
parser.parseString ("");
CPPUNIT_ASSERT(false);
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(true); }
}
{
OptionsParser parser ("test8");
parser.push_back (new OptionNoParam ("-a", "option a", false));
parser.push_back (new OptionOneParam ("-b", "option b", true));
try {
parser.parseString ("-a");
CPPUNIT_ASSERT(false);
}
catch (OptionFailure& e) { CPPUNIT_ASSERT(true); }
}
}
/********************************************************************************/
void stringline_check1 (void)
{
string s1 = "abcdefghijklmnopqrstuvwxyz";
string s2 = s1 + s1;
CPPUNIT_ASSERT (StringLine::format (s1).size() == StringLine::getDefaultWidth());
CPPUNIT_ASSERT (StringLine::format (s2).size() == StringLine::getDefaultWidth());
}
};
/********************************************************************************/
CPPUNIT_TEST_SUITE_REGISTRATION (TestMisc);
CPPUNIT_TEST_SUITE_REGISTRATION_GATB (TestMisc);
/********************************************************************************/
} } /* end of namespaces. */
/********************************************************************************/
| 37.990453 | 123 | 0.497361 | [
"vector"
] |
7153158981a19dcc1477775b1d054703c40e529d | 3,243 | cpp | C++ | owClient/Objects/GameObjects/WoWGameObject.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 30 | 2017-09-02T20:25:47.000Z | 2021-12-31T10:12:07.000Z | owClient/Objects/GameObjects/WoWGameObject.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | null | null | null | owClient/Objects/GameObjects/WoWGameObject.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 23 | 2018-02-04T17:18:33.000Z | 2022-03-22T09:45:36.000Z | #include "stdafx.h"
#ifdef ENABLE_WOW_CLIENT
// General
#include "WoWGameObject.h"
// Additional
#include "../../World/WorldServer.h"
CowServerGameObject::CowServerGameObject(IScene& Scene, CWorldServer& WoWWorld, CowGuid Guid)
: CowServerWorldObject(Scene, WoWWorld, Guid)
{
//m_ObjectType |= TYPEMASK_GAMEOBJECT;
m_Values.SetValuesCount(GAMEOBJECT_END);
}
CowServerGameObject::~CowServerGameObject()
{
}
void CowServerGameObject::OnValueUpdated(uint16 index)
{
if (index == OBJECT_FIELD_ENTRY)
{
CowGuid::EntryType_t objectEntryID = m_Values.GetUInt32Value(index);
if (m_GameObjectTemplate == nullptr)
{
GetWoWWorld().GetClientCache().RequestGameObjectTemplate(objectEntryID, GetWoWGUID(), std::dynamic_pointer_cast<CowServerGameObject>(shared_from_this()));
}
}
}
void CowServerGameObject::OnValuesUpdated(const UpdateMask & Mask)
{
if (Mask.GetBit(GAMEOBJECT_DISPLAYID))
{
OnDisplayIDChanged(m_Values.GetUInt32Value(GAMEOBJECT_DISPLAYID));
}
}
void CowServerGameObject::OnHiddenNodePositionChanged()
{
if (m_GameObjectModel)
{
m_GameObjectModel->SetLocalPosition(Position);
m_GameObjectModel->SetLocalRotationEuler(glm::vec3(0.0f, Orientation, 0.0f));
}
}
//
// IClientCacheGameobjectResponseListener
//
void CowServerGameObject::OnTemplate(CowGuid::EntryType_t Entry, const std::shared_ptr<SGameObjectQueryResult>& QueryResult)
{
m_GameObjectTemplate = QueryResult;
}
//
// ISceneNode
//
void CowServerGameObject::Update(const UpdateEventArgs & e)
{
__super::Update(e);
}
//
// Protected
//
std::shared_ptr<CowServerGameObject> CowServerGameObject::Create(CWorldServer& WoWWorld, IScene& Scene, CowGuid Guid)
{
std::shared_ptr<CowServerGameObject> thisObj = MakeShared(CowServerGameObject, Scene, WoWWorld, Guid);
return thisObj;
}
void CowServerGameObject::Destroy()
{
if (m_GameObjectModel)
m_GameObjectModel->MakeMeOrphan();
}
//
// Protected
//
void CowServerGameObject::OnDisplayIDChanged(uint32 DisplayID)
{
if (m_GameObjectModel != nullptr)
return;
//try
//{
m_GameObjectModel = GetWoWWorld().GetWorldClient().GetCreator()->BuildGameObjectFromDisplayInfo(GetScene().GetBaseManager().GetApplication().GetRenderDevice(), GetScene(), DisplayID);
//const DBC_CreatureDisplayInfoRecord * creatureDisplayInfo = GetBaseManager().GetManager<CDBCStorage>()->DBC_CreatureDisplayInfo()[diplayID];
//if (creatureDisplayInfo == nullptr)
// throw CException("Creature display info '%d' don't found.", diplayID);
//const DBC_CreatureModelDataRecord* creatureModelDataRecord = GetBaseManager().GetManager<CDBCStorage>()->DBC_CreatureModelData()[creatureDisplayInfo->Get_Model()];
//if (creatureModelDataRecord == nullptr)
// throw CException("Creature model data '%d' don't found.", creatureDisplayInfo->Get_Model());
//float scaleFromCreature = creatureDisplayInfo->Get_Scale();
//float scaleFromModel = creatureModelDataRecord->Get_Scale();
float scale = 1.0f;
if (m_Values.IsExists(OBJECT_FIELD_SCALE_X))
scale = m_Values.GetFloatValue(OBJECT_FIELD_SCALE_X);
m_GameObjectModel->SetScale(glm::vec3(scale));
//}
//catch (const CException& e)
//{
// Log::Error("CowServerGameObject::AfterCreate: Exception '%s'.", e.MessageCStr());
//}
}
#endif
| 25.535433 | 185 | 0.763799 | [
"model"
] |
715896391ff4a4c648b457d853727ac72da0d53c | 23,342 | cpp | C++ | src/mc/ProofAttachment.cpp | ryanberryhill/iimc | 2746410d283c53c494cc2389638bfd8c0a0b3404 | [
"BSD-3-Clause"
] | null | null | null | src/mc/ProofAttachment.cpp | ryanberryhill/iimc | 2746410d283c53c494cc2389638bfd8c0a0b3404 | [
"BSD-3-Clause"
] | null | null | null | src/mc/ProofAttachment.cpp | ryanberryhill/iimc | 2746410d283c53c494cc2389638bfd8c0a0b3404 | [
"BSD-3-Clause"
] | 2 | 2019-02-06T04:20:23.000Z | 2019-02-10T18:25:46.000Z | /********************************************************************
Copyright (c) 2010-2015, Regents of the University of Colorado
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 Colorado 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 "COI.h"
#include "CNFAttachment.h"
#include "ProofAttachment.h"
#include "SeqAttachment.h"
#include "Util.h"
#include <boost/regex.hpp>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
namespace {
struct nameCompare {
nameCompare(Expr::Manager::View *v) : v(v) {}
bool operator ()(ID const a, ID const b) const {
std::string aString = stringOf(*v, a);
std::string bString = stringOf(*v, b);
std::string aName, bName;
boost::smatch m;
if (aString[0] == '!') aString = aString.substr(1);
if (bString[0] == '!') bString = bString.substr(1);
bool aIsPred = !std::strncmp(aString.c_str(), "p_xx", 2);
bool bIsPred = !std::strncmp(bString.c_str(), "p_xx", 2);
// put the predicates at the end (they are also poorly sorted)
if (aIsPred && bIsPred){
// strip off predicate prefix and continue
aString = aString.substr(2);
bString = bString.substr(2);
}
else if (aIsPred)
return false;
else if (bIsPred)
return true;
// get name in !name<3> or name<*2*>
boost::regex getName ("(.*?)(<\\*?\\d\\*?>)");
boost::regex_search(aString, m, getName);
aName = m[1].str();
boost::regex_search(bString, m, getName);
bName = m[1].str();
if (aName != bName)
return aName < bName;
// only support single multi-dimensional Ex: reg [3:0] X [2:0];
boost::regex getBit ("<(\\d*?)>"); // find 3 in ...<3>...
boost::regex getWidth ("<\\*(\\d*?)\\*>"); // find 3 in ...<*3*>...
int bvalA = boost::regex_search(aString, m, getBit) ?
atoi(m[1].str().c_str()) : -1;
int wvalA = boost::regex_search(aString, m, getWidth) ?
atoi(m[1].str().c_str()) : -1;
int bvalB = boost::regex_search(bString, m, getBit) ?
atoi(m[1].str().c_str()) : -1;
int wvalB = boost::regex_search(bString, m, getWidth) ?
atoi(m[1].str().c_str()) : -1;
if (wvalA != wvalB)
return wvalA < wvalB;
else
return bvalA < bvalB;
}
private:
Expr::Manager::View *v;
};
}
/**
* Make string out of attachment.
*/
std::string ProofAttachment::string(bool includeDetails) const {
if (includeDetails) {
std::ostringstream ret;
ret << "PROOF (Timestamp = " << _ts << "):\n";
if (_hasConclusion)
ret << (_safe == 0 ? "Safe" : "Counterexample") << std::endl;
else
ret << "No conlusion yet" << std::endl;
return ret.str();
} else {
return "PROOF";
}
}
/**
* Print conclusion (or nothing).
*/
void ProofAttachment::printConclusion(std::ostream& os) const
{
bool printInfo = _model.options().count("print_info") > 0;
if (printInfo)
Util::printSystemInfo(os);
std::ostringstream oss;
if (_hasConclusion)
oss << _safe << std::endl;
else
oss << "2" << std::endl;
os << oss.str() << flush;
}
void ProofAttachment::restoreInitialCondition() {
ExprAttachment const * const eat = (ExprAttachment const *)
model().constAttachment(Key::EXPR);
vector<ID> initialConditions = eat->originalInitialConditions();
vector<ID> stateVars = eat->originalStateVars();
model().constRelease(eat);
unordered_set<ID> hasValue(_cex.front().state.begin(), _cex.front().state.end());
for (vector<ID>::const_iterator it = initialConditions.begin();
it != initialConditions.end(); ++it) {
if (hasValue.find(*it) == hasValue.end())
_cex.front().state.push_back(*it);
}
if (_cex.front().state.size() < stateVars.size())
if (model().verbosity() > Options::Informative)
cout << "c Warning: Uninitialized latches were dropped by optimization"
<< endl;
}
/**
* If this function is called, the model has been decoded.
* The objective is to undo the effect of optimizations subsequent to
* decoding (we assume that no optimizations took place before that)
* and produce a valid counterexample for the unoptimized, still decoded
* model. This valid counterexample must specify both input and state
* values, because some inputs of the encoded model will be derived from
* the states of the decoded one.
*/
void ProofAttachment::restoreDroppedLatches() {
//Currently only works for AIGER 1.0
Expr::Manager::View * ev = model().newView();
// Grab information about the unoptimized decoded model.
SeqAttachment const * const seat = (SeqAttachment const *)
model().constAttachment(Key::SEQ);
assert(seat); // if we reached this point, the attachment should exist
set<ID> init(seat->decodedInitialConditions.begin(),
seat->decodedInitialConditions.end());
const vector<ID> & initialConditions = seat->decodedInitialConditions;
const vector<ID> & decodedInputs = seat->decodedInputs;
const vector<ID> & latches = seat->decodedStateVars;
const vector<ID> & nsf = seat->decodedNextStateFns;
const vector<ID> & constraintFns = seat->decodedConstraintFns;
unordered_map<ID, ID> missingLatches = seat->optimized;
model().constRelease(seat);
// Build unoptimized decoded transition relation for simulation.
vector< vector<ID> > tr;
vector<ID> trans;
for (unsigned i = 0; i < latches.size(); ++i) {
trans.push_back(ev->apply(Expr::Equiv,
ev->prime(latches[i]),
nsf[i]));
}
for (vector<ID>::const_iterator cit = constraintFns.begin();
cit != constraintFns.end(); ++cit) {
trans.push_back(*cit);
}
Expr::tseitin(*ev, trans, tr);
SAT::Manager * sman = model().newSATManager();
SAT::Manager::View * sview = sman->newView(*ev);
sview->add(tr);
vector<Transition>::iterator cexIt = _cex.begin();
//Restore initial conditions of missing latches.
for(unordered_map<ID, ID>::const_iterator latchIt = missingLatches.begin();
latchIt != missingLatches.end(); ++latchIt) {
//Dropped latches must obey initial conditions
if (init.find(latchIt->first) != init.end()) {
cexIt->state.push_back(latchIt->first);
}
else if (init.find(ev->apply(Expr::Not, latchIt->first)) != init.end()) {
cexIt->state.push_back(ev->apply(Expr::Not, latchIt->first));
} else {
// Dubious: Make sure every latch is initialized!
cexIt->state.push_back(ev->apply(Expr::Not, latchIt->first));
}
}
// Make sure latches that are not missing got their initial conditions.
set<ID> cexInit(cexIt->state.begin(), cexIt->state.end());
for (vector<ID>::const_iterator it = initialConditions.begin();
it != initialConditions.end(); ++it) {
if (cexInit.find(*it) == cexInit.end())
cexIt->state.push_back(*it);
}
// Add missing inputs in negative phase.
set<ID> inputSet(cexIt->inputs.begin(), cexIt->inputs.end());
for (vector<ID>::const_iterator iit = decodedInputs.begin();
iit != decodedInputs.end(); ++iit) {
if (inputSet.find(*iit) != inputSet.end()) continue;
ID negInp = ev->apply(Expr::Not, *iit);
if (inputSet.find(negInp) == inputSet.end())
cexIt->inputs.push_back(negInp);
}
for(++cexIt; cexIt != _cex.end(); ++cexIt) {
SAT::Assignment asgn;
for(unordered_map<ID, ID>::const_iterator latchIt = missingLatches.begin();
latchIt != missingLatches.end(); ++latchIt) {
if(latchIt->second == ev->btrue()) {
cexIt->state.push_back(latchIt->first);
}
else if(latchIt->second == ev->bfalse()) {
cexIt->state.push_back(ev->apply(Expr::Not, latchIt->first));
}
else if(latchIt->second != latchIt->first) {
//Equivalent to another latch
bool complementary = ev->op(latchIt->second) == Expr::Not;
ID regularEquiv = complementary ?
ev->apply(Expr::Not, latchIt->second) : latchIt->second;
unordered_map<ID, ID>::const_iterator equivLatch =
missingLatches.find(regularEquiv);
//if it's not a missing latch
if(equivLatch == missingLatches.end()) {
//The missing latch should have the same value as the one it's
//equivalent to
set<ID> state(cexIt->state.begin(), cexIt->state.end());
if(state.find(latchIt->second) != state.end()) {
cexIt->state.push_back(latchIt->first);
}
else if (state.find(ev->apply(Expr::Not, latchIt->second)) != state.end()) {
cexIt->state.push_back(ev->apply(Expr::Not, latchIt->first));
}
else {
asgn.insert(SAT::Assignment::value_type(
ev->prime(latchIt->first), SAT::Unknown));
}
}
else {
//It is equivalent to a missing latch. We let the SAT
//solver figure out the right value.
asgn.insert(SAT::Assignment::value_type(
ev->prime(latchIt->first), SAT::Unknown));
}
}
else {
//Latch is not in COI. Need to find its value through a SAT query
asgn.insert(SAT::Assignment::value_type(
ev->prime(latchIt->first), SAT::Unknown));
}
}
// Add to the assignment the latches that are not missing, but
// were given no value in this step of the counterexample.
set<ID> latchSet(cexIt->state.begin(), cexIt->state.end());
for (vector<ID>::const_iterator latchIt = latches.begin();
latchIt != latches.end(); ++latchIt) {
if (latchSet.find(*latchIt) == latchSet.end()) {
ID negID = ev->apply(Expr::Not, *latchIt);
if (latchSet.find(negID) == latchSet.end()) {
asgn.insert(SAT::Assignment::value_type(
ev->prime(*latchIt), SAT::Unknown));
}
}
}
// Add missing inputs in negative phase.
set<ID> inputSet(cexIt->inputs.begin(), cexIt->inputs.end());
for (vector<ID>::const_iterator iit = decodedInputs.begin();
iit != decodedInputs.end(); ++iit) {
if (inputSet.find(*iit) != inputSet.end()) continue;
ID negInp = ev->apply(Expr::Not, *iit);
if (inputSet.find(negInp) == inputSet.end())
cexIt->inputs.push_back(negInp);
}
if(!asgn.empty()) {
// There is at least one latch whose value should be found.
vector<Transition>::iterator prevState = cexIt - 1;
vector<ID> assumps = prevState->state;
assumps.insert(assumps.end(), prevState->inputs.begin(),
prevState->inputs.end());
for(vector<ID>::const_iterator it = cexIt->state.begin();
it != cexIt->state.end(); ++it) {
assumps.push_back(ev->prime(*it));
}
bool sat = sview->sat(&assumps, &asgn);
assert(sat);
for(SAT::Assignment::iterator it = asgn.begin(); it != asgn.end();
++it) {
assert(it->second != SAT::Unknown);
if(it->second == SAT::True) {
cexIt->state.push_back(ev->unprime(it->first));
}
else {
cexIt->state.push_back(ev->apply(Expr::Not, ev->unprime(it->first)));
}
}
}
}
delete sview;
delete sman;
delete ev;
}
void ProofAttachment::addEquivalenceInfo() {
if(model().options().count("xmap_cex"))
return;
SeqAttachment const * const seat = (SeqAttachment const *) model().constAttachment(Key::SEQ);
if(!seat)
return;
Expr::Manager::View * ev = model().newView();
const unordered_map<ID, ID> & optLatches = seat->optimized;
for(unordered_map<ID, ID>::const_iterator it = optLatches.begin();
it != optLatches.end(); ++it) {
if(it->second == ev->btrue()) {
_proof.push_back(vector<ID>(1, it->first));
}
else if(it->second == ev->bfalse()) {
_proof.push_back(vector<ID>(1, ev->apply(Expr::Not, it->first)));
}
else if(it->second != it->first) {
//equivalent to another latch
vector<ID> clause1, clause2;
clause1.push_back(it->first);
clause1.push_back(ev->apply(Expr::Not, it->second));
_proof.push_back(clause1);
clause2.push_back(ev->apply(Expr::Not, it->first));
clause2.push_back(it->second);
_proof.push_back(clause2);
}
}
delete ev;
model().constRelease(seat);
}
void ProofAttachment::printCex(std::ostream& os) const
{
assert(_hasConclusion && _safe == 1);
Expr::Manager::View * v = _model.newView();
assert(_model.options().count("print_cex")); // delete this?
os << std::endl << "1\nCounterexample Trace:" << std::endl;
std::vector<Transition> cex(_cex);
// compute changing latches/inputs, take state intersection after sorting by ID
std::vector <ID> newState (_cex[0].state);
std::vector <ID> newInputs (_cex[0].inputs);
std::vector <ID> diffState (_cex[0].state);
std::vector <ID> diffInputs (_cex[0].inputs);
if (!_cex.empty()){
std::sort(cex[0].state.begin(), cex[0].state.end());
std::sort(cex[0].inputs.begin(), cex[0].inputs.end());
}
unsigned i;
for(i = 1; i < _cex.size(); ++i) {
std::vector<ID>::iterator endIt;
std::sort(cex[i].state.begin(), cex[i].state.end()); // by ID, for intersection
endIt = set_difference(cex[i].state.begin(), cex[i].state.end(),
cex[i-1].state.begin(), cex[i-1].state.end(), diffState.begin());
cex[i-1].state = newState;
newState = std::vector<ID>(diffState.begin(), endIt);
std::sort(cex[i].inputs.begin(), cex[i].inputs.end());
endIt = set_difference(cex[i].inputs.begin(), cex[i].inputs.end(),
cex[i-1].inputs.begin(), cex[i-1].inputs.end(), diffInputs.begin());
cex[i-1].inputs = newInputs;
newInputs = std::vector<ID>(diffInputs.begin(), endIt);
}
cex[i-1].state = newState;
cex[i-1].inputs = newInputs;
// lexographically sort states
for(unsigned i = 0; i < cex.size(); ++i) {
sort(cex[i].state.begin(), cex[i].state.end(), nameCompare(v));
sort(cex[i].inputs.begin(), cex[i].inputs.end(), nameCompare(v));
}
// traverse and print each cex state
for(unsigned i = 0; i < cex.size(); ++i) {
vector <ID> state (cex[i].state);
vector <ID> inputs (cex[i].inputs);
os << "--State " << i << ":" << endl;
if(!state.empty()) {
for(unsigned j = 0; j < state.size(); ++j) {
bool isNeg = v->op(state[j]) == Expr::Not;
ID baseId = isNeg ? v->apply(Expr::Not, state[j]) : state[j];
// indentation can be used by some editors to do text folding
os << " " << stringOf(*v, baseId) << ":" << !isNeg << endl;
}
}
else
os << " No latch change" << std::endl;
os << "--Inputs: " << std::endl;
if(!inputs.empty()) {
for(unsigned j = 0; j < inputs.size(); ++j) {
bool isNeg = v->op(inputs[j]) == Expr::Not;
ID baseId = isNeg ? v->apply(Expr::Not, inputs[j]) : inputs[j];
os << " " << stringOf(*v, baseId) << ":" << !isNeg << endl;
}
}
else
os << " No input change" << std::endl;
os << std::endl;
}
delete v;
}
void ProofAttachment::printWitness(std::ostream& os)
{
assert(_hasConclusion && _safe == 1);
Expr::Manager::View * v = model().newView();
// Get the original inputs and state variables.
ExprAttachment const * const eat = (ExprAttachment const *) model().constAttachment(Key::EXPR);
vector<ID> inputVars = eat->originalInputs();
vector<ID> stateVars = eat->originalStateVars();
model().constRelease(eat);
std::string ostr("1\nc witness\nb0\n");
size_t ostrlen = stateVars.size() + 1 + (inputVars.size() + 1) * _cex.size() + 40;
ostr.reserve(ostrlen);
// Print initial state.
vector<ID> initState(_cex[0].state);
unordered_map<ID, bool> initMap;
for (size_t j = 0; j < initState.size(); ++j) {
ID s = initState[j];
bool isNeg = v->op(s) == Expr::Not;
if (isNeg) {
initMap.insert(unordered_map<ID, bool>::value_type(v->apply(Expr::Not,s),false));
} else {
initMap.insert(unordered_map<ID, bool>::value_type(s,true));
}
}
for (size_t j = 0; j < stateVars.size(); ++j) {
unordered_map<ID, bool>::const_iterator it = initMap.find(stateVars[j]);
if (it == initMap.end()) {
ostr.append(1, 'x');
} else {
ostr.append(1, it->second ? '1' : '0');
}
}
ostr.append(1, '\n');
for (unsigned i = 0; i < _cex.size(); ++i) {
vector<ID> inputs (_cex[i].inputs);
unordered_map<ID, bool> inputMap;
for (size_t j = 0; j < inputs.size(); ++j) {
ID t = inputs[j];
bool isNeg =v->op(t) == Expr::Not;
if (isNeg) {
inputMap.insert(unordered_map<ID, bool>::value_type(v->apply(Expr::Not,t),false));
} else {
inputMap.insert(unordered_map<ID, bool>::value_type(t,true));
}
}
for (size_t j = 0; j < inputVars.size(); ++j) {
unordered_map<ID, bool>::const_iterator it = inputMap.find(inputVars[j]);
if (it == inputMap.end()) {
ostr.append(1, 'x');
} else {
ostr.append(1, it->second ? '1' : '0');
}
}
ostr.append(1, '\n');
}
ostr.append(".\nc end witness\n");
os << ostr;
delete v;
}
void ProofAttachment::decodeCounterexample(void)
{
restoreDroppedLatches();
SeqAttachment const * const seat = (SeqAttachment const *)
model().constAttachment(Key::SEQ);
unordered_map<ID,ID> latchToInput = seat->latchToInput;
model().constRelease(seat);
// We need to re-encode inputs and reverse them. Moreover, the decoded
// traces are one step shorter, because the initialized latch has been
// eliminated. Here we assume that all latches have been restored.
Expr::Manager::View * v = model().newView();
vector<Transition> reversedCex;
// Add last input, which is all Xs.
reversedCex.push_back(Transition(vector<ID>(), vector<ID>()));
for (unsigned i = 0; i < _cex.size(); ++i) {
vector<ID> state;
vector<ID> inputs(_cex[i].inputs);
for (vector<ID>::const_iterator sit = _cex[i].state.begin(); sit != _cex[i].state.end(); ++sit) {
bool isNeg = v->op(*sit) == Expr::Not;
ID lid = isNeg ? v->apply(Expr::Not, *sit) : *sit;
unordered_map<ID,ID>::const_iterator it = latchToInput.find(lid);
if (it != latchToInput.end()) {
ID iid = isNeg ? v->apply(Expr::Not, it->second) : it->second;
inputs.push_back(iid);
}
}
if (i == _cex.size() - 1) {
ExprAttachment const * const eat = (ExprAttachment const *) model().constAttachment(Key::EXPR);
state = eat->originalInitialConditions();
model().constRelease(eat);
}
reversedCex.push_back(Transition(state,inputs));
}
_cex = vector<Transition>(reversedCex.rbegin(),reversedCex.rend());
delete v;
}
void ProofAttachment::unfoldCounterexample(void)
{
SeqAttachment const * const seat = (SeqAttachment const *)
model().constAttachment(Key::SEQ);
unordered_map<ID, pair<ID, unsigned> > cycleInputs = seat->cycleInputs;
unsigned int unrollings = seat->unrollings;
model().constRelease(seat);
if (unrollings == 1)
return;
std::vector<Transition> newCex;
newCex.push_back(Transition());
newCex[0].state = _cex[0].state;
Expr::Manager::View * v = model().newView();
// for each input@cycle in _cex, add original input value to correct step
for (unsigned step = 0; step < _cex.size(); ++step) {
for (unsigned i = 0; i < unrollings; ++i)
newCex.push_back(Transition());
for (vector<ID>::const_iterator jt = _cex[step].inputs.begin();
jt != _cex[step].inputs.end(); ++jt) {
bool isNeg = v->op(*jt) == Expr::Not;
ID baseIndex = isNeg ? v->apply(Expr::Not, *jt) : *jt;
ID lid = (cycleInputs[baseIndex]).first;
unsigned phase = (cycleInputs[baseIndex]).second;
unsigned int newStep = step*unrollings + phase;
if (isNeg)
newCex[newStep].inputs.push_back(v->apply(Expr::Not, lid));
else
newCex[newStep].inputs.push_back(lid);
}
}
delete v;
_cex = newCex;
}
void ProofAttachment::produceEvidenceForFailure(void)
{
boost::program_options::variables_map const & opts = model().options();
assert(opts.count("print_cex"));
bool skipMap = opts.count("xmap_cex");
bool printInfo = opts.count("print_info") > 0;
if (printInfo)
Util::printSystemInfo();
if (!skipMap) {
// Determine the type of transformation to be applied to the raw
// counterexample. We assume that decoding if applied always comes
// first, and that decoding and phase abstraction are mutually exclusive.
SeqAttachment const * const seat = (SeqAttachment const *)
model().constAttachment(Key::SEQ);
bool decoded = seat && seat->decoded;
bool phaseAbstracted = seat && (seat-> unrollings > 1);
model().constRelease(seat);
assert(!(decoded && phaseAbstracted));
if (decoded) {
decodeCounterexample();
} else if (phaseAbstracted) {
unfoldCounterexample();
restoreInitialCondition();
} else {
restoreInitialCondition();
}
}
// Determine the output stream.
bool printToFile = opts.count("cex_file");
ofstream ofs;
if (printToFile) {
// At this point, the conclusion (1) has not been written to cout.
// If the counterexample goes to a file, we need to duplicate that 1.
cout << '1' << endl;
std::string fname = opts["cex_file"].as<std::string>();
ofs.open(fname.c_str());
}
ostream& os = printToFile ? ofs : cout;
// Select output format.
bool aigerCex = opts.count("cex_aiger");
if (aigerCex)
printWitness(os);
else
printCex(os);
if (printToFile) {
ofs.close();
}
}
void ProofAttachment::printProof(std::ostream& os) const
{
assert(_hasConclusion && _safe == 0);
Expr::Manager::View * v = _model.newView();
os << std::endl << "One-step Inductive Strengthening of Property (in CNF):"
<< std::endl;
for(unsigned i = 0; i < _proof.size(); ++i) {
os << "Clause " << i << ": ";
for(unsigned j = 0; j < _proof[i].size(); ++j) {
os << stringOf(*v, _proof[i][j]) << " ";
}
os << std::endl;
}
delete v;
}
| 35.048048 | 101 | 0.622954 | [
"vector",
"model"
] |
716d5b722ff12d26d6d924bc11e0a790e7625003 | 18,552 | cpp | C++ | src/welding_demo_node.cpp | Veix123/welding_demo | af0428e442accd5956ada9d3feb2a1bf833a4592 | [
"Apache-2.0"
] | null | null | null | src/welding_demo_node.cpp | Veix123/welding_demo | af0428e442accd5956ada9d3feb2a1bf833a4592 | [
"Apache-2.0"
] | null | null | null | src/welding_demo_node.cpp | Veix123/welding_demo | af0428e442accd5956ada9d3feb2a1bf833a4592 | [
"Apache-2.0"
] | null | null | null | #include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit_msgs/msg/display_robot_state.hpp>
#include <moveit_msgs/msg/display_trajectory.hpp>
#include <moveit_msgs/msg/attached_collision_object.hpp>
#include <moveit_msgs/msg/collision_object.hpp>
#include <moveit_visual_tools/moveit_visual_tools.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include <math.h>
#include <tf2_eigen/tf2_eigen.hpp>
// All source files that use ROS logging should define a file-specific
// static const rclcpp::Logger named LOGGER, located at the top of the file
// and inside the namespace with the narrowest scope (if there is one)
static const rclcpp::Logger LOGGER = rclcpp::get_logger("welding_demo");
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
rclcpp::NodeOptions node_options;
node_options.automatically_declare_parameters_from_overrides(true);
auto welding_demo_node = rclcpp::Node::make_shared("welding_demo_node", node_options);
// We spin up a SingleThreadedExecutor for the current state monitor to get information
// about the robot's state.
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(welding_demo_node);
std::thread([&executor]() { executor.spin(); }).detach();
// BEGIN_TUTORIAL
//
// Setup
// ^^^^^
//
// MoveIt operates on sets of joints called "planning groups" and stores them in an object called
// the ``JointModelGroup``. Throughout MoveIt, the terms "planning group" and "joint model group"
// are used interchangeably.
static const std::string PLANNING_GROUP = "ur_manipulator";
// The
// :moveit_codedir:`MoveGroupInterface<moveit_ros/planning_interface/move_group_interface/include/moveit/move_group_interface/move_group_interface.h>`
// class can be easily set up using just the name of the planning group you would like to control
// and plan for.
moveit::planning_interface::MoveGroupInterface move_group(welding_demo_node, PLANNING_GROUP);
// We will use the
// :moveit_codedir:`PlanningSceneInterface<moveit_ros/planning_interface/planning_scene_interface/include/moveit/planning_scene_interface/planning_scene_interface.h>`
// class to add and remove collision objects in our "virtual world" scene
moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
// Visualization
// ^^^^^^^^^^^^^
namespace rvt = rviz_visual_tools;
moveit_visual_tools::MoveItVisualTools visual_tools(
welding_demo_node, "base_link", "welding_demo_tutorial", move_group.getRobotModel());
visual_tools.deleteAllMarkers();
/* Remote control is an introspection tool that allows users to step through a high level script
*/
/* via buttons and keyboard shortcuts in RViz */
visual_tools.loadRemoteControl();
// RViz provides many types of markers, in this demo we will use text, cylinders, and spheres
Eigen::Isometry3d text_pose = Eigen::Isometry3d::Identity();
text_pose.translation().z() = 1.0;
visual_tools.publishText(text_pose, "MoveGroupInterface_Demo", rvt::WHITE, rvt::XLARGE);
// Batch publishing is used to reduce the number of messages being sent to RViz for large
// visualizations
visual_tools.trigger();
// Getting Basic Information
// ^^^^^^^^^^^^^^^^^^^^^^^^^
//
// We can print the name of the reference frame for this robot.
RCLCPP_INFO(LOGGER, "Planning frame: %s", move_group.getPlanningFrame().c_str());
// We can also print the name of the end-effector link for this group.
RCLCPP_INFO(LOGGER, "End effector link: %s", move_group.getEndEffectorLink().c_str());
// We can get a list of all the groups in the robot:
RCLCPP_INFO(LOGGER, "Available Planning Groups:");
std::copy(move_group.getJointModelGroupNames().begin(),
move_group.getJointModelGroupNames().end(),
std::ostream_iterator<std::string>(std::cout, ", "));
// Start the demo loop
// ^^^^^^^^^^^^^^^^^^^^^^^^^
while (1)
{
visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to create a plan for a test "
"trajectory");
// Cartesian Paths
// ^^^^^^^^^^^^^^^
// You can plan a Cartesian path directly by specifying a list of waypoints
// for the end-effector to go through. Note that we are starting
// from the new start state above. The initial pose (start state) does not
// need to be added to the waypoint list but adding it can help with visualizations
std::vector<geometry_msgs::msg::Pose> waypoints;
geometry_msgs::msg::Pose robot_pose;
tf2::Vector3 center_pos = tf2::Vector3(0.2, 0, 0.8);
tf2::Vector3 goal_pos;
tf2::Vector3 goal_dir = tf2::Vector3(1, 0, 0); // forward pointing unit vec
tf2::Vector3 norm_vec;
goal_dir *= 0.2; // circle radius
tf2::Quaternion q_rot; // rotation for the unit vec (needed for the circle generation)
for (float angle = 0; angle < 2 * M_PI; angle += 0.5)
{
q_rot.setRPY(0, 0, angle); // define rotation
goal_pos = center_pos + tf2::quatRotate(q_rot, goal_dir); // apply the center offset for the
// rotated unit vec
q_rot.setRPY(0, 0, M_PI - angle); // align goal orientation towards the center of the circle
norm_vec = tf2::quatRotate(q_rot, goal_dir); // to be substituted with the normal data from PCL.
// convert to Eigen for a moment, and build quaternion from 2 vectors
Eigen::Vector3d vec1(norm_vec); // normal
Eigen::Vector3d vec2(1, 0, 0); // fwd direction
Eigen::Quaterniond quat = Eigen::Quaterniond::FromTwoVectors(vec1, vec2);
// convert from vector3 to pose message
robot_pose.position = tf2::toMsg(goal_pos, robot_pose.position);
// convert form quaternion to orientation message
geometry_msgs::msg::Quaternion qmsg;
qmsg = Eigen::toMsg(quat);
robot_pose.orientation = qmsg;
waypoints.push_back(robot_pose);
RCLCPP_INFO(LOGGER, "q_rot: %f %f %f %f", q_rot.x(), q_rot.y(), q_rot.z(), q_rot.w());
}
// We want the Cartesian path to be interpolated at a resolution of 1 cm
// which is why we will specify 0.01 as the max step in Cartesian
// translation. We will specify the jump threshold as 0.0, effectively disabling it.
// Warning - disabling the jump threshold while operating real hardware can cause
// large unpredictable motions of redundant joints and could be a safety issue
moveit_msgs::msg::RobotTrajectory trajectory;
const double jump_threshold = 0.0;
const double eef_step = 0.01;
double fraction =
move_group.computeCartesianPath(waypoints, eef_step, jump_threshold, trajectory);
RCLCPP_INFO(LOGGER, "Visualizing plan for a Cartesian path (%.2f%% achieved)",
fraction * 100.0);
// Visualize the plan in RViz
visual_tools.deleteAllMarkers();
visual_tools.publishText(text_pose, "Cartesian_Path", rvt::WHITE, rvt::XLARGE);
visual_tools.publishPath(waypoints, rvt::LIME_GREEN, rvt::SMALL);
for (std::size_t i = 0; i < waypoints.size(); ++i)
visual_tools.publishAxisLabeled(waypoints[i], "pt" + std::to_string(i), rvt::SMALL);
visual_tools.trigger();
visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to execute the trajectory");
move_group.execute(trajectory);
visual_tools.deleteAllMarkers();
visual_tools.trigger();
}
rclcpp::shutdown();
return 0;
}
// Some snippets from other demos...
// Moving to a pose goal
// ^^^^^^^^^^^^^^^^^^^^^
//
// Moving to a pose goal is similar to the step above
// except we now use the ``move()`` function. Note that
// the pose goal we had set earlier is still active
// and so the robot will try to move to that goal. We will
// not use that function in this tutorial since it is
// a blocking function and requires a controller to be active
// and report success on execution of a trajectory.
/* Uncomment below line when working with a real robot */
/* move_group.move(); */
// Planning with Path Constraints
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
// Path constraints can easily be specified for a link on the robot.
// Let's specify a path constraint and a pose goal for our group.
// First define the path constraint.
// moveit_msgs::msg::OrientationConstraint ocm;
// ocm.link_name = "panda_link7";
// ocm.header.frame_id = "panda_link0";
// ocm.orientation.w = 1.0;
// ocm.absolute_x_axis_tolerance = 0.1;
// ocm.absolute_y_axis_tolerance = 0.1;
// ocm.absolute_z_axis_tolerance = 0.1;
// ocm.weight = 1.0;
//
// // Now, set it as the path constraint for the group.
// moveit_msgs::msg::Constraints test_constraints;
// test_constraints.orientation_constraints.push_back(ocm);
// move_group.setPathConstraints(test_constraints);
//
// // Planning with constraints can be slow because every sample must call an inverse kinematics
// solver.
// // Let's increase the planning time from the default 5 seconds to be sure the planner has enough
// time to succeed. move_group.setPlanningTime(10.0);
//
// success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
// RCLCPP_INFO(LOGGER, "Visualizing plan 3 (constraints) %s", success ? "" : "FAILED");
//
// // Visualize the plan in RViz:
// visual_tools.deleteAllMarkers();
// visual_tools.publishAxisLabeled(start_pose2, "start");
// visual_tools.publishAxisLabeled(target_pose1, "goal");
// visual_tools.publishText(text_pose, "Constrained_Goal", rvt::WHITE, rvt::XLARGE);
// visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group);
// visual_tools.trigger();
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo");
//
// // When done with the path constraint, be sure to clear it.
// move_group.clearPathConstraints();
// // Cartesian motions should often be slow, e.g. when approaching objects. The speed of Cartesian
// // plans cannot currently be set through the maxVelocityScalingFactor, but requires you to time
// // the trajectory manually, as described `here
// <https://groups.google.com/forum/#!topic/moveit-users/MOoFxy2exT4>`_.
// // Pull requests are welcome.
// //
// // You can execute a trajectory like this.
// /* move_group.execute(trajectory); */
//
// // Adding objects to the environment
// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// //
// // First, let's plan to another simple goal with no objects in the way.
// move_group.setStartState(*move_group.getCurrentState());
// geometry_msgs::msg::Pose another_pose;
// another_pose.orientation.w = 0;
// another_pose.orientation.x = -1.0;
// another_pose.position.x = 0.7;
// another_pose.position.y = 0.0;
// another_pose.position.z = 0.59;
// move_group.setPoseTarget(another_pose);
//
// success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
// RCLCPP_INFO(LOGGER, "Visualizing plan 5 (with no obstacles) %s", success ? "" : "FAILED");
//
// visual_tools.deleteAllMarkers();
// visual_tools.publishText(text_pose, "Clear_Goal", rvt::WHITE, rvt::XLARGE);
// visual_tools.publishAxisLabeled(another_pose, "goal");
// visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group);
// visual_tools.trigger();
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo");
//
// // The result may look like this:
// //
// // .. image:: ./move_group_interface_tutorial_clear_path.gif
// // :alt: animation showing the arm moving relatively straight toward the goal
// //
// // Now, let's define a collision object ROS message for the robot to avoid.
// moveit_msgs::msg::CollisionObject collision_object;
// collision_object.header.frame_id = move_group.getPlanningFrame();
//
// // The id of the object is used to identify it.
// collision_object.id = "box1";
//
// // Define a box to add to the world.
// shape_msgs::msg::SolidPrimitive primitive;
// primitive.type = primitive.BOX;
// primitive.dimensions.resize(3);
// primitive.dimensions[primitive.BOX_X] = 0.1;
// primitive.dimensions[primitive.BOX_Y] = 1.5;
// primitive.dimensions[primitive.BOX_Z] = 0.5;
//
// // Define a pose for the box (specified relative to frame_id).
// geometry_msgs::msg::Pose box_pose;
// box_pose.orientation.w = 1.0;
// box_pose.position.x = 0.48;
// box_pose.position.y = 0.0;
// box_pose.position.z = 0.25;
//
// collision_object.primitives.push_back(primitive);
// collision_object.primitive_poses.push_back(box_pose);
// collision_object.operation = collision_object.ADD;
//
// std::vector<moveit_msgs::msg::CollisionObject> collision_objects;
// collision_objects.push_back(collision_object);
//
// // Now, let's add the collision object into the world
// // (using a vector that could contain additional objects)
// RCLCPP_INFO(LOGGER, "Add an object into the world");
// planning_scene_interface.addCollisionObjects(collision_objects);
//
// // Show text in RViz of status and wait for MoveGroup to receive and process the collision
// object message visual_tools.publishText(text_pose, "Add_object", rvt::WHITE, rvt::XLARGE);
// visual_tools.trigger();
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object
// appears in RViz");
//
// // Now, when we plan a trajectory it will avoid the obstacle.
// success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
// RCLCPP_INFO(LOGGER, "Visualizing plan 6 (pose goal move around cuboid) %s", success ? "" :
// "FAILED"); visual_tools.publishText(text_pose, "Obstacle_Goal", rvt::WHITE, rvt::XLARGE);
// visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group);
// visual_tools.trigger();
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the plan is complete");
//
// // The result may look like this:
// //
// // .. image:: ./move_group_interface_tutorial_avoid_path.gif
// // :alt: animation showing the arm moving avoiding the new obstacle
// //
// // Attaching objects to the robot
// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// //
// // You can attach an object to the robot, so that it moves with the robot geometry.
// // This simulates picking up the object for the purpose of manipulating it.
// // The motion planning should avoid collisions between objects as well.
// moveit_msgs::msg::CollisionObject object_to_attach;
// object_to_attach.id = "cylinder1";
//
// shape_msgs::msg::SolidPrimitive cylinder_primitive;
// cylinder_primitive.type = primitive.CYLINDER;
// cylinder_primitive.dimensions.resize(2);
// cylinder_primitive.dimensions[primitive.CYLINDER_HEIGHT] = 0.20;
// cylinder_primitive.dimensions[primitive.CYLINDER_RADIUS] = 0.04;
//
// // We define the frame/pose for this cylinder so that it appears in the gripper.
// object_to_attach.header.frame_id = move_group.getEndEffectorLink();
// geometry_msgs::msg::Pose grab_pose;
// grab_pose.orientation.w = 1.0;
// grab_pose.position.z = 0.2;
//
// // First, we add the object to the world (without using a vector).
// object_to_attach.primitives.push_back(cylinder_primitive);
// object_to_attach.primitive_poses.push_back(grab_pose);
// object_to_attach.operation = object_to_attach.ADD;
// planning_scene_interface.applyCollisionObject(object_to_attach);
//
// // Then, we "attach" the object to the robot. It uses the frame_id to determine which robot link
// it is attached to.
// // We also need to tell MoveIt that the object is allowed to be in collision with the finger
// links of the gripper.
// // You could also use applyAttachedCollisionObject to attach an object to the robot directly.
// RCLCPP_INFO(LOGGER, "Attach the object to the robot");
// std::vector<std::string> touch_links;
// touch_links.push_back("panda_rightfinger");
// touch_links.push_back("panda_leftfinger");
// move_group.attachObject(object_to_attach.id, "panda_hand", touch_links);
//
// visual_tools.publishText(text_pose, "Object_attached_to_robot", rvt::WHITE, rvt::XLARGE);
// visual_tools.trigger();
//
// /* Wait for MoveGroup to receive and process the attached collision object message */
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the new object is
// attached to the robot");
//
// // Replan, but now with the object in hand.
// move_group.setStartStateToCurrentState();
// success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
// RCLCPP_INFO(LOGGER, "Visualizing plan 7 (move around cuboid with cylinder) %s", success ? "" :
// "FAILED"); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group);
// visual_tools.trigger();
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the plan is complete");
//
// // The result may look something like this:
// //
// // .. image:: ./move_group_interface_tutorial_attached_object.gif
// // :alt: animation showing the arm moving differently once the object is attached
// //
// // Detaching and Removing Objects
// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// //
// // Now, let's detach the cylinder from the robot's gripper.
// RCLCPP_INFO(LOGGER, "Detach the object from the robot");
// move_group.detachObject(object_to_attach.id);
//
// // Show text in RViz of status
// visual_tools.deleteAllMarkers();
// visual_tools.publishText(text_pose, "Object_detached_from_robot", rvt::WHITE, rvt::XLARGE);
// visual_tools.trigger();
//
// /* Wait for MoveGroup to receive and process the attached collision object message */
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the new object is
// detached from the robot");
//
// // Now, let's remove the objects from the world.
// RCLCPP_INFO(LOGGER, "Remove the objects from the world");
// std::vector<std::string> object_ids;
// object_ids.push_back(collision_object.id);
// object_ids.push_back(object_to_attach.id);
// planning_scene_interface.removeCollisionObjects(object_ids);
//
// // Show text in RViz of status
// visual_tools.publishText(text_pose, "Objects_removed", rvt::WHITE, rvt::XLARGE);
// visual_tools.trigger();
//
// /* Wait for MoveGroup to receive and process the attached collision object message */
// visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object
// disappears");
// END_TUTORIAL
| 46.149254 | 168 | 0.712969 | [
"geometry",
"object",
"vector",
"model"
] |
717412868e351441173fdd67b4a34049ed450e46 | 2,081 | hpp | C++ | include/Particle.hpp | ThomScottW/GravSimCpp | 893e09f061276f69d400abf5c253c94b7fb2a717 | [
"MIT"
] | null | null | null | include/Particle.hpp | ThomScottW/GravSimCpp | 893e09f061276f69d400abf5c253c94b7fb2a717 | [
"MIT"
] | null | null | null | include/Particle.hpp | ThomScottW/GravSimCpp | 893e09f061276f69d400abf5c253c94b7fb2a717 | [
"MIT"
] | null | null | null | #ifndef PARTICLE_HPP
#define PARTICLE_HPP
#include "MotionVector.hpp"
class Particle
{
public:
Particle(
double radius,
double x,
double y,
MotionVector<double> vec,
double density=0.15
);
// Return the x coordinate of this particle.
double x();
// Return the y coordinate of this particle.
double y();
// Move the particle based on its vector's direction and speed.
void move();
// Accelrate this particle towards a point.
void accelerateTowards(double x, double y, double constant, double pointMass=1);
// Collide with another particle, coalescing into a larger particle. An elasticity
// constant simulates the loss of energy after collision.
void coalesce(Particle& p2, double constant);
// Return the distance from this particle's center to a point.
double distanceFrom(double x, double y);
// Return true if this particle is colliding with p2.
bool isCollidingWith(Particle& p2);
// Return true if this particle has been absorbed by another.
bool isAbsorbed();
// Stops the particle from being affected by gravity and freezes it in place.
void freeze();
// The particle can now be affected by gravity.
void unFreeze();
// Return true if the particle is frozen.
bool isFrozen();
// Return the radius of a particle with a given mass.
double static calcRad(double mass, double density);
// Return the mass of a particle, given a radius.
double static calcMass(double radius, double density);
// Return the radius of this particle.
double getRadius();
// Return the mass of this particle.
double getMass();
// Simulate the effect of elasticity by applying a force to the particle's
// motion vector. The elasticity constant is defined by the environment.
void applyElasticity(double constant);
private:
double rad;
double x_pos;
double y_pos;
double mass;
MotionVector<double> vec;
double density;
bool absorbed;
bool fixed;
};
#endif
| 25.072289 | 86 | 0.679481 | [
"vector"
] |
717a6fa012d009ae6a6a0a711bffc0b348b26e49 | 1,740 | cpp | C++ | sample/server.cpp | tynia/tynia | 9dd2a09faafa9d38c2679fa32e25a4db1317095e | [
"MIT"
] | null | null | null | sample/server.cpp | tynia/tynia | 9dd2a09faafa9d38c2679fa32e25a4db1317095e | [
"MIT"
] | null | null | null | sample/server.cpp | tynia/tynia | 9dd2a09faafa9d38c2679fa32e25a4db1317095e | [
"MIT"
] | null | null | null | #include "util/inspire.h"
#include "util/assert.h"
#include "net.h"
#include "thread/threads.h"
#include "util/system/condition.h"
struct msgClient
{
int64 id;
char data[100];
};
class Server
{
public:
Server() : _fd(-1), _stop(false)
{}
~Server()
{
if (!_sessions.empty())
{
for (int idx = 0; idx < _sessions.size(); ++idx)
{
::closesocket(_sessions[idx]);
}
}
}
void stop()
{
_stop = true;
}
virtual const int run()
{
_fd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
STRONG_ASSERT(SOCKET_ERROR != _fd, "Failed to initialize socket");
int port = 50000;
sockaddr_in addr;
memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
int rc = ::bind(_fd, (sockaddr*)&addr, 0);
STRONG_ASSERT(SOCKET_ERROR != rc, "Failed to bind socket");
rc = ::listen(_fd, 1000000);
STRONG_ASSERT(SOCKET_ERROR != rc, "Failed to listen");
_stop = false;
while (!_stop)
{
int remote;
sockaddr_in raddr;
int len = sizeof(sockaddr);
remote = ::accept(_fd, (sockaddr*)&raddr, &len);
if (SOCKET_ERROR != remote)
{
msgClient cc;
::recv(remote, (char*)&cc, sizeof(int64) + 100, 0);
std::cout << "Receive from client: " << cc.id << ", msg: " << cc.data << std::endl;
_sessions.push_back(remote);
}
}
return 0;
}
private:
bool _stop;
int _fd;
std::vector<int> _sessions;
};
int main(int argc, char** argv)
{
Server serv;
serv.run();
return 0;
} | 20.963855 | 95 | 0.543678 | [
"vector"
] |
717f7aac737a847d9a14d55cda4bcfbc53c27a27 | 886 | cpp | C++ | Dungeon Engine/Gui.cpp | 62bit/Dungeon | e83526c2d4f63a816e231942b87b1d4c8988897a | [
"MIT"
] | 2 | 2020-08-02T01:41:03.000Z | 2020-08-11T16:37:10.000Z | Dungeon Engine/Gui.cpp | 62bit/Dungeon | e83526c2d4f63a816e231942b87b1d4c8988897a | [
"MIT"
] | null | null | null | Dungeon Engine/Gui.cpp | 62bit/Dungeon | e83526c2d4f63a816e231942b87b1d4c8988897a | [
"MIT"
] | 1 | 2020-08-11T18:29:39.000Z | 2020-08-11T18:29:39.000Z | #include "Gui.h"
Gui::Gui(GLFWwindow* window, bool install_callbacks)
:_window(window), _renderer(Renderer::GetInstance())
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
_io = ImGui::GetIO();
(void)_io;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window, install_callbacks);
ImGui_ImplOpenGL3_Init("#version 330 core");
}
void Gui::GuiAddWindow(MyGuiWindow* window)
{
_guiWindows.push_back(window);
}
void Gui::GuiRemoveWindow(MyGuiWindow* window)
{
if (_guiWindows.size() <= 0)
return;
std::vector<MyGuiWindow*>::iterator it = std::find(_guiWindows.begin(), _guiWindows.end(), window);
_guiWindows.erase(it);
}
void Gui::Update() const
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
for (MyGuiWindow* w : _guiWindows)
w->Update();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
| 18.458333 | 100 | 0.72912 | [
"render",
"vector"
] |
71808c09c283a4b827f571a9715d5077a3e8c7ff | 588 | cpp | C++ | docs/snippets/protecting_model_guide.cpp | ldebski/openvino | ecbe0166af8badb2a6f7e9839ad284608ff83061 | [
"Apache-2.0"
] | 2 | 2021-02-26T15:46:19.000Z | 2021-05-16T20:48:13.000Z | docs/snippets/protecting_model_guide.cpp | ldebski/openvino | ecbe0166af8badb2a6f7e9839ad284608ff83061 | [
"Apache-2.0"
] | null | null | null | docs/snippets/protecting_model_guide.cpp | ldebski/openvino | ecbe0166af8badb2a6f7e9839ad284608ff83061 | [
"Apache-2.0"
] | null | null | null | #include <inference_engine.hpp>
int main() {
using namespace InferenceEngine;
//! [part0]
std::vector<uint8_t> model;
std::vector<uint8_t> weights;
// Read model files and decrypt them into temporary memory block
decrypt_file(model_file, password, model);
decrypt_file(weights_file, password, weights);
//! [part0]
//! [part1]
Core core;
// Load model from temporary memory block
std::string strModel(model.begin(), model.end());
CNNNetwork network = core.ReadNetwork(strModel, make_shared_blob<uint8_t>({Precision::U8, {weights.size()}, C}, weights.data()));
//! [part1]
return 0;
}
| 25.565217 | 129 | 0.734694 | [
"vector",
"model"
] |
7180d696d85853ba27c8c751c6c83ef1f7b819bb | 3,565 | hpp | C++ | Portal-stein/Portal-stein/Wall.hpp | jeysym/portal-stein | 33cb29f66f9adb89f545b105ad1cdeaed9460c63 | [
"MIT"
] | null | null | null | Portal-stein/Portal-stein/Wall.hpp | jeysym/portal-stein | 33cb29f66f9adb89f545b105ad1cdeaed9460c63 | [
"MIT"
] | null | null | null | Portal-stein/Portal-stein/Wall.hpp | jeysym/portal-stein | 33cb29f66f9adb89f545b105ad1cdeaed9460c63 | [
"MIT"
] | null | null | null | #pragma once
#ifndef PS_WALL_INCLUDED
#define PS_WALL_INCLUDED
#include <memory>
#include <SFML\Graphics.hpp>
#include "Portal.hpp"
#include "ObjectInScene.hpp"
#include "Geometry.hpp"
namespace ps {
struct WallDrawParameters {
sf::Vector2f scrWallTop; ///< Screen coordinate of wall top.
sf::Vector2f scrWallBottom; ///< Screen coordinate of wall bottom.
sf::Vector2f uvWallTop; ///< Texture coordinate of wall top.
sf::Vector2f uvWallBottom; ///< Texture coordinate of wall bottom/
};
struct WallIntersection {
float rayIntersectionDistance; ///< Distance of from ray origin to hit point.
float distanceToWallEdge; ///< Distance from Wall edge to hit point.
};
//************************************************************************
// WALL CLASSES
//************************************************************************
/// Class that represents wall, that has color and (optional) texture.
class Wall {
private:
sf::Color color;
std::shared_ptr<sf::Texture> texture;
public:
sf::Vector2f from;
sf::Vector2f to;
/// Creates a colored wall.
Wall(sf::Vector2f from, sf::Vector2f to, sf::Color color);
/// Creates a wall with color + texture.
Wall(sf::Vector2f from, sf::Vector2f to, sf::Color color, std::shared_ptr<sf::Texture> texture);
/// Draws the wall on render target, according to draw parameters that were passed.
void draw(sf::RenderTarget & rt, const WallDrawParameters & params) const;
/// Gets width of the wall.
float getWidth() const;
/// Returns true if the wall faces the ray. Returning false means this wall is not visible by that ray.
bool facesRay(const Ray & ray) const;
/// Returns signed distance (positive on the inside of segment) of the point from the wall. Distance is handled correctly even for points, for which
/// the least distant point of the wall is one of the wall's vertices.
float distanceFromWall(const sf::Vector2f & point) const;
/// Intersects the wall with a ray. Intersection is returned as out parameter.
bool intersect(const Ray & ray, WallIntersection & intersection) const;
/// Returns true if line segment intersects the wall.
bool intersect(const LineSegment & lineSegment_) const;
};
/// Wall that can have portal on itself.
class PortalWall : public Wall {
private:
portalPtr portal;
public:
/// Creates a colored wall.
PortalWall(sf::Vector2f from, sf::Vector2f to, sf::Color color);
/// Creates a wall with color + texture.
PortalWall(sf::Vector2f from, sf::Vector2f to, sf::Color color, std::shared_ptr<sf::Texture> texture);
PortalWall(const PortalWall & rs) = default;
PortalWall(PortalWall && rs) = default;
PortalWall & operator=(const PortalWall & rs) = default;
PortalWall & operator=(PortalWall && rs) = default;
/// Returns true if this wall has portal on it.
bool isPortal() const;
/// Takes object and passes it through portal.
void stepThrough(ObjectInScene & obj) const;
/// Sets portal for this wall.
void setPortal(const portalPtr & portal);
};
//************************************************************************
// PREDEFINED WALLS WITH COMMON PORTALS
//************************************************************************
/// Makes PortalWall that has Door portal on it.
PortalWall makeDoorWall(sf::Vector2f from, sf::Vector2f to, std::size_t targetSegment);
/// Makes PortalWall that has WallPortal on it.
PortalWall makeWallPortalWall(LineSegment wallFrom, LineSegment wallTo, std::size_t targetSegment_);
}
#endif // !PS_WALL_INCLUDED
| 35.65 | 151 | 0.662553 | [
"geometry",
"render",
"object"
] |
718510293570bd50c486c1477faee2f1bd8d2433 | 1,939 | cpp | C++ | test/range/python/tuple_example.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | test/range/python/tuple_example.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | test/range/python/tuple_example.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2015 Rogier van Dalen.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* \file
Provide an example usage of python/tuple.hpp.
The functions defined here are exported to Python, and used by
test-tuple.py.
*/
#include "range/python/tuple.hpp"
#include <tuple>
#include <string>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include "range/tuple.hpp"
#include "range/std/tuple.hpp"
#include "range/transform.hpp"
#include "range/view_shared.hpp"
std::tuple <double, std::string> double_string;
std::tuple <double, std::string> get_double_string()
{ return double_string; }
range::tuple <int, float, std::string> get_int_float_string (int i, float f) {
return range::make_tuple (i, f, "Wow!");
}
struct twice {
template <class Type> Type operator() (Type const & o) const
{ return o + o; }
};
auto get_twice (int i, float f)
RETURNS (range::transform (range::view_shared (get_int_float_string (i, f)),
twice()));
BOOST_PYTHON_MODULE (tuple_example) {
using namespace boost::python;
double_string = std::make_tuple (6.5, "Excellent.");
range::python::register_tuple <std::tuple <double, std::string>>();
range::python::register_tuple <range::tuple <int, float, std::string>>();
range::python::register_tuple <decltype (get_twice (5, 6))>();
def ("getDoubleString", &get_double_string);
def ("getIntBoolString", &get_int_float_string);
def ("getTwice", &get_twice);
}
| 28.940299 | 78 | 0.722537 | [
"transform"
] |
7191c207547dc12118ea58560435411fae42e447 | 4,684 | cpp | C++ | src/geometry/BoxGeometry.cpp | fwlab/fwlab | 55c09e83c5da158102b36e8b6b36a3544114bb9e | [
"MIT"
] | 1 | 2022-02-28T13:08:03.000Z | 2022-02-28T13:08:03.000Z | src/geometry/BoxGeometry.cpp | fwlab/fwlab | 55c09e83c5da158102b36e8b6b36a3544114bb9e | [
"MIT"
] | null | null | null | src/geometry/BoxGeometry.cpp | fwlab/fwlab | 55c09e83c5da158102b36e8b6b36a3544114bb9e | [
"MIT"
] | null | null | null | #include <cmath>
#include <iterator>
#include <iostream>
#include <unordered_map>
#include <geometry/SurfaceOrientation.h>
#include "../utils/Logger.h"
#include "BoxGeometry.h"
namespace fwlab::geometry
{
BoxGeometry::BoxGeometry()
{
}
BoxGeometry::~BoxGeometry()
{
//if (tangents)
//{
// delete tangents;
//}
}
void BoxGeometry::create(float width, float height, float depth, uint16_t widthSegments, uint16_t heightSegments, uint16_t depthSegments)
{
// helper variables
numberOfVertices = 0;
groupStart = 0;
// build each side of the box geometry
buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
// position
auto position = new core::VertexBufferAttribute(vertices);
attributes.insert({ filament::VertexAttribute::POSITION, position });
// uv
auto uv = new core::VertexBufferAttribute(uvs);
attributes.insert({ filament::VertexAttribute::UV0, uv });
// index
index = new core::IndexBufferAttribute(triangles);
// normal
auto vertexCount = vertices.size();
auto* quats = filament::geometry::SurfaceOrientation::Builder()
.vertexCount(vertexCount)
.positions(vertices.data())
.normals(normals.data())
.uvs(uvs.data())
.triangleCount(triangles.size())
.triangles(triangles.data())
.build();
tangents = new filament::math::short4[vertexCount];
quats->getQuats(tangents, vertexCount, sizeof(filament::math::short4));
delete quats;
quats = nullptr;
auto normal = new core::VertexBufferAttribute(tangents, 4, vertexCount, filament::VertexBuffer::AttributeType::SHORT4, true);
attributes.insert({ filament::VertexAttribute::TANGENTS, normal });
delete tangents;
BufferGeometry::create();
}
void BoxGeometry::buildPlane(std::string u, std::string v, std::string w, float udir, float vdir, float width, float height, float depth, int gridX, int gridY, int materialIndex)
{
float segmentWidth = width / gridX;
float segmentHeight = height / gridY;
float widthHalf = width / 2;
float heightHalf = height / 2;
float depthHalf = depth / 2;
int gridX1 = gridX + 1;
int gridY1 = gridY + 1;
int vertexCounter = 0;
int groupCount = 0;
std::unordered_map<std::string, float> vector;
// generate vertices, normals and uvs
for (float iy = 0; iy < gridY1; iy++)
{
float y = iy * segmentHeight - heightHalf;
for (float ix = 0; ix < gridX1; ix++)
{
float x = ix * segmentWidth - widthHalf;
// set values to correct vector component
vector.clear();
vector.insert({ u, x * udir });
vector.insert({ v, y * vdir });
vector.insert({ w, depthHalf });
// now apply vector to vertex buffer
this->vertices.push_back(filament::math::float3(vector.at("x"), vector.at("y"), vector.at("z")));
// set values to correct vector component
vector.clear();
vector.insert({ u, 0 });
vector.insert({ v, 0 });
vector.insert({ w, depth > 0 ? 1 : -1 });
// now apply vector to normal buffer
this->normals.push_back(filament::math::float3(vector.at("x"), vector.at("y"), vector.at("z")));
// uvs
this->uvs.push_back(filament::math::float2(ix / gridX, 1 - (iy / gridY)));
// counters
vertexCounter += 1;
}
}
// indices
// 1. you need three indices to draw a single face
// 2. a single segment consists of two faces
// 3. so we need to generate six (2*3) indices per segment
for (int iy = 0; iy < gridY; iy++)
{
for (int ix = 0; ix < gridX; ix++)
{
int a = numberOfVertices + ix + gridX1 * iy;
int b = numberOfVertices + ix + gridX1 * (iy + 1);
int c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
int d = numberOfVertices + (ix + 1) + gridX1 * iy;
// faces
this->triangles.push_back(filament::math::uint3(a, b, d));
this->triangles.push_back(filament::math::uint3(b, c, d));
// increase counter
groupCount += 6;
}
}
// add a group to the geometry. this will ensure multi material support
this->addGroup(groupStart, groupCount, materialIndex);
// calculate new start value for groups
groupStart += groupCount;
// update total number of vertices
numberOfVertices += vertexCounter;
}
} | 30.415584 | 179 | 0.655209 | [
"geometry",
"vector"
] |
71961214d9e25ea598a317ecf627bd2bc69dc283 | 692 | cpp | C++ | main.cpp | viniciusfer01/SculptorTheReturn | 9c80c9fc4c8a74759d1663e9b57a4d9199e2b2e2 | [
"MIT"
] | null | null | null | main.cpp | viniciusfer01/SculptorTheReturn | 9c80c9fc4c8a74759d1663e9b57a4d9199e2b2e2 | [
"MIT"
] | null | null | null | main.cpp | viniciusfer01/SculptorTheReturn | 9c80c9fc4c8a74759d1663e9b57a4d9199e2b2e2 | [
"MIT"
] | null | null | null | #include "putsphere.h"
#include "putvoxel.h"
#include "cutbox.h"
#include "cutellipsoid.h"
#include "cutsphere.h"
#include "cutvoxel.h"
#include "interpretador.h"
using namespace std;
int main(){
Sculptor *s1;
Interpretador parser;
std:: vector<FiguraGeometrica*> figs;
figs = parser.parse("input.txt");
s1 = new Sculptor(parser.getDimx(), parser.getDimy(), parser.getDimz());
cout << figs.size() << endl;
for(size_t i=0; i<figs.size(); i++){
figs[i]->draw(*s1);
}
s1->limpaVoxels();
s1->writeOFF((char*)"exit.off");
for(size_t i=0; i<figs.size(); i++){
delete figs[i];
}
delete s1;
return 0;
}
| 19.222222 | 76 | 0.58815 | [
"vector"
] |
71985c8ab454c20db1b136256e6a45321217f4a9 | 2,203 | cc | C++ | src/parser.cc | jdavidberger/stencet | 092dfabe395c46efdd74504050f83aa38d1b2c87 | [
"MIT"
] | null | null | null | src/parser.cc | jdavidberger/stencet | 092dfabe395c46efdd74504050f83aa38d1b2c87 | [
"MIT"
] | null | null | null | src/parser.cc | jdavidberger/stencet | 092dfabe395c46efdd74504050f83aa38d1b2c87 | [
"MIT"
] | null | null | null | /* Copyright (C) 2012-2013 Justin Berger
The full license is available in the LICENSE file at the root of this project and is also available at http://opensource.org/licenses/MIT. */
#include <stencet/parser.h>
#include <stencet/tag.h>
namespace stencet {
inline Token nextToken(std::istream& stream, char& buffer){
Token rtn = Val;
buffer = stream.get();
if(buffer == EOF)
return eof;
char peek = stream.peek();
if(buffer == '{'){
rtn =
peek == '{' ? OpenVar :
peek == '%' ? OpenTag : Val;
} else if (peek == '}'){
rtn =
buffer == '}' ? CloseVar :
buffer == '%' ? CloseTag : Val;
}
if(rtn != Val)
stream.get();
return rtn;
}
static void finish(std::istream& stream, std::string& text){
Token tkn;
char curr;
text.clear();
while( (tkn = nextToken(stream, curr)) != EOF ){
if(tkn == CloseVar || tkn == CloseTag)
return;
if(curr != ' ' || text.size() > 0)
text += curr;
}
}
ParseStatus::t Parse(std::istream& stream,
std::vector<Region*>& regions,
std::string& unknown){
char curr;
unknown.clear();
LiteralRegion* lb = 0;
Token tkn;
int depth = 0;
while( (tkn = nextToken(stream, curr)) != EOF ){
if(tkn == OpenVar || tkn == OpenTag) {
lb = 0;
std::string contents;
finish(stream, contents);
if(tkn == OpenTag){
if(stream.peek() == '\r') stream.get();
if(stream.peek() == '\n') stream.get();
bool endTag = contents.find("end") == 0;
depth += endTag ? -1 : 1;
if(depth == -1)
return ParseStatus::POP;
if(!endTag){
const char* n = &contents[0];
while(*n == ' ') n++;
const char* ne = n;
while(*ne != ' ' && *ne) ne++;
std::string name(n, ne);
Tag* tag = TagFactory::Create(name, stream, contents);
if(tag)
regions.push_back(tag);
else {
contents.swap(unknown);
return ParseStatus::UNKNOWN;
}
}
} else {
regions.push_back(new VariableRegion(contents));
}
} else if(tkn == Val) {
if(lb == 0){
lb = new LiteralRegion();
regions.push_back(lb);
}
lb->data += curr;
}
}
return ParseStatus::END;
}
}
| 22.479592 | 144 | 0.551975 | [
"vector"
] |
719b50dbfa97dbbe1e72acfcb547ebaa8c6d125b | 828 | cpp | C++ | igl/copyleft/cgal/lexicographic_triangulation.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | igl/copyleft/cgal/lexicographic_triangulation.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | igl/copyleft/cgal/lexicographic_triangulation.cpp | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com>
// Qingan Zhou <qnzhou@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "lexicographic_triangulation.h"
#include "../../lexicographic_triangulation.h"
#include "orient2D.h"
template<
typename DerivedP,
typename DerivedF
>
IGL_INLINE void igl::copyleft::cgal::lexicographic_triangulation(
const Eigen::PlainObjectBase<DerivedP>& P,
Eigen::PlainObjectBase<DerivedF>& F)
{
typedef typename DerivedP::Scalar Scalar;
igl::lexicographic_triangulation(P, orient2D<Scalar>, F);
}
| 33.12 | 79 | 0.719807 | [
"geometry"
] |
71a27c647ebcfa090030a3e0297e83a835a92c66 | 714 | hpp | C++ | Server/Sources/GameLogic/GameData.hpp | Eitu33/indie | 0183cfb07f76ec74aad24c7806965e0a6f9fe77b | [
"MIT"
] | 1 | 2022-01-28T19:48:31.000Z | 2022-01-28T19:48:31.000Z | Server/Sources/GameLogic/GameData.hpp | Eitu33/indie | 0183cfb07f76ec74aad24c7806965e0a6f9fe77b | [
"MIT"
] | null | null | null | Server/Sources/GameLogic/GameData.hpp | Eitu33/indie | 0183cfb07f76ec74aad24c7806965e0a6f9fe77b | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2019
** oop_indie_studio_2018
** File description:
** GameData
*/
#ifndef GAMEDATA_HPP_
#define GAMEDATA_HPP_
#include "Direction.hpp"
#include "Bonus.hpp"
#include <vector>
namespace game_logic
{
struct PlayerData
{
unsigned int id;
float x;
float y;
Direction direction;
bool isAlive;
};
struct BombData
{
float x;
float y;
int explosionSize[4];
};
struct WallData
{
float x;
float y;
bool isBonus;
Bonus bonus;
bool isTough;
};
struct GameData
{
std::vector<struct PlayerData> players;
std::vector<struct BombData> bombs;
std::vector<struct WallData> walls;
};
} // namespace game_logic
#endif /* !GAMEDATA_HPP_ */
| 13.471698 | 43 | 0.666667 | [
"vector"
] |
71a321b567fc087b4f0b63ac83ff93635175221f | 16,131 | cpp | C++ | samples/Common/Source/es_util.cpp | cpuimage/TinyText | efb62630180c6e0558b696fcb5bbb5f13f545623 | [
"Apache-2.0"
] | 5 | 2020-10-15T08:35:40.000Z | 2022-03-26T14:02:10.000Z | samples/Common/Source/es_util.cpp | cpuimage/TinyText | efb62630180c6e0558b696fcb5bbb5f13f545623 | [
"Apache-2.0"
] | null | null | null | samples/Common/Source/es_util.cpp | cpuimage/TinyText | efb62630180c6e0558b696fcb5bbb5f13f545623 | [
"Apache-2.0"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2013 Dan Ginsburg, Budirijanto Purnomo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Book: OpenGL(R) ES 3.0 Programming Guide, 2nd Edition
// Authors: Dan Ginsburg, Budirijanto Purnomo, Dave Shreiner, Aaftab Munshi
// ISBN-10: 0-321-93388-5
// ISBN-13: 978-0-321-93388-1
// Publisher: Addison-Wesley Professional
// URLs: http://www.opengles-book.com
// http://my.safaribooksonline.com/book/animation-and-3d/9780133440133
//
// ESUtil.c
//
// A utility library for OpenGL ES. This library provides a
// basic common framework for the example applications in the
// OpenGL ES 3.0 Programming Guide.
//
///
// Includes
//
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "es_util.h"
#include "es_util_win.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#ifdef ANDROID
#include <android/log.h>
#include <android_native_app_glue.h>
#include <android/asset_manager.h>
typedef AAsset esFile;
#else
typedef FILE esFile;
#endif
#ifdef __APPLE__
#include "FileWrapper.h"
#endif
#ifndef __APPLE__
///
// GetContextRenderableType()
//
// Check whether EGL_KHR_create_context extension is supported. If so,
// return EGL_OPENGL_ES3_BIT_KHR instead of EGL_OPENGL_ES2_BIT
//
EGLint GetContextRenderableType(EGLDisplay eglDisplay) {
#ifdef EGL_KHR_create_context
const char *extensions = eglQueryString(eglDisplay, EGL_EXTENSIONS);
// check whether EGL_KHR_create_context is in the extension string
if (extensions != NULL && strstr(extensions, "EGL_KHR_create_context")) {
// extension is supported
return EGL_OPENGL_ES3_BIT_KHR;
}
#endif
// extension is not supported
return EGL_OPENGL_ES2_BIT;
}
#endif
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
//
///
// esCreateWindow()
//
// title - name for title bar of window
// width - width of window to create
// height - height of window to create
// flags - bitwise or of window creation flags
// ES_WINDOW_ALPHA - specifies that the framebuffer should have alpha
// ES_WINDOW_DEPTH - specifies that a depth buffer should be created
// ES_WINDOW_STENCIL - specifies that a stencil buffer should be created
// ES_WINDOW_MULTISAMPLE - specifies that a multi-sample buffer should be created
//
GLboolean ESUTIL_API esCreateWindow(ESContext *esContext, const char *title, GLint width, GLint height, GLuint flags) {
#ifndef __APPLE__
EGLConfig config;
EGLint majorVersion;
EGLint minorVersion;
EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
if (esContext == NULL) {
return GL_FALSE;
}
#ifdef ANDROID
// For Android, get the width/height from the window rather than what the
// application requested.
esContext->width = ANativeWindow_getWidth ( esContext->eglNativeWindow );
esContext->height = ANativeWindow_getHeight ( esContext->eglNativeWindow );
#else
esContext->width = width;
esContext->height = height;
#endif
if (!WinCreate(esContext, title)) {
return GL_FALSE;
}
esContext->eglDisplay = eglGetDisplay(esContext->eglNativeDisplay);
if (esContext->eglDisplay == EGL_NO_DISPLAY) {
return GL_FALSE;
}
// Initialize EGL
if (!eglInitialize(esContext->eglDisplay, &majorVersion, &minorVersion)) {
return GL_FALSE;
}
{
EGLint numConfigs = 0;
EGLint attribList[] =
{
EGL_RED_SIZE, 5,
EGL_GREEN_SIZE, 6,
EGL_BLUE_SIZE, 5,
EGL_ALPHA_SIZE, (flags & ES_WINDOW_ALPHA) ? 8 : EGL_DONT_CARE,
EGL_DEPTH_SIZE, (flags & ES_WINDOW_DEPTH) ? 8 : EGL_DONT_CARE,
EGL_STENCIL_SIZE, (flags & ES_WINDOW_STENCIL) ? 8 : EGL_DONT_CARE,
EGL_SAMPLE_BUFFERS, (flags & ES_WINDOW_MULTISAMPLE) ? 1 : 0,
// if EGL_KHR_create_context extension is supported, then we will use
// EGL_OPENGL_ES3_BIT_KHR instead of EGL_OPENGL_ES2_BIT in the attribute list
EGL_RENDERABLE_TYPE, GetContextRenderableType(esContext->eglDisplay),
EGL_NONE
};
// Choose config
if (!eglChooseConfig(esContext->eglDisplay, attribList, &config, 1, &numConfigs)) {
return GL_FALSE;
}
if (numConfigs < 1) {
return GL_FALSE;
}
}
#ifdef ANDROID
// For Android, need to get the EGL_NATIVE_VISUAL_ID and set it using ANativeWindow_setBuffersGeometry
{
EGLint format = 0;
eglGetConfigAttrib ( esContext->eglDisplay, config, EGL_NATIVE_VISUAL_ID, &format );
ANativeWindow_setBuffersGeometry ( esContext->eglNativeWindow, 0, 0, format );
}
#endif // ANDROID
// Create a surface
esContext->eglSurface = eglCreateWindowSurface(esContext->eglDisplay, config,
esContext->eglNativeWindow, NULL);
if (esContext->eglSurface == EGL_NO_SURFACE) {
return GL_FALSE;
}
// Create a GL context
esContext->eglContext = eglCreateContext(esContext->eglDisplay, config,
EGL_NO_CONTEXT, contextAttribs);
if (esContext->eglContext == EGL_NO_CONTEXT) {
return GL_FALSE;
}
// Make the context current
if (!eglMakeCurrent(esContext->eglDisplay, esContext->eglSurface,
esContext->eglSurface, esContext->eglContext)) {
return GL_FALSE;
}
#endif // #ifndef __APPLE__
return GL_TRUE;
}
///
// esRegisterDrawFunc()
//
void ESUTIL_API esRegisterDrawFunc(ESContext *esContext, void ( ESCALLBACK *drawFunc )(ESContext *)) {
esContext->drawFunc = drawFunc;
}
///
// esRegisterShutdownFunc()
//
void ESUTIL_API esRegisterShutdownFunc(ESContext *esContext, void ( ESCALLBACK *shutdownFunc )(ESContext *)) {
esContext->shutdownFunc = shutdownFunc;
}
///
// esRegisterUpdateFunc()
//
void ESUTIL_API esRegisterUpdateFunc(ESContext *esContext, void ( ESCALLBACK *updateFunc )(ESContext *, float)) {
esContext->updateFunc = updateFunc;
}
///
// esRegisterKeyFunc()
//
void ESUTIL_API esRegisterKeyFunc(ESContext *esContext,
void ( ESCALLBACK *keyFunc )(ESContext *, unsigned char, int, int)) {
esContext->keyFunc = keyFunc;
}
///
// esLogMessage()
//
// Log an error message to the debug output for the platform
//
void ESUTIL_API esLogMessage(const char *formatStr, ...) {
va_list params;
char buf[BUFSIZ];
va_start (params, formatStr);
vsprintf(buf, formatStr, params);
#ifdef ANDROID
__android_log_print ( ANDROID_LOG_INFO, "esUtil" , "%s", buf );
#else
printf("%s", buf);
#endif
va_end (params);
}
///
// esFileRead()
//
// Wrapper for platform specific File open
//
static esFile *esFileOpen(void *ioContext, const char *fileName) {
esFile *pFile = NULL;
#ifdef ANDROID
if ( ioContext != NULL )
{
AAssetManager *assetManager = ( AAssetManager * ) ioContext;
pFile = AAssetManager_open ( assetManager, fileName, AASSET_MODE_BUFFER );
}
#else
#ifdef __APPLE__
// iOS: Remap the filename to a path that can be opened from the bundle.
fileName = GetBundleFileName ( fileName );
#endif
pFile = fopen(fileName, "rb");
#endif
return pFile;
}
///
// esFileRead()
//
// Wrapper for platform specific File close
//
static void esFileClose(esFile *pFile) {
if (pFile != NULL) {
#ifdef ANDROID
AAsset_close ( pFile );
#else
fclose(pFile);
pFile = NULL;
#endif
}
}
///
// esFileRead()
//
// Wrapper for platform specific File read
//
static int esFileRead(esFile *pFile, int bytesToRead, void *buffer) {
int bytesRead = 0;
if (pFile == NULL) {
return bytesRead;
}
#ifdef ANDROID
bytesRead = AAsset_read ( pFile, buffer, bytesToRead );
#else
bytesRead = fread(buffer, bytesToRead, 1, pFile);
#endif
return bytesRead;
}
static long esFileGetLength(esFile *pFile) {
long length;
#ifdef ANDROID
length = AAsset_getLength(pFile);
#else
fseek(pFile, 0, SEEK_END);
length = ftell(pFile);
fseek(pFile, 0, SEEK_SET);
#endif
return length;
}
static int esFileSeek(esFile *pFile, long offset, int origin) {
int pos = 0;
if (pFile == NULL) {
return pos;
}
#ifdef ANDROID
pos = AAsset_seek ( pFile, offset, origin );
#else
pos = fseek(pFile, offset, origin);
#endif
return pos;
}
///
// esLoadImage()
//
// Loads a 8-bit, 24-bit or 32-bit image from a file
//
unsigned char *ESUTIL_API esLoadImage(void *ioContext, const char *fileName, int *width, int *height,
int *channels_in_file) {
// Open the file for reading
esFile *fp = esFileOpen(ioContext, fileName);
if (fp == NULL) {
// Log error as 'error in opening the input file from apk'
esLogMessage("esLoadImage FAILED to load : { %s }\n", fileName);
return NULL;
}
unsigned char *buffer = stbi_load_from_file(fp, width, height, channels_in_file, 0);
esFileClose(fp);
return buffer;
}
//
///
/// \brief Load a shader, check for compile errors, print error messages to output log
/// \param type Type of shader (GL_VERTEX_SHADER or GL_FRAGMENT_SHADER)
/// \param shaderSrc Shader source string
/// \return A new shader object on success, 0 on failure
//
GLuint ESUTIL_API esLoadShader(GLenum type, const char *shaderSrc) {
GLuint shader;
GLint compiled;
// Create the shader object
shader = glCreateShader(type);
if (shader == 0) {
return 0;
}
// Load the shader source
glShaderSource(shader, 1, &shaderSrc, NULL);
// Compile the shader
glCompileShader(shader);
// Check the compile status
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint infoLen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen > 1) {
char *infoLog = (char *) (malloc(sizeof(char) * infoLen));
glGetShaderInfoLog(shader, infoLen, NULL, infoLog);
esLogMessage("Error compiling shader:\n%s\n", infoLog);
free(infoLog);
}
glDeleteShader(shader);
return 0;
}
return shader;
}
//
///
/// \brief Load a vertex and fragment shader, create a program object, link program.
// Errors output to log.
/// \param vertShaderSrc Vertex shader source code
/// \param fragShaderSrc Fragment shader source code
/// \return A new program object linked with the vertex/fragment shader pair, 0 on failure
//
GLuint ESUTIL_API esLoadProgram(const char *vertShaderSrc, const char *fragShaderSrc) {
GLuint vertexShader;
GLuint fragmentShader;
GLuint programObject;
GLint linked;
// Load the vertex/fragment shaders
vertexShader = esLoadShader(GL_VERTEX_SHADER, vertShaderSrc);
if (vertexShader == 0) {
return 0;
}
fragmentShader = esLoadShader(GL_FRAGMENT_SHADER, fragShaderSrc);
if (fragmentShader == 0) {
glDeleteShader(vertexShader);
return 0;
}
// Create the program object
programObject = glCreateProgram();
if (programObject == 0) {
return 0;
}
glAttachShader(programObject, vertexShader);
glAttachShader(programObject, fragmentShader);
// Link the program
glLinkProgram(programObject);
// Check the link status
glGetProgramiv(programObject, GL_LINK_STATUS, &linked);
if (!linked) {
GLint infoLen = 0;
glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen > 1) {
char *infoLog = (char *) (malloc(sizeof(char) * infoLen));
glGetProgramInfoLog(programObject, infoLen, NULL, infoLog);
esLogMessage("Error linking program:\n%s\n", infoLog);
free(infoLog);
}
glDeleteProgram(programObject);
return 0;
}
// Free up no longer needed shader resources
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return programObject;
}
bool ESUTIL_API esGenerateTexture(Texture *texture) {
if ((texture->width >= MaxSlideLimit || texture->height >= MaxSlideLimit))
return kFailure;
GLint filtering = texture->filter == TEXTURE_FILTER_LINEAR ? GL_LINEAR : GL_NEAREST;
GLint internal_format = 0;
GLenum format = 0;
int channel = 0;
switch (texture->format) {
case TEXTURE_FORMAT_RGBA:
internal_format = format = GL_RGBA;
channel = 4;
break;
case TEXTURE_FORMAT_RGB:
internal_format = format = GL_RGB;
channel = 3;
break;
case TEXTURE_FORMAT_LUMINANCE:
internal_format = format = GL_RED;
channel = 1;
break;
default:
esLogMessage("Error texture (%s) format.\n", texture->name);
return kFailure;
}
GLint wrap = GL_CLAMP_TO_EDGE;
switch (texture->wrap) {
case TEXTURE_WRAP_CLAMP:
wrap = GL_CLAMP_TO_EDGE;
break;
case TEXTURE_WRAP_REPEAT:
wrap = GL_REPEAT;
break;
case TEXTURE_WRAP_MIRRORED:
wrap = GL_MIRRORED_REPEAT;
break;
default:
return kFailure;
}
if (texture->channel != channel) {
esLogMessage("Error texture (%s) channel.\n", texture->name);
return kFailure;
}
glGenTextures(1, &texture->id);
glBindTexture(GL_TEXTURE_2D, texture->id);
glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture->width, texture->height, 0, format, GL_UNSIGNED_BYTE,
texture->data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap);
return kSuccess;
}
///
// Load texture from disk
//
bool ESUTIL_API esLoadTexture(void *ioContext, Texture *texture, const char *filename) {
texture->data = (unsigned char *) (esLoadImage(ioContext, filename, &texture->width,
&texture->height, &texture->channel));
if (texture->data == NULL) {
esLogMessage("Error loading (%s) image.\n", filename);
return kFailure;
}
bool ret = esGenerateTexture(texture);
free(texture->data);
texture->data = NULL;
return ret;
}
int ESUTIL_API esSaveTextureToPng(unsigned char *data, int width, int height, int channel, const char *filename) {
return stbi_write_png(filename, width, height, channel, data, 0);
}
| 28.3 | 119 | 0.649371 | [
"object",
"3d"
] |
71a6c44eda78dde95e296a1e665b97223ba98a35 | 3,966 | cpp | C++ | iriclib_riversurvey.cpp | kskinoue0612/iriclib_v4 | 8d6212247f43bb0b34dc99678a3cc028d6f9fc3a | [
"MIT"
] | null | null | null | iriclib_riversurvey.cpp | kskinoue0612/iriclib_v4 | 8d6212247f43bb0b34dc99678a3cc028d6f9fc3a | [
"MIT"
] | 15 | 2021-07-10T20:47:34.000Z | 2022-01-27T21:30:36.000Z | iriclib_riversurvey.cpp | kskinoue0612/iriclib_v4 | 8d6212247f43bb0b34dc99678a3cc028d6f9fc3a | [
"MIT"
] | 2 | 2021-07-06T04:33:56.000Z | 2021-08-30T03:50:02.000Z | #include <fstream>
#include <stdlib.h>
#include "iriclib_riversurvey.h"
#include "iriclib_bstream.h"
using namespace std;
using namespace iRICLib;
RiverPathPoint::RiverPathPoint()
{
nextPoint = 0;
gridSkip = 0;
}
RiverPathPoint::~RiverPathPoint()
{
if (nextPoint != 0){
delete nextPoint;
}
}
InputBStream& operator >> (InputBStream& stream, std::vector<double>& vec)
{
int size;
double val;
stream >> size;
vec.clear();
for (int i = 0; i < size; ++i){
stream >> val;
vec.push_back(val);
}
return stream;
}
InputBStream& operator >> (InputBStream& stream, RiverPathPoint& p)
{
int size;
stream >> p.name;
p.nameReal = atof(p.name.c_str());
stream >> p.positionX >> p.positionY;
stream >> p.directionX >> p.directionY;
stream >> p.leftShift;
stream >> size;
p.altitudes.clear();
for (int i = 0; i < size; ++i){
Altitude alt;
stream >> alt.position >> alt.height >> alt.active;
p.altitudes.push_back(alt);
}
stream >> p.fixedPointLSet;
if (p.fixedPointLSet != 0){
stream >> p.directionLX >> p.directionLY >> p.fixedPointLIndex;
}
stream >> p.fixedPointRSet;
if (p.fixedPointRSet != 0){
stream >> p.directionRX >> p.directionRY >> p.fixedPointRIndex;
}
stream >> p.gridSkip;
stream >> p.centerToLeftCtrlPoints;
stream >> p.centerToRightCtrlPoints;
stream >> p.centerLineCtrlPoints;
stream >> p.leftBankCtrlPoints;
stream >> p.rightBankCtrlPoints;
stream >> p.wseSpecified;
stream >> p.waterSurfaceElevation;
return stream;
}
OutputBStream& operator << (OutputBStream& stream, const std::vector<double>& vec)
{
stream << static_cast<int>(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i){
stream << vec.at(i);
}
return stream;
}
OutputBStream& operator << (OutputBStream& stream, const RiverPathPoint& p)
{
stream << p.name;
stream << p.positionX << p.positionY;
stream << p.directionX << p.directionY;
stream << p.leftShift;
stream << static_cast<int>(p.altitudes.size());
for (unsigned int i = 0; i < p.altitudes.size(); ++i){
Altitude alt = p.altitudes[i];
stream << alt.position << alt.height << alt.active;
}
stream << p.fixedPointLSet;
if (p.fixedPointLSet != 0){
stream << p.directionLX << p.directionLY << p.fixedPointLIndex;
}
stream << p.fixedPointRSet;
if (p.fixedPointRSet != 0){
stream << p.directionRX << p.directionRY << p.fixedPointRIndex;
}
stream << p.gridSkip;
stream << p.centerToLeftCtrlPoints;
stream << p.centerToRightCtrlPoints;
stream << p.centerLineCtrlPoints;
stream << p.leftBankCtrlPoints;
stream << p.rightBankCtrlPoints;
stream << p.wseSpecified;
stream << p.waterSurfaceElevation;
return stream;
}
RiverSurvey::RiverSurvey()
{
firstPoint = 0;
}
RiverSurvey::~RiverSurvey()
{
if (firstPoint != 0){
delete firstPoint;
}
}
int RiverSurvey::load(const char* filename)
{
ifstream istream(filename, ios::in | ios::binary);
if (! istream){
// open error
return -1;
}
InputBStream str(istream);
int size;
points.clear();
str >> size;
RiverPathPoint* p;
RiverPathPoint* prevP;
for (int i = 0; i < size; ++i){
p = new RiverPathPoint();
str >> *p;
if (i == 0){
firstPoint = p;
} else {
prevP->nextPoint = p;
}
points.push_back(p);
prevP = p;
}
istream.close();
return 0;
}
int RiverSurvey::save(const char* filename)
{
ofstream ostream(filename, ios::out | ios::binary);
if (! ostream){
// open error
return -1;
}
OutputBStream str(ostream);
points.clear();
RiverPathPoint* p;
if (firstPoint != 0){
points.push_back(firstPoint);
p = firstPoint;
while (p->nextPoint != 0){
p = p->nextPoint;
points.push_back(p);
}
}
str << static_cast<int>(points.size());
for (unsigned int i = 0; i < points.size(); ++i){
RiverPathPoint* p = points[i];
str << *p;
}
ostream.close();
return 0;
}
| 21.911602 | 83 | 0.632879 | [
"vector"
] |
71a6e705f16df597d5f92cce4f1308476f2c40c1 | 718 | hpp | C++ | polygon.hpp | xialiangzhen/3d-image-synthesis | ccbd8be4be0114479228dfd7c19ef47087d4ad01 | [
"BSD-3-Clause"
] | null | null | null | polygon.hpp | xialiangzhen/3d-image-synthesis | ccbd8be4be0114479228dfd7c19ef47087d4ad01 | [
"BSD-3-Clause"
] | null | null | null | polygon.hpp | xialiangzhen/3d-image-synthesis | ccbd8be4be0114479228dfd7c19ef47087d4ad01 | [
"BSD-3-Clause"
] | null | null | null | //
// polygon.hpp
// demo
//
// Created by 夏 夏 on 16/3/30.
// Copyright © 2016年 Liangzhen Xia. All rights reserved.
//
#ifndef polygon_hpp
#define polygon_hpp
#include <stdio.h>
#include "object.hpp"
class polygon: public object
{
public:
vector<triangle> triangles;
vector<triangle> triangles0;
int intersection;
polygon(string filePath);
bool inObject(cyPoint3f p);
cyPoint3f normalVector(cyPoint3f ph);
double miniIntersection(cyPoint3f pe, cyPoint3f npe);
cyColor getColor(vector<light> alllights, cyPoint3f ph, cyPoint3f pe, vector<object*> allobjects);
void getIORfromTexture(cyPoint3f ph);
void translation(cyPoint3f moveVector);
};
#endif /* polygon_hpp */
| 22.4375 | 102 | 0.711699 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.